clouds-coder 2026.11.29__tar.gz → 2026.12.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/Clouds_Coder.py +2051 -261
  2. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/PKG-INFO +1 -1
  3. clouds_coder-2026.11.29/split_coder.py → clouds_coder-2026.12.4/Split Tools/split_coder.py +4 -0
  4. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/clouds_coder.egg-info/PKG-INFO +1 -1
  5. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/clouds_coder.egg-info/SOURCES.txt +3 -0
  6. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/pyproject.toml +1 -1
  7. clouds_coder-2026.11.29/Split Tools/split_coder.py → clouds_coder-2026.12.4/split_coder.py +4 -0
  8. clouds_coder-2026.12.4/tests/test_goal_mode.py +366 -0
  9. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_model_configuration.py +87 -3
  10. clouds_coder-2026.12.4/tests/test_service_logos.py +82 -0
  11. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_single_no_plan_todo_bootstrap.py +22 -0
  12. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_skill_execution_permissions.py +73 -0
  13. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_split_distribution.py +8 -0
  14. clouds_coder-2026.12.4/tests/test_user_bubbles_after_compact.py +118 -0
  15. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_web_ui_export.py +15 -0
  16. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/.github/workflows/python-app.yml +0 -0
  17. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/.github/workflows/python-publish.yml +0 -0
  18. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/LICENSE +0 -0
  19. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/MANIFEST.in +0 -0
  20. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/README-ja.md +0 -0
  21. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/README-zh.md +0 -0
  22. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/README.md +0 -0
  23. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/RELEASE_NOTES.md +0 -0
  24. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/Split Tools/run_split.bat +0 -0
  25. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/Split Tools/run_split.command +0 -0
  26. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/Split Tools/run_split.py +0 -0
  27. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/Split Tools/run_split.sh +0 -0
  28. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/clouds_coder.egg-info/dependency_links.txt +0 -0
  29. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/clouds_coder.egg-info/entry_points.txt +0 -0
  30. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/clouds_coder.egg-info/requires.txt +0 -0
  31. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/clouds_coder.egg-info/top_level.txt +0 -0
  32. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/docs/liquid_kernel_delivery_verification_20261030.md +0 -0
  33. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/liquid_kernel/README.md +0 -0
  34. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/liquid_kernel/__init__.py +0 -0
  35. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/liquid_kernel/agentic.py +0 -0
  36. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/liquid_kernel/context.py +0 -0
  37. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/liquid_kernel/control.py +0 -0
  38. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/liquid_kernel/execution.py +0 -0
  39. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/liquid_kernel/models.py +0 -0
  40. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/log/CHANGELOG-2026-03-07.md +0 -0
  41. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/log/CHANGELOG-2026-03-16.md +0 -0
  42. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/log/CHANGELOG-2026-03-20.md +0 -0
  43. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/log/CHANGELOG-2026-03-25.md +0 -0
  44. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/log/CHANGELOG-2026-03-31.md +0 -0
  45. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/log/CHANGELOG-2026-05-02.md +0 -0
  46. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/log/CHANGELOG-2026-05-28.md +0 -0
  47. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/log/CHANGELOG-2026-06-05.md +0 -0
  48. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/log/CHANGELOG-2026-06-22.md +0 -0
  49. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/log/CHANGELOG-2026-08-10.md +0 -0
  50. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/log/CHANGELOG-2026-08-16.md +0 -0
  51. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/log/CHANGELOG-2026-08-20.md +0 -0
  52. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/log/CHANGELOG-2026-09-12.md +0 -0
  53. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/log/CHANGELOG-2026-10-30.md +0 -0
  54. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/log/CHANGELOG-2026-11-01.md +0 -0
  55. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/log/CHANGELOG-2026-11-04.md +0 -0
  56. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/log/CHANGELOG-2026-11-28.md +0 -0
  57. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/log/CHANGELOG-2026-11-29.md +0 -0
  58. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/requirements.txt +0 -0
  59. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/ruff.toml +0 -0
  60. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/setup.cfg +0 -0
  61. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/UPLOAD_NOTES.md +0 -0
  62. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/conftest.py +0 -0
  63. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/fixtures/skills/shader-dev/SKILL.md +0 -0
  64. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_acceptance_portability.py +0 -0
  65. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_admin_bootstrap_compatibility.py +0 -0
  66. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_admin_i18n.py +0 -0
  67. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_admin_output_limits.py +0 -0
  68. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_agentic_evolution.py +0 -0
  69. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_agentic_flow_compatibility.py +0 -0
  70. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_authoritative_prompt_delivery.py +0 -0
  71. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_cache_runtime.py +0 -0
  72. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_candidate_retention.py +0 -0
  73. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_collaboration.py +0 -0
  74. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_context_auto_compact.py +0 -0
  75. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_context_memory_recall.py +0 -0
  76. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_cross_platform_runtime.py +0 -0
  77. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_dynamic_agent_loop.py +0 -0
  78. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_effort_probe.py +0 -0
  79. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_evaluator_transport_defenses.py +0 -0
  80. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_evolution_browser.py +0 -0
  81. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_evolution_integration.py +0 -0
  82. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_evolution_policy_safety.py +0 -0
  83. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_evolution_progress.py +0 -0
  84. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_external_skill_permissions.py +0 -0
  85. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_http_incomplete_read.py +0 -0
  86. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_ide_v2.py +0 -0
  87. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_json_restart_defenses.py +0 -0
  88. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_kernel_bootstrap.py +0 -0
  89. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_kernel_restart_persistence.py +0 -0
  90. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_kimi_tool_history_compat.py +0 -0
  91. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_l3_l4_todo_runtime.py +0 -0
  92. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_liquid_kernel.py +0 -0
  93. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_live_harness_repairs.py +0 -0
  94. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_long_content_enrichment_pileup.py +0 -0
  95. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_mcp_workspace_trust.py +0 -0
  96. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_native_output_recovery.py +0 -0
  97. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_network_change_notice.py +0 -0
  98. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_optimization_opportunities.py +0 -0
  99. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_optional_evolution_quotas.py +0 -0
  100. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_outcome_scoring.py +0 -0
  101. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_pair_deployment_policy.py +0 -0
  102. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_plan_structure.py +0 -0
  103. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_plan_todo_progression.py +0 -0
  104. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_portable_capabilities.py +0 -0
  105. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_process_manager.py +0 -0
  106. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_prompt_enhancement_recovery.py +0 -0
  107. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_proposal_schema_recovery.py +0 -0
  108. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_rag_admin_auth.py +0 -0
  109. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_read_compaction_visibility.py +0 -0
  110. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_requirements_coverage.py +0 -0
  111. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_screenshot_regressions.py +0 -0
  112. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_semantic_task_routing.py +0 -0
  113. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_session_llm_concurrency.py +0 -0
  114. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_session_performance.py +0 -0
  115. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_shared_context_runtime.py +0 -0
  116. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_shell_timeout_modes.py +0 -0
  117. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_skill_selection.py +0 -0
  118. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_skills_studio_v2.py +0 -0
  119. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_sqlite_connection_lifecycle.py +0 -0
  120. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_step_skill_runtime.py +0 -0
  121. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_sync_routing_scope.py +0 -0
  122. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_thinking_only_recovery.py +0 -0
  123. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_todo_finish_mode_matrix.py +0 -0
  124. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_todo_llm_budget.py +0 -0
  125. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_todo_no_progress.py +0 -0
  126. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_todo_short_ids.py +0 -0
  127. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_todo_tree_revision_guard.py +0 -0
  128. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_todo_update_recovery.py +0 -0
  129. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_ui_language.py +0 -0
  130. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_web_search_local_graph.py +0 -0
  131. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tests/test_web_search_public_discovery.py +0 -0
  132. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tools/__init__.py +0 -0
  133. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tools/inspect_evolution_progress.py +0 -0
  134. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tools/sync_liquid_kernel_bundle.py +0 -0
  135. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tools/verify_admin_restart_real.py +0 -0
  136. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tools/verify_context_runtime_real.py +0 -0
  137. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tools/verify_evolution_entrypoint.py +0 -0
  138. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tools/verify_evolution_progress_real.py +0 -0
  139. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tools/verify_evolution_real.py +0 -0
  140. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tools/verify_frozen_review_real.py +0 -0
  141. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tools/verify_json_semantic_real.py +0 -0
  142. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tools/verify_model_compatibility_real.py +0 -0
  143. {clouds_coder-2026.11.29 → clouds_coder-2026.12.4}/tools/verify_transport_parity_real.py +0 -0
@@ -5920,6 +5920,26 @@ DEFAULT_SINGLE_NO_PLAN_TODO_PROMPT = (
5920
5920
  "evidence, and do not implement or modify files in this turn. Do not "
5921
5921
  "invent unrelated work or switch to plan mode."
5922
5922
  )
5923
+ TODO_PREPARATION_ARGUMENT_EXAMPLE = (
5924
+ '{"goal":"brief understood objective","state":"relevant observed or user-provided state",'
5925
+ '"skills":"selection or reason no skill is relevant","basis":"observed_context",'
5926
+ '"ready":true,"missing":[]}'
5927
+ )
5928
+ SINGLE_NO_PLAN_TODO_PREPARATION_INSTRUCTION = (
5929
+ "Include the top-level preparation object alongside the Todo items in the same tool call: "
5930
+ + TODO_PREPARATION_ARGUMENT_EXAMPLE
5931
+ + ". Replace the example values with your actual assessment. "
5932
+ "Use user_context, observed_context, or continuation for basis. "
5933
+ "If the provider cannot emit a tool call, return the same structured call as JSON "
5934
+ 'with name="TodoWrite" and an arguments object containing preparation and items.'
5935
+ )
5936
+ SINGLE_NO_PLAN_TODO_OBSERVATION_RETRY = (
5937
+ "Preparation is still open. Change the read-only probe based on the tool error. "
5938
+ 'For files or libraries, prefer read_file with mode="directory" and a virtual path '
5939
+ 'such as "/workspace" or "/js_lib"; for skills, use list_skills. '
5940
+ "If the remaining check belongs to execution and the goal is understood, make that check "
5941
+ "the first in_progress Todo and submit the preparation assessment."
5942
+ )
5923
5943
  SINGLE_NO_PLAN_TODO_BOOTSTRAP_MAX_ATTEMPTS = 2
5924
5944
  # A first Todo list whose preparation still names gaps is sent back this many
5925
5945
  # times. The next submission is accepted with the gaps kept on record, so a
@@ -6058,6 +6078,49 @@ MANAGER_CTX_LIMIT_TIER3 = 40
6058
6078
  MAX_CONTEXT_ARCHIVE_SEGMENTS = 1200
6059
6079
  # Display-only retained user bubbles (frontend persistence; not LLM context).
6060
6080
  MAX_USER_BUBBLE_LOG = 600
6081
+ # The user's own messages stay in every feed window. Tool, status and model
6082
+ # rows fill the rest; user messages outside the tail window are added back,
6083
+ # newest first, within these counts and byte budgets.
6084
+ UI_PINNED_USER_ROWS_LITE = 100
6085
+ UI_PINNED_USER_ROWS_FULL = 400
6086
+ UI_PINNED_USER_ROWS_BYTES = 128 * 1024
6087
+ UI_PINNED_USER_ROWS_IDE = 80
6088
+ UI_PINNED_USER_ROWS_IDE_BYTES = 96 * 1024
6089
+ # Compaction leaves this user-role marker where an earlier resume note was.
6090
+ UI_COMPACT_RESUME_ARCHIVED_MARKER = "[previous compact-resume archived"
6091
+ # Goal mode: one completion condition per session. After every run a separate
6092
+ # evaluator call judges the condition from the run's evidence; while it is not
6093
+ # met the session starts the next turn itself, within these budgets.
6094
+ GOAL_OBJECTIVE_MAX_CHARS = 4000
6095
+ # A goal turn is one whole run (each run may use up to max_rounds model rounds),
6096
+ # so its budget is a separate admin setting (--goal_turns) rather than max_rounds.
6097
+ GOAL_DEFAULT_MAX_TURNS = 30
6098
+ GOAL_MAX_TURNS_LIMIT = 500
6099
+ GOAL_TOKEN_BUDGET_LIMIT = 10_000_000_000
6100
+ GOAL_TIME_BUDGET_LIMIT_SECONDS = 30 * 24 * 3600
6101
+ GOAL_PREFERENCE_KEYS = ("max_turns", "token_budget", "time_budget_seconds", "allow_model_proposals")
6102
+ # Answer values of an ask_user goal proposal; the labels are localized.
6103
+ GOAL_PROPOSAL_ACCEPT = "Yes, set this as the goal"
6104
+ GOAL_PROPOSAL_DECLINE = "No, continue without a goal"
6105
+ GOAL_PROPOSAL_LABELS = {
6106
+ "zh-CN": ("设为目标", "不设目标,继续"),
6107
+ "zh-TW": ("設為目標", "不設目標,繼續"),
6108
+ "ja": ("ゴールに設定する", "ゴールを設定せずに続ける"),
6109
+ "en": ("Set as goal", "Continue without a goal"),
6110
+ }
6111
+ GOAL_STATUSES = ("active", "paused", "complete", "impossible", "budget_limited")
6112
+ GOAL_TERMINAL_STATUSES = ("complete", "impossible", "budget_limited")
6113
+ GOAL_EVALUATOR_TIMEOUT_SECONDS = 120.0
6114
+ GOAL_EVALUATOR_MAX_TOKENS = 900
6115
+ GOAL_EVALUATOR_ATTEMPTS = 2
6116
+ GOAL_EVIDENCE_MAX_CHARS = 28000
6117
+ GOAL_VERDICT_HISTORY_MAX = 24
6118
+ # Consecutive turns without a tool call, failed runs or failed evaluations
6119
+ # after which the goal pauses for the user instead of continuing.
6120
+ GOAL_NO_PROGRESS_PAUSE_TURNS = 3
6121
+ GOAL_ERROR_PAUSE_TURNS = 3
6122
+ GOAL_EVALUATION_FAILURE_PAUSE = 3
6123
+ GOAL_CONTINUATION_TAG = "goal-continuation"
6061
6124
  # Manager->worker instruction budget. The old 1200/1400 cap forced the manager to
6062
6125
  # paraphrase the full goal + current step + failure context + concrete action into
6063
6126
  # ~200 tokens, dropping error traces and constraints — a major cause of poor
@@ -7067,8 +7130,8 @@ MEDIA_CAPABILITY_KEYS = {
7067
7130
  }
7068
7131
 
7069
7132
 
7070
- def _capability_probe_png_bytes() -> bytes:
7071
- """Return a deterministic, valid 1x1 PNG for provider capability probes."""
7133
+ def _capability_probe_png_bytes(color: tuple[int, int, int] | None = None) -> bytes:
7134
+ """Return a transparent placeholder or a solid-color probe image."""
7072
7135
  def chunk(kind: bytes, payload: bytes) -> bytes:
7073
7136
  return (
7074
7137
  struct.pack(">I", len(payload))
@@ -7077,26 +7140,46 @@ def _capability_probe_png_bytes() -> bytes:
7077
7140
  + struct.pack(">I", zlib.crc32(kind + payload) & 0xFFFFFFFF)
7078
7141
  )
7079
7142
 
7080
- header = struct.pack(">IIBBBBB", 1, 1, 8, 6, 0, 0, 0)
7081
- pixels = zlib.compress(b"\x00\x00\x00\x00\x00")
7143
+ if color is None:
7144
+ header = struct.pack(">IIBBBBB", 1, 1, 8, 6, 0, 0, 0)
7145
+ pixels = zlib.compress(b"\x00\x00\x00\x00\x00")
7146
+ else:
7147
+ header = struct.pack(">IIBBBBB", 64, 64, 8, 2, 0, 0, 0)
7148
+ pixels = zlib.compress((b"\x00" + bytes(color) * 64) * 64)
7082
7149
  return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", header) + chunk(b"IDAT", pixels) + chunk(b"IEND", b"")
7083
7150
 
7084
7151
 
7085
7152
  def _capability_probe_audio_bytes() -> bytes:
7086
- """Return a valid, empty PCM/WAV payload for provider capability probes."""
7153
+ """Return a quarter-second PCM/WAV tone."""
7154
+ samples = bytes(round(128 + 80 * math.sin(math.tau * 440 * i / 8000)) for i in range(2000))
7087
7155
  return (
7088
7156
  b"RIFF"
7089
- + struct.pack("<I", 36)
7157
+ + struct.pack("<I", 36 + len(samples))
7090
7158
  + b"WAVEfmt "
7091
7159
  + struct.pack("<IHHIIHH", 16, 1, 1, 8000, 8000, 1, 8)
7092
7160
  + b"data"
7093
- + struct.pack("<I", 0)
7161
+ + struct.pack("<I", len(samples))
7162
+ + samples
7094
7163
  )
7095
7164
 
7096
7165
 
7097
7166
  def _capability_probe_video_bytes() -> bytes:
7098
- """Return a minimal ISO-BMFF header for provider capability probes."""
7099
- return struct.pack(">I", 20) + b"ftypisom" + struct.pack(">I", 0) + b"isomiso2"
7167
+ """Return a half-second 16x16 red H.264 clip in a self-contained MP4."""
7168
+ return base64.b64decode(
7169
+ "AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAMMbW9vdgAAAGxtdmhkAAAAAAAAAAAAAAAAAAAD6AAAAfQAAQAA"
7170
+ "AQAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
7171
+ "AAAAAgAAAlt0cmFrAAAAXHRraGQAAAADAAAAAAAAAAAAAAABAAAAAAAAAfQAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAA"
7172
+ "AAAAAAABAAAAAAAAAAAAAAAAAABAAAAAABAAAAAQAAAAAAAkZWR0cwAAABxlbHN0AAAAAAAAAAEAAAH0AAAAAAABAAAAAAHT"
7173
+ "bWRpYQAAACBtZGhkAAAAAAAAAAAAAAAAAABAAAAAIABVxAAAAAAALWhkbHIAAAAAAAAAAHZpZGUAAAAAAAAAAAAAAABWaWRl"
7174
+ "b0hhbmRsZXIAAAABfm1pbmYAAAAUdm1oZAAAAAEAAAAAAAAAAAAAACRkaW5mAAAAHGRyZWYAAAAAAAAAAQAAAAx1cmwgAAAA"
7175
+ "AQAAAT5zdGJsAAAAtnN0c2QAAAAAAAAAAQAAAKZhdmMxAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAABAAEABIAAAASAAAAAAA"
7176
+ "AAABDExhdmMgbGlieDI2NAAAAAAAAAAAAAAAAAAAAAAAAAAAGP//AAAALGF2Y0MBQsAK/+EAFWdCwAraewEQAAADABAAAAMB"
7177
+ "APEiagEABGjOD8gAAAAQcGFzcAAAAAEAAAABAAAAFGJ0cnQAAAAAAAADIAAAAAAAAAAYc3R0cwAAAAAAAAABAAAABAAACAAA"
7178
+ "AAAUc3RzcwAAAAAAAAABAAAAAQAAABxzdHNjAAAAAAAAAAEAAAABAAAABAAAAAEAAAAkc3RzegAAAAAAAAAAAAAABAAAABcA"
7179
+ "AAAJAAAACQAAAAkAAAAUc3RjbwAAAAAAAAABAAADPAAAAD11ZHRhAAAANW1ldGEAAAAAAAAAIWhkbHIAAAAAAAAAAG1kaXJh"
7180
+ "cHBsAAAAAAAAAAAAAAAACGlsc3QAAAAIZnJlZQAAADptZGF0AAAAE2WIhDoRigACGPHAAED2OAAIeWAAAAAFQZogNpQAAAAF"
7181
+ "QZpAOpQAAAAFQZpgOpQ="
7182
+ )
7100
7183
 
7101
7184
  OFFLINE_JS_LIB_CATALOG: list[dict[str, object]] = [
7102
7185
  {
@@ -9208,6 +9291,24 @@ def merge_multimodal_capabilities(base: dict[str, bool], override: dict[str, boo
9208
9291
  return out
9209
9292
 
9210
9293
 
9294
+ def resolve_configured_media_capabilities(profile: dict, model: str) -> dict[str, bool]:
9295
+ if "capability_overrides" in profile:
9296
+ model_overrides = profile.get("model_capability_overrides") or {}
9297
+ return {
9298
+ **parse_capability_overrides(profile["capability_overrides"]),
9299
+ **parse_capability_overrides(model_overrides.get(model.casefold()) if isinstance(model_overrides, dict) else None),
9300
+ }
9301
+ # Older sessions saved heuristic defaults and explicit settings in one
9302
+ # map. Preserve values that differ from the original name-based defaults.
9303
+ if model != str(profile.get("model", "") or ""):
9304
+ return {}
9305
+ declared = parse_capability_overrides(profile.get("capabilities"))
9306
+ if len(declared) < len(MEDIA_CAPABILITY_KEYS):
9307
+ return declared
9308
+ defaults = infer_model_multimodal_capabilities(str(profile.get("provider", "") or ""), model)
9309
+ return {key: value for key, value in declared.items() if value != defaults[key]}
9310
+
9311
+
9211
9312
  def parse_media_endpoints(raw: object) -> dict[str, str]:
9212
9313
  obj = raw
9213
9314
  if isinstance(raw, str):
@@ -10629,6 +10730,73 @@ def _bounded_ui_rows(
10629
10730
  return selected, len(selected) < len(source)
10630
10731
 
10631
10732
 
10733
+ def _bounded_ui_is_pinned(row: object) -> bool:
10734
+ """A message the user wrote; feed windows and byte budgets keep it."""
10735
+ return isinstance(row, dict) and bool(row.get("user_input"))
10736
+
10737
+
10738
+ def _bounded_ui_row_identity(row: dict) -> str:
10739
+ identity = str(row.get("id", "") or "").strip()
10740
+ if identity:
10741
+ return identity
10742
+ return f"{row.get('ts', 0)}|{row.get('role', '')}|{str(row.get('text', '') or '')[:80]}"
10743
+
10744
+
10745
+ def _bounded_ui_feed_window(rows: object, window: int, pin_limit: int) -> list[dict]:
10746
+ """Tail window of a feed in time order that still holds the user's messages."""
10747
+ source = [row for row in (list(rows) if isinstance(rows, (list, tuple, deque)) else []) if isinstance(row, dict)]
10748
+ window = max(1, int(window or 1))
10749
+ tail = source[-window:]
10750
+ if len(source) <= window or int(pin_limit or 0) <= 0:
10751
+ return tail
10752
+ older = [row for row in source[:-window] if _bounded_ui_is_pinned(row)]
10753
+ return older[-int(pin_limit):] + tail
10754
+
10755
+
10756
+ def _bounded_ui_feed_rows(
10757
+ rows: object,
10758
+ *,
10759
+ max_rows: int,
10760
+ byte_budget: int,
10761
+ pin_limit: int,
10762
+ pin_budget: int,
10763
+ text_limit: int = 2800,
10764
+ data_text_limit: int = 1200,
10765
+ collection_limit: int = 24,
10766
+ keep: str = "tail",
10767
+ ) -> tuple[list[dict], bool]:
10768
+ """Bound a conversation feed like _bounded_ui_rows and keep the user's messages.
10769
+
10770
+ The newest rows fill the window as before. User messages outside it are
10771
+ added back, newest first, within pin_limit rows and pin_budget bytes. The
10772
+ result keeps feed order. A head window (cursor paging) is left as it is.
10773
+ """
10774
+ source = [row for row in (list(rows) if isinstance(rows, (list, tuple, deque)) else []) if isinstance(row, dict)]
10775
+ limits = {"text_limit": text_limit, "data_text_limit": data_text_limit, "collection_limit": collection_limit}
10776
+ bounded, truncated = _bounded_ui_rows(source, max_rows=max_rows, byte_budget=byte_budget, keep=keep, **limits)
10777
+ if keep == "head" or int(pin_limit or 0) <= 0:
10778
+ return bounded, truncated
10779
+ kept = {_bounded_ui_row_identity(row) for row in bounded}
10780
+ missing = [row for row in source if _bounded_ui_is_pinned(row) and _bounded_ui_row_identity(row) not in kept]
10781
+ if not missing:
10782
+ return bounded, truncated
10783
+ pinned, _ = _bounded_ui_rows(missing, max_rows=int(pin_limit), byte_budget=pin_budget, **limits)
10784
+ order = {_bounded_ui_row_identity(row): index for index, row in enumerate(source)}
10785
+ merged = sorted(pinned + bounded, key=lambda row: order.get(_bounded_ui_row_identity(row), len(order)))
10786
+ return merged, truncated
10787
+
10788
+
10789
+ def _bounded_ui_drop_oldest(rows: list, count: int) -> list:
10790
+ """Drop the oldest feed rows; the user's own messages go last."""
10791
+ count = max(0, int(count or 0))
10792
+ unpinned = [index for index, row in enumerate(rows) if not _bounded_ui_is_pinned(row)]
10793
+ drop = set(unpinned[:count])
10794
+ if len(drop) < count:
10795
+ pinned = [index for index, row in enumerate(rows) if _bounded_ui_is_pinned(row)]
10796
+ drop.update(pinned[: count - len(drop)])
10797
+ return [row for index, row in enumerate(rows) if index not in drop]
10798
+
10799
+
10632
10800
  def _enforce_ui_payload_budget(payload: dict, byte_budget: int) -> dict:
10633
10801
  byte_budget = max(64 * 1024, int(byte_budget or 0))
10634
10802
  try:
@@ -10665,7 +10833,10 @@ def _enforce_ui_payload_budget(payload: dict, byte_budget: int) -> dict:
10665
10833
  value = list(payload.get(key, []))
10666
10834
  minimum = minimums[key]
10667
10835
  remove = max(1, (len(value) - minimum + 1) // 2)
10668
- payload[key] = value[remove:]
10836
+ if key in ("conversation_feed", "feed"):
10837
+ payload[key] = _bounded_ui_drop_oldest(value, remove)
10838
+ else:
10839
+ payload[key] = value[remove:]
10669
10840
  for key in ("live_thinking", "live_response_text", "live_truncation_text", "recovered_reason"):
10670
10841
  if key in payload:
10671
10842
  payload[key], truncated = _ui_trim_text(payload.get(key, ""), 512)
@@ -10691,14 +10862,26 @@ def _apply_lite_snapshot_bounds(payload: dict) -> dict:
10691
10862
  window_meta: dict[str, dict] = {}
10692
10863
  for key, max_rows, budget, text_limit, data_limit, collection_limit in windows:
10693
10864
  source = payload.get(key, [])
10694
- bounded, truncated = _bounded_ui_rows(
10695
- source,
10696
- max_rows=max_rows,
10697
- byte_budget=budget,
10698
- text_limit=text_limit,
10699
- data_text_limit=data_limit,
10700
- collection_limit=collection_limit,
10701
- )
10865
+ if key == "conversation_feed":
10866
+ bounded, truncated = _bounded_ui_feed_rows(
10867
+ source,
10868
+ max_rows=max_rows,
10869
+ byte_budget=budget,
10870
+ pin_limit=UI_PINNED_USER_ROWS_LITE,
10871
+ pin_budget=UI_PINNED_USER_ROWS_BYTES,
10872
+ text_limit=text_limit,
10873
+ data_text_limit=data_limit,
10874
+ collection_limit=collection_limit,
10875
+ )
10876
+ else:
10877
+ bounded, truncated = _bounded_ui_rows(
10878
+ source,
10879
+ max_rows=max_rows,
10880
+ byte_budget=budget,
10881
+ text_limit=text_limit,
10882
+ data_text_limit=data_limit,
10883
+ collection_limit=collection_limit,
10884
+ )
10702
10885
  payload[key] = bounded
10703
10886
  window_meta[key] = {
10704
10887
  "returned": len(bounded),
@@ -10763,7 +10946,7 @@ def ide_public_operation_data(data: object) -> dict:
10763
10946
  "reason": 600, "archive_segment": 240, "next_call_label": 240,
10764
10947
  "control_tag": 120, "origin": 80, "title": 240, "details": 8000,
10765
10948
  "session_title": 240, "title_origin": 40,
10766
- "public_progress": 4000,
10949
+ "public_progress": 4000, "phase": 40, "verdict": 20, "next_step": 400,
10767
10950
  }
10768
10951
  for key, limit in text_limits.items():
10769
10952
  if key in source:
@@ -10781,10 +10964,21 @@ def ide_public_operation_data(data: object) -> dict:
10781
10964
  "context_used_before", "context_left_before", "context_left_percent_before",
10782
10965
  "context_used_after", "context_left_after", "context_left_percent_after",
10783
10966
  "context_used_reduction", "matched_rows", "returned", "total_rows",
10784
- "title_revision", "dropped_total",
10967
+ "title_revision", "dropped_total", "turn", "tool_calls",
10785
10968
  ):
10786
10969
  if key in source:
10787
10970
  public[key] = source.get(key)
10971
+ if isinstance(source.get("goal"), dict):
10972
+ goal = source["goal"]
10973
+ public["goal"] = {
10974
+ key: (trim(str(goal.get(key, "") or ""), 4000) if key in {"objective", "status", "status_reason", "id"} else goal.get(key))
10975
+ for key in (
10976
+ "id", "objective", "status", "status_reason", "turns", "max_turns", "tokens_used",
10977
+ "token_budget", "time_used_seconds", "time_budget_seconds", "active_since", "evaluating",
10978
+ "time_banked_seconds",
10979
+ )
10980
+ if key in goal
10981
+ }
10788
10982
  if "effective" in source:
10789
10983
  public["effective"] = bool(source.get("effective"))
10790
10984
  if "default_collapsed" in source:
@@ -15147,6 +15341,21 @@ def extract_openai_compat_model_records(payload: object) -> list[dict]:
15147
15341
 
15148
15342
  def capability_hints(node: dict) -> dict:
15149
15343
  caps: dict = {}
15344
+ if str(node.get("model_type", "")).strip().lower() == "vlm":
15345
+ caps["input_image"] = True
15346
+ for vision_key in ("supports_vision", "vision"):
15347
+ if isinstance(node.get(vision_key), bool):
15348
+ caps["input_image"] = node[vision_key]
15349
+ break
15350
+ architecture = node.get("architecture")
15351
+ inputs = node.get("input_modalities") or (
15352
+ architecture.get("input_modalities") if isinstance(architecture, dict) else None
15353
+ )
15354
+ if isinstance(inputs, (list, tuple, set)):
15355
+ modalities = {str(value).strip().lower() for value in inputs}
15356
+ if modalities & {"text", "image", "audio", "video"}:
15357
+ caps.update({f"input_{kind}": kind in modalities for kind in ("image", "audio", "video")})
15358
+ caps.update(parse_capability_overrides(node))
15150
15359
  for key in ("reasoning_supported", "supports_reasoning", "reasoning", "thinking"):
15151
15360
  if key in node:
15152
15361
  raw = node.get(key)
@@ -15189,6 +15398,8 @@ def extract_openai_compat_model_records(payload: object) -> list[dict]:
15189
15398
  elif isinstance(raw_caps, (list, tuple, set)):
15190
15399
  nested = capability_hints({"supported_features": raw_caps})
15191
15400
  caps.update(nested)
15401
+ if any(str(value).strip().lower() in {"vision", "image_input", "input_image"} for value in raw_caps):
15402
+ caps.setdefault("input_image", True)
15192
15403
  return caps
15193
15404
 
15194
15405
  def walk(node: object, depth: int = 0):
@@ -15667,20 +15878,17 @@ def parse_llm_config_profiles(config: dict, default_ollama_url: str, default_oll
15667
15878
  out.append(key)
15668
15879
  return out
15669
15880
 
15670
- def build_profile_capabilities(provider_key: str, provider: str, model: str) -> dict[str, bool]:
15671
- caps = infer_model_multimodal_capabilities(provider, model)
15672
- if any(k in raw_global_caps for k in MEDIA_CAPABILITY_KEYS):
15673
- caps = merge_multimodal_capabilities(caps, parse_capability_overrides(raw_global_caps))
15881
+ configured_model_capabilities = {
15882
+ str(model).strip().casefold(): caps
15883
+ for model, values in model_caps_map.items()
15884
+ if str(model).strip() and (caps := parse_capability_overrides(values))
15885
+ }
15886
+
15887
+ def build_provider_capability_overrides(provider_key: str, provider: str) -> dict[str, bool]:
15888
+ caps = parse_capability_overrides(raw_global_caps)
15674
15889
  for alias in _provider_aliases(provider_key, provider):
15675
- nested_global = raw_global_caps.get(alias)
15676
- if nested_global is not None:
15677
- caps = merge_multimodal_capabilities(caps, parse_capability_overrides(nested_global))
15678
- direct_override = config.get(f"{alias}_capabilities")
15679
- if direct_override is not None:
15680
- caps = merge_multimodal_capabilities(caps, parse_capability_overrides(direct_override))
15681
- model_override = model_caps_map.get(model) or model_caps_map.get(str(model or "").lower())
15682
- if model_override is not None:
15683
- caps = merge_multimodal_capabilities(caps, parse_capability_overrides(model_override))
15890
+ caps.update(parse_capability_overrides(raw_global_caps.get(alias)))
15891
+ caps.update(parse_capability_overrides(config.get(f"{alias}_capabilities")))
15684
15892
  return caps
15685
15893
 
15686
15894
  def build_profile_media_endpoints(provider_key: str) -> dict[str, str]:
@@ -15781,7 +15989,8 @@ def parse_llm_config_profiles(config: dict, default_ollama_url: str, default_oll
15781
15989
  response_stream: bool = False,
15782
15990
  temperature: float = 0.2,
15783
15991
  request_timeout: int = DEFAULT_REQUEST_TIMEOUT,
15784
- capabilities: dict | None = None,
15992
+ capabilities_key: str = "",
15993
+ inline_capabilities: dict | None = None,
15785
15994
  media_endpoints: dict | None = None,
15786
15995
  source: str = "config",
15787
15996
  effort: str = "",
@@ -15791,6 +16000,16 @@ def parse_llm_config_profiles(config: dict, default_ollama_url: str, default_oll
15791
16000
  model_settings: dict | None = None,
15792
16001
  configured_models: list | None = None,
15793
16002
  ):
16003
+ inline = parse_capability_overrides(inline_capabilities)
16004
+ capability_overrides = {**build_provider_capability_overrides(capabilities_key or profile_id, provider), **inline}
16005
+ model_capability_overrides = {
16006
+ model_id: {**overrides, **inline}
16007
+ for model_id, overrides in configured_model_capabilities.items()
16008
+ }
16009
+ capabilities = merge_multimodal_capabilities(
16010
+ infer_model_multimodal_capabilities(provider, model),
16011
+ {**capability_overrides, **model_capability_overrides.get(model.strip().casefold(), {})},
16012
+ )
15794
16013
  out.append(
15795
16014
  {
15796
16015
  "id": profile_id,
@@ -15815,7 +16034,9 @@ def parse_llm_config_profiles(config: dict, default_ollama_url: str, default_oll
15815
16034
  maximum=MAX_TIMEOUT_SECONDS,
15816
16035
  fallback=DEFAULT_REQUEST_TIMEOUT,
15817
16036
  ),
15818
- "capabilities": capabilities or default_multimodal_capabilities(),
16037
+ "capabilities": capabilities,
16038
+ "capability_overrides": capability_overrides,
16039
+ "model_capability_overrides": model_capability_overrides,
15819
16040
  "media_endpoints": media_endpoints or {},
15820
16041
  "effort": str(effort or "").strip().lower(),
15821
16042
  "max_effort": str(max_effort or "").strip().lower(),
@@ -15999,12 +16220,6 @@ def parse_llm_config_profiles(config: dict, default_ollama_url: str, default_oll
15999
16220
  elif is_openai_like_provider(provider):
16000
16221
  endpoint = endpoint or complete_chat_endpoint(base_url)
16001
16222
  caps_key = str(raw_profile.get("capabilities_key") or profile_id or provider)
16002
- capabilities = build_profile_capabilities(caps_key, provider, model)
16003
- if raw_profile.get("capabilities") is not None:
16004
- capabilities = merge_multimodal_capabilities(
16005
- capabilities,
16006
- parse_capability_overrides(raw_profile.get("capabilities")),
16007
- )
16008
16223
  media_endpoints = build_profile_media_endpoints(caps_key)
16009
16224
  if raw_profile.get("media_endpoints") is not None:
16010
16225
  media_endpoints.update(parse_media_endpoints(raw_profile.get("media_endpoints")))
@@ -16058,7 +16273,8 @@ def parse_llm_config_profiles(config: dict, default_ollama_url: str, default_oll
16058
16273
  ),
16059
16274
  temperature=float(raw_profile.get("temperature", temp) or temp),
16060
16275
  request_timeout=raw_profile.get("request_timeout", timeout),
16061
- capabilities=capabilities,
16276
+ capabilities_key=caps_key,
16277
+ inline_capabilities=raw_profile.get("capabilities"),
16062
16278
  media_endpoints=media_endpoints,
16063
16279
  effort=str(raw_profile.get("effort", effort_default) or effort_default),
16064
16280
  max_effort=str(raw_profile.get("max_effort", max_effort_default) or max_effort_default),
@@ -16090,7 +16306,6 @@ def parse_llm_config_profiles(config: dict, default_ollama_url: str, default_oll
16090
16306
  response_stream=bool(config.get("ollama_response_stream", response_stream_default)),
16091
16307
  temperature=temp,
16092
16308
  request_timeout=timeout,
16093
- capabilities=build_profile_capabilities("ollama", "ollama", ollama_model),
16094
16309
  media_endpoints=build_profile_media_endpoints("ollama"),
16095
16310
  )
16096
16311
 
@@ -16111,7 +16326,6 @@ def parse_llm_config_profiles(config: dict, default_ollama_url: str, default_oll
16111
16326
  response_stream=bool(config.get("openai_response_stream", response_stream_default)),
16112
16327
  temperature=temp,
16113
16328
  request_timeout=timeout,
16114
- capabilities=build_profile_capabilities("openai", normalize_profile_provider("openai"), openai_model or "gpt-4o-mini"),
16115
16329
  media_endpoints=build_profile_media_endpoints("openai"),
16116
16330
  )
16117
16331
 
@@ -16132,7 +16346,6 @@ def parse_llm_config_profiles(config: dict, default_ollama_url: str, default_oll
16132
16346
  response_stream=bool(config.get("siliconflow_response_stream", response_stream_default)),
16133
16347
  temperature=temp,
16134
16348
  request_timeout=timeout,
16135
- capabilities=build_profile_capabilities("siliconflow", normalize_profile_provider("siliconflow"), sf_model or "Qwen/Qwen3-Next-80B-A3B-Instruct"),
16136
16349
  media_endpoints=build_profile_media_endpoints("siliconflow"),
16137
16350
  )
16138
16351
 
@@ -16155,7 +16368,6 @@ def parse_llm_config_profiles(config: dict, default_ollama_url: str, default_oll
16155
16368
  response_stream=bool(config.get("vllm_response_stream", response_stream_default)),
16156
16369
  temperature=temp,
16157
16370
  request_timeout=timeout,
16158
- capabilities=build_profile_capabilities("vllm", normalize_profile_provider("vllm"), vllm_model or "auto"),
16159
16371
  media_endpoints=build_profile_media_endpoints("vllm"),
16160
16372
  )
16161
16373
 
@@ -16176,7 +16388,6 @@ def parse_llm_config_profiles(config: dict, default_ollama_url: str, default_oll
16176
16388
  response_stream=bool(config.get("lmstudio_response_stream", response_stream_default)),
16177
16389
  temperature=temp,
16178
16390
  request_timeout=timeout,
16179
- capabilities=build_profile_capabilities("lmstudio", normalize_profile_provider("lmstudio"), lms_model or "auto"),
16180
16391
  media_endpoints=build_profile_media_endpoints("lmstudio"),
16181
16392
  )
16182
16393
 
@@ -16199,7 +16410,6 @@ def parse_llm_config_profiles(config: dict, default_ollama_url: str, default_oll
16199
16410
  response_stream=bool(config.get("anthropic_response_stream", response_stream_default)),
16200
16411
  temperature=temp,
16201
16412
  request_timeout=timeout,
16202
- capabilities=build_profile_capabilities("anthropic", "anthropic", anth_model or "claude-sonnet-4-20250514"),
16203
16413
  media_endpoints=build_profile_media_endpoints("anthropic"),
16204
16414
  )
16205
16415
 
@@ -16222,7 +16432,6 @@ def parse_llm_config_profiles(config: dict, default_ollama_url: str, default_oll
16222
16432
  response_stream=bool(config.get("glm_response_stream", response_stream_default)),
16223
16433
  temperature=temp,
16224
16434
  request_timeout=timeout,
16225
- capabilities=build_profile_capabilities("glm", normalize_profile_provider("glm"), glm_model or "glm-4-flash"),
16226
16435
  media_endpoints=build_profile_media_endpoints("glm"),
16227
16436
  effort=str(config.get("glm_effort", effort_default) or effort_default),
16228
16437
  max_effort=str(config.get("glm_max_effort", max_effort_default) or max_effort_default),
@@ -16247,7 +16456,6 @@ def parse_llm_config_profiles(config: dict, default_ollama_url: str, default_oll
16247
16456
  response_stream=bool(config.get("kimi_response_stream", response_stream_default)),
16248
16457
  temperature=temp,
16249
16458
  request_timeout=timeout,
16250
- capabilities=build_profile_capabilities("kimi", normalize_profile_provider("kimi"), kimi_model or "moonshot-v1-8k"),
16251
16459
  media_endpoints=build_profile_media_endpoints("kimi"),
16252
16460
  )
16253
16461
 
@@ -16270,7 +16478,6 @@ def parse_llm_config_profiles(config: dict, default_ollama_url: str, default_oll
16270
16478
  response_stream=bool(config.get("openrouter_response_stream", response_stream_default)),
16271
16479
  temperature=temp,
16272
16480
  request_timeout=timeout,
16273
- capabilities=build_profile_capabilities("openrouter", normalize_profile_provider("openrouter"), or_model or "meta-llama/llama-3.1-8b-instruct"),
16274
16481
  media_endpoints=build_profile_media_endpoints("openrouter"),
16275
16482
  )
16276
16483
 
@@ -16337,7 +16544,6 @@ def parse_llm_config_profiles(config: dict, default_ollama_url: str, default_oll
16337
16544
  response_stream=bool(config.get("custom_response_stream", response_stream_default)),
16338
16545
  temperature=temp,
16339
16546
  request_timeout=timeout,
16340
- capabilities=build_profile_capabilities("custom", normalize_profile_provider("custom_http"), str(config.get("custom_model", "") or config.get("openai_model", "") or "custom-model")),
16341
16547
  media_endpoints=build_profile_media_endpoints("custom"),
16342
16548
  )
16343
16549
 
@@ -16353,7 +16559,6 @@ def parse_llm_config_profiles(config: dict, default_ollama_url: str, default_oll
16353
16559
  response_stream=response_stream_default,
16354
16560
  temperature=0.2,
16355
16561
  request_timeout=DEFAULT_REQUEST_TIMEOUT,
16356
- capabilities=build_profile_capabilities("ollama", "ollama", default_ollama_model),
16357
16562
  media_endpoints=build_profile_media_endpoints("ollama"),
16358
16563
  source="default",
16359
16564
  )
@@ -18210,6 +18415,7 @@ def _admin_config_schema() -> list[dict]:
18210
18415
  row("max_run_tokens", "runtime", "Run token quota (0 = unlimited)", "integer", 0, "--max_run_tokens", minimum=0, maximum=100000000),
18211
18416
  row("max_task_tokens", "runtime", "Plan-step token quota (0 = unlimited)", "integer", 0, "--max_task_tokens", minimum=0, maximum=100000000),
18212
18417
  row("max_rounds", "runtime", "Maximum agent rounds", "integer", MAX_AGENT_ROUNDS, "--max_rounds", minimum=MIN_AGENT_ROUNDS, maximum=MAX_AGENT_ROUNDS_CAP),
18418
+ row("goal_turns", "runtime", "Default goal turns", "integer", GOAL_DEFAULT_MAX_TURNS, "--goal_turns", minimum=1, maximum=GOAL_MAX_TURNS_LIMIT),
18213
18419
  row("run_timeout", "runtime", "Run timeout (seconds)", "integer", MAX_RUN_SECONDS, "--run_timeout", minimum=MIN_RUN_TIMEOUT_SECONDS, maximum=MAX_RUN_TIMEOUT_SECONDS),
18214
18420
  row("shell_command_timeout", "runtime", "Shell timeout (seconds)", "integer", DEFAULT_SHELL_COMMAND_TIMEOUT_SECONDS, "--shell_command_timeout", minimum=MIN_SHELL_COMMAND_TIMEOUT_SECONDS, maximum=MAX_SHELL_COMMAND_TIMEOUT_SECONDS),
18215
18421
  row("shell_timeout_mode", "runtime", "Shell timeout mode", "enum", DEFAULT_SHELL_TIMEOUT_MODE, "--shell-timeout-mode", choices=list(SHELL_TIMEOUT_MODES)),
@@ -30491,46 +30697,49 @@ class OllamaClient:
30491
30697
  )
30492
30698
  return any(m in low for m in bad_markers)
30493
30699
 
30494
- def _active_probe_input_capability(self, media_type: str) -> tuple[bool, str]:
30700
+ def _active_probe_input_capability(self, media_type: str, *, cancel_check=None) -> tuple[bool | None, str]:
30495
30701
  mtype = str(media_type or "").strip().lower()
30496
30702
  if mtype not in {"image", "audio", "video"}:
30497
30703
  return False, "unsupported media type"
30498
30704
  if str(self.provider or "").strip().lower() == "ollama" and mtype in {"audio", "video"}:
30499
30705
  return False, "ollama chat payload currently supports image attachments only"
30500
- probe_map = {
30501
- "image": (_capability_probe_png_bytes(), "image/png"),
30502
- "audio": (_capability_probe_audio_bytes(), "audio/wav"),
30503
- "video": (_capability_probe_video_bytes(), "video/mp4"),
30504
- }
30505
- probe_bytes, mime = probe_map[mtype]
30706
+ if mtype == "image":
30707
+ expected, color = secrets.choice((("red", (255, 0, 0)), ("blue", (0, 0, 255))))
30708
+ probe_bytes, mime = _capability_probe_png_bytes(color), "image/png"
30709
+ prompt = "What is the main color in the attached image? Answer with the color, or UNAVAILABLE if you cannot see it."
30710
+ elif mtype == "audio":
30711
+ expected = "tone"
30712
+ probe_bytes, mime = _capability_probe_audio_bytes(), "audio/wav"
30713
+ prompt = "Does the attached audio contain a tone, speech, or silence? Use one word, or UNAVAILABLE if you cannot hear it."
30714
+ else:
30715
+ expected = "red"
30716
+ probe_bytes, mime = _capability_probe_video_bytes(), "video/mp4"
30717
+ prompt = "What is the main color in the attached video? Answer with the color, or UNAVAILABLE if you cannot see it."
30506
30718
  data_b64 = base64.b64encode(probe_bytes).decode("ascii")
30507
- prompt_map = {
30508
- "image": "Capability probe: briefly describe this image in one sentence.",
30509
- "audio": "Capability probe: transcribe or describe this audio in one sentence.",
30510
- "video": "Capability probe: briefly describe this video in one sentence.",
30511
- }
30512
- temp_timeout = self.timeout
30513
- self.timeout = max(12, min(self.timeout or 40, 40))
30514
30719
  try:
30515
30720
  rsp = self.chat(
30516
- [{"role": "user", "content": prompt_map[mtype]}],
30517
- max_tokens=80,
30721
+ [{"role": "user", "content": prompt}],
30722
+ max_tokens=256,
30518
30723
  temperature=0.0,
30519
30724
  think=False,
30520
30725
  stream_thinking=False,
30726
+ effort=EFFORT_OFF,
30521
30727
  media_inputs=[{"type": mtype, "data_b64": data_b64, "mime": mime, "name": f"probe.{mtype}"}],
30522
30728
  probe_mode=True,
30729
+ cancel_check=cancel_check,
30730
+ request_timeout=min(self.timeout or 15, 15),
30523
30731
  )
30524
30732
  txt = str(rsp.get("content", "") or "").strip()
30525
- if self._looks_like_unsupported_text(txt):
30526
- return False, trim(txt, 160)
30527
- if txt or rsp.get("tool_calls"):
30733
+ if re.search(rf"\b{expected}\b", txt, re.IGNORECASE):
30528
30734
  return True, "ok"
30529
- return True, "accepted"
30735
+ if txt.casefold().strip(".") == "unavailable" or self._looks_like_unsupported_text(txt):
30736
+ return False, trim(txt, 160)
30737
+ return None, "probe response did not confirm media perception"
30530
30738
  except Exception as exc:
30531
- return False, trim(str(exc), 180)
30532
- finally:
30533
- self.timeout = temp_timeout
30739
+ note = trim(str(exc), 180)
30740
+ if getattr(exc, "status", None) in {400, 415, 422} and self._looks_like_unsupported_text(note):
30741
+ return False, note
30742
+ return None, note
30534
30743
 
30535
30744
  def _active_probe_output_capability(self, media_type: str) -> tuple[bool, str]:
30536
30745
  mtype = str(media_type or "").strip().lower()
@@ -30572,16 +30781,21 @@ class OllamaClient:
30572
30781
  return merge_multimodal_capabilities(default_multimodal_capabilities(), parse_capability_overrides(caps))
30573
30782
  caps = merge_multimodal_capabilities(default_multimodal_capabilities(), self.capabilities or {})
30574
30783
  details: dict[str, str] = {}
30784
+ observed = {}
30575
30785
  for mtype, cap_key in (("image", "input_image"), ("audio", "input_audio"), ("video", "input_video")):
30576
30786
  ok, note = self._active_probe_input_capability(mtype)
30577
- caps[cap_key] = bool(ok)
30787
+ if ok is not None:
30788
+ caps[cap_key] = ok
30789
+ observed[cap_key] = ok
30578
30790
  details[cap_key] = note
30579
30791
  for mtype, cap_key in (("image", "output_image"), ("audio", "output_audio"), ("video", "output_video")):
30580
30792
  ok, note = self._active_probe_output_capability(mtype)
30581
30793
  caps[cap_key] = bool(ok)
30794
+ observed[cap_key] = bool(ok)
30582
30795
  details[cap_key] = note
30583
30796
  self._probe_cache[key] = {
30584
30797
  "capabilities": dict(caps),
30798
+ "observed_capabilities": observed,
30585
30799
  "details": details,
30586
30800
  "provider": self.provider,
30587
30801
  "model": self.model,
@@ -32209,11 +32423,12 @@ TOOLS = [
32209
32423
  ),
32210
32424
  tool_def(
32211
32425
  "ask_user",
32212
- "Pause the run and ask the user a question when you need a decision or clarification you cannot make yourself (e.g. choosing among options, confirming a direction, missing info). The run STOPS after this call and resumes only when the user replies. Do NOT use this to report progress or to finish — use finish_task for completion. Provide a clear question; optionally provide `options` (a short list of choices to present as buttons) and set `allow_free_text` false to require picking an option.",
32426
+ "Pause the run and ask the user a question when you need a decision or clarification you cannot make yourself (e.g. choosing among options, confirming a direction, missing info). The run STOPS after this call and resumes only when the user replies. Do NOT use this to report progress or to finish — use finish_task for completion. Provide a clear question; optionally provide `options` (a short list of choices to present as buttons) and set `allow_free_text` false to require picking an option. Set `goal_condition` only when the system prompt says goal proposals are on: it asks the user to confirm that condition as the session goal.",
32213
32427
  {
32214
32428
  "question": {"type": "string"},
32215
32429
  "options": {"type": "array", "items": {"type": "string"}},
32216
32430
  "allow_free_text": {"type": "boolean"},
32431
+ "goal_condition": {"type": "string"},
32217
32432
  },
32218
32433
  ["question"],
32219
32434
  ),
@@ -33641,6 +33856,22 @@ _EVIDENCE_CONTROLLER_INIT_LOCK = threading.Lock()
33641
33856
 
33642
33857
 
33643
33858
  class SessionState:
33859
+ # Goal-mode defaults for instances built without __init__ (tests and
33860
+ # integrations); __init__ gives every session its own values.
33861
+ goal_state: dict | None = None
33862
+ goal_preferences: dict | None = None
33863
+ goal_default_turns = GOAL_DEFAULT_MAX_TURNS
33864
+ goal_evaluating = False
33865
+ _goal_continuation_turn = False
33866
+ _goal_turn_started_at = 0.0
33867
+
33868
+ @property
33869
+ def goal_lock(self) -> threading.RLock:
33870
+ lock = self.__dict__.get("_goal_lock")
33871
+ if lock is None:
33872
+ lock = self.__dict__.setdefault("_goal_lock", threading.RLock())
33873
+ return lock
33874
+
33644
33875
  def _evidence_controller(self) -> EvidenceRetrievalController:
33645
33876
  with _EVIDENCE_CONTROLLER_INIT_LOCK:
33646
33877
  controller = getattr(self, '_evidence_retrieval_controller', None)
@@ -34256,6 +34487,15 @@ class SessionState:
34256
34487
  self.deferred_start_inputs: list[dict] = []
34257
34488
  self.deferred_start_seq = 0
34258
34489
  self.deferred_start_worker_started = False
34490
+ # Goal mode (see GOAL_* constants). Empty dict: no goal set.
34491
+ self.goal_state: dict = {}
34492
+ # Per-session choices from the composer's goal menu; 0 means "use the default".
34493
+ self.goal_preferences: dict = self._goal_normalize_preferences({})
34494
+ self.goal_default_turns = GOAL_DEFAULT_MAX_TURNS
34495
+ self._goal_lock = threading.RLock()
34496
+ self.goal_evaluating = False
34497
+ self._goal_continuation_turn = False
34498
+ self._goal_turn_started_at = 0.0
34259
34499
  self.deferred_start_worker_lock = threading.Lock()
34260
34500
  self.deferred_start_recent_submissions: list[dict] = []
34261
34501
  self.scheduler_visible_inputs: list[dict] = []
@@ -34392,6 +34632,7 @@ class SessionState:
34392
34632
  self._cached_llm_complexity = ""
34393
34633
  self._cached_complexity_dimensions: dict = {} # scope/steps/skill/output dimensions
34394
34634
  self._pending_media_inputs: list[dict] = []
34635
+ self._media_input_probe_attempts: dict[tuple[str, str], float] = {}
34395
34636
  self._pending_runtime_updates: list[dict] = []
34396
34637
  self._deferred_runtime_sync_requested = False
34397
34638
  self.tool_retry_counts: dict[str, int] = {}
@@ -34725,18 +34966,71 @@ class SessionState:
34725
34966
  model = str(model_override or row.get("model", self.ollama.model) or self.ollama.model).strip().lower()
34726
34967
  return "|".join([provider, base_url, endpoint, model])
34727
34968
 
34969
+ def _confirmed_media_capabilities(self, profile: dict, model: str) -> dict[str, bool]:
34970
+ key = self._profile_cache_key(profile, model)
34971
+ cached = self.multimodal_capability_cache.get(key, {})
34972
+ confirmed = parse_capability_overrides(cached.get("capabilities", {}) if isinstance(cached, dict) else {})
34973
+ for record in probe_provider_models(profile, cached_only=True):
34974
+ if str(record.get("id", "")).casefold() != model.casefold():
34975
+ continue
34976
+ advertised = record.get("capabilities", {})
34977
+ if isinstance(advertised, dict) and advertised.get("vision") is True:
34978
+ confirmed["input_image"] = True
34979
+ confirmed.update(parse_capability_overrides(advertised))
34980
+ break
34981
+ confirmed.update(resolve_configured_media_capabilities(profile, model))
34982
+ return confirmed
34983
+
34728
34984
  def _capabilities_from_profile(self, profile: dict | None = None, model_override: str = "") -> dict[str, bool]:
34729
34985
  row = profile if isinstance(profile, dict) else dict(self.model_profiles.get(self.active_profile_id, {}))
34730
34986
  provider = str(row.get("provider", self.ollama.provider) or self.ollama.provider)
34731
34987
  model = str(model_override or row.get("model", self.ollama.model) or self.ollama.model)
34732
- declared = parse_capability_overrides(row.get("capabilities", {}))
34733
- inferred = infer_model_multimodal_capabilities(provider, model)
34734
- merged = merge_multimodal_capabilities(inferred, declared)
34735
- key = self._profile_cache_key(row, model)
34736
- cached = self.multimodal_capability_cache.get(key, {})
34737
- if isinstance(cached, dict):
34738
- merged = merge_multimodal_capabilities(merged, parse_capability_overrides(cached.get("capabilities", {})))
34739
- return merged
34988
+ return merge_multimodal_capabilities(
34989
+ infer_model_multimodal_capabilities(provider, model), self._confirmed_media_capabilities(row, model),
34990
+ )
34991
+
34992
+ def _ensure_media_input_capabilities(self, media_types: set[str]) -> dict[str, bool]:
34993
+ """Probe only requested input types whose support is still unknown."""
34994
+ profile = dict(self.model_profiles.get(self.active_profile_id, {}))
34995
+ caps = self._capabilities_from_profile(profile)
34996
+ if not profile:
34997
+ return caps
34998
+ model = str(profile.get("model") or self.ollama.model)
34999
+ key = self._profile_cache_key(profile, model)
35000
+ confirmed = self._confirmed_media_capabilities(profile, model)
35001
+ unknown = {kind for kind in media_types if f"input_{kind}" not in confirmed}
35002
+ if not unknown:
35003
+ return caps
35004
+ provider = str(profile.get("provider", "") or "").lower()
35005
+ if is_openai_like_provider(provider) or provider == "anthropic":
35006
+ probe_provider_models(profile)
35007
+ confirmed = self._confirmed_media_capabilities(profile, model)
35008
+ tool_cancel = self._current_tool_cancel_event()
35009
+
35010
+ def cancelled() -> bool:
35011
+ return bool(self.cancel_requested or (tool_cancel is not None and tool_cancel.is_set()))
35012
+
35013
+ for kind in sorted(unknown):
35014
+ cap_key = f"input_{kind}"
35015
+ if cap_key in confirmed or cancelled():
35016
+ continue
35017
+ with self.lock:
35018
+ attempt_key = (key, kind)
35019
+ now = time.monotonic()
35020
+ if self._media_input_probe_attempts.get(attempt_key, 0) > now:
35021
+ continue
35022
+ self._media_input_probe_attempts[attempt_key] = now + 60
35023
+ supported, note = self.ollama._active_probe_input_capability(kind, cancel_check=cancelled)
35024
+ if supported is None or cancelled():
35025
+ continue
35026
+ with self.lock:
35027
+ if key != self._profile_cache_key():
35028
+ break
35029
+ entry = self.multimodal_capability_cache.setdefault(key, {})
35030
+ entry.setdefault("capabilities", {})[cap_key] = supported
35031
+ entry.setdefault("details", {})[cap_key] = note
35032
+ entry.update(updated_at=now_ts(), provider=provider, model=model)
35033
+ return self._capabilities_from_profile()
34740
35034
 
34741
35035
  def _ensure_active_profile_capabilities(self, force_probe: bool = False) -> dict[str, bool]:
34742
35036
  profile = dict(self.model_profiles.get(self.active_profile_id, {}))
@@ -34748,10 +35042,7 @@ class SessionState:
34748
35042
  if isinstance(cached, dict):
34749
35043
  caps = parse_capability_overrides(cached.get("capabilities", {}))
34750
35044
  if caps:
34751
- merged_cached = merge_multimodal_capabilities(
34752
- self._capabilities_from_profile(profile),
34753
- caps,
34754
- )
35045
+ merged_cached = self._capabilities_from_profile(profile)
34755
35046
  profile["capabilities"] = merged_cached
34756
35047
  self.model_profiles[self.active_profile_id] = profile
34757
35048
  return merged_cached
@@ -34762,15 +35053,15 @@ class SessionState:
34762
35053
  return merged
34763
35054
  try:
34764
35055
  probed = self.ollama.probe_multimodal_capabilities(force=True if force_probe else False)
34765
- merged = merge_multimodal_capabilities(self._capabilities_from_profile(profile), probed)
34766
35056
  entry = self.ollama.probe_cache_entry()
34767
35057
  self.multimodal_capability_cache[key] = {
34768
- "capabilities": merged,
35058
+ "capabilities": entry.get("observed_capabilities", probed),
34769
35059
  "details": entry.get("details", {}),
34770
35060
  "updated_at": float(entry.get("updated_at", now_ts()) or now_ts()),
34771
35061
  "provider": str(profile.get("provider", "")),
34772
35062
  "model": str(profile.get("model", "")),
34773
35063
  }
35064
+ merged = self._capabilities_from_profile(profile)
34774
35065
  profile["capabilities"] = merged
34775
35066
  self.model_profiles[self.active_profile_id] = profile
34776
35067
  self.updated_at = now_ts()
@@ -34778,17 +35069,16 @@ class SessionState:
34778
35069
  return merged
34779
35070
  except Exception as exc:
34780
35071
  merged = self._capabilities_from_profile(profile)
34781
- self.multimodal_capability_cache[key] = {
34782
- "capabilities": merged,
34783
- "details": {"probe_error": trim(str(exc), 240)},
34784
- "updated_at": now_ts(),
34785
- "provider": str(profile.get("provider", "")),
34786
- "model": str(profile.get("model", "")),
34787
- }
35072
+ entry = self.multimodal_capability_cache.setdefault(key, {})
35073
+ entry.setdefault("details", {})["probe_error"] = trim(str(exc), 240)
34788
35074
  return merged
34789
35075
 
34790
35076
  def _recent_multimodal_inputs(self, max_items: int = 4, max_total_bytes: int = 12 * 1024 * 1024) -> list[dict]:
34791
- caps = self._capabilities_from_profile()
35077
+ with self.lock:
35078
+ rows = list(self.uploads)
35079
+ requested = {str(row.get("kind", "")).strip().lower() for row in rows if isinstance(row, dict)}
35080
+ requested &= {"image", "audio", "video"}
35081
+ caps = self._ensure_media_input_capabilities(requested) if requested else self._capabilities_from_profile()
34792
35082
  wants_image = bool(caps.get("input_image", False))
34793
35083
  wants_audio = bool(caps.get("input_audio", False))
34794
35084
  wants_video = bool(caps.get("input_video", False))
@@ -34804,8 +35094,6 @@ class SessionState:
34804
35094
  items: list[dict] = []
34805
35095
  used_rel: set[str] = set()
34806
35096
  total = 0
34807
- with self.lock:
34808
- rows = list(self.uploads)
34809
35097
  for row in reversed(rows):
34810
35098
  kind = str(row.get("kind", "") or "").strip().lower()
34811
35099
  if kind not in kind_allow:
@@ -34854,23 +35142,47 @@ class SessionState:
34854
35142
  used_rel=used_rel,
34855
35143
  )
34856
35144
  items.extend(extra)
34857
- # Merge pending media inputs from read_file (multimodal file reads)
34858
- with self.lock:
34859
- pending = list(getattr(self, "_pending_media_inputs", []))
34860
- self._pending_media_inputs = []
34861
- for media in pending:
34862
- kind = str(media.get("type", "") or "").strip().lower()
34863
- if kind not in kind_allow:
34864
- continue
34865
- rel = str(media.get("workspace_path", "") or "")
34866
- if rel in used_rel:
34867
- continue
34868
- if len(items) >= max_items:
34869
- break
34870
- items.append(media)
34871
- used_rel.add(rel)
34872
35145
  return items
34873
35146
 
35147
+ def _media_inputs_for_tool_results(
35148
+ self, messages: list[dict], media_inputs: list[dict] | None,
35149
+ ) -> tuple[list[dict] | None, set[str]]:
35150
+ if not getattr(self, "_pending_media_inputs", None):
35151
+ return media_inputs, set()
35152
+ call_ids = {row.get("tool_call_id") for row in messages if row.get("role") == "tool"}
35153
+ caps = self._capabilities_from_profile()
35154
+ with self.lock:
35155
+ pending = [
35156
+ row for row in self._pending_media_inputs
35157
+ if row["read_call_id"] in call_ids and caps.get(f"input_{row['type']}")
35158
+ ]
35159
+ if not pending:
35160
+ return media_inputs, set()
35161
+ combined = []
35162
+ delivered = set()
35163
+ seen = set()
35164
+ remaining = 28 * 1024 * 1024 # Base64 bytes for up to 20 MB of input.
35165
+ for row in [*reversed(pending), *(media_inputs or [])]:
35166
+ path = row.get("workspace_path") or row.get("name")
35167
+ size = len(row.get("data_b64", ""))
35168
+ if path not in seen:
35169
+ if not size or size > remaining or len(combined) >= 4:
35170
+ continue
35171
+ seen.add(path)
35172
+ combined.append(row)
35173
+ remaining -= size
35174
+ read_id = row.get("read_call_id")
35175
+ if read_id:
35176
+ delivered.add(read_id)
35177
+ return combined, delivered
35178
+
35179
+ def _acknowledge_media_tool_results(self, call_ids: set[str]) -> None:
35180
+ if call_ids:
35181
+ with self.lock:
35182
+ self._pending_media_inputs = [
35183
+ row for row in self._pending_media_inputs if row["read_call_id"] not in call_ids
35184
+ ]
35185
+
34874
35186
  def _is_external_user_message_for_goal_tracking(self, row: dict | None) -> bool:
34875
35187
  if not isinstance(row, dict):
34876
35188
  return False
@@ -35436,6 +35748,10 @@ class SessionState:
35436
35748
  if not profile:
35437
35749
  return
35438
35750
  stored = dict(profile)
35751
+ if "capability_overrides" not in stored:
35752
+ stored["capability_overrides"] = resolve_configured_media_capabilities(
35753
+ stored, str(stored.get("model", "") or ""),
35754
+ )
35439
35755
  row = dict(stored)
35440
35756
  # Restore the selected model's persisted runtime controls before the
35441
35757
  # client is configured. This keeps effort/streaming identical after a
@@ -35455,7 +35771,7 @@ class SessionState:
35455
35771
  if isinstance(cached, dict):
35456
35772
  cached_caps = parse_capability_overrides(cached.get("capabilities", {}))
35457
35773
  if cached_caps:
35458
- merged = merge_multimodal_capabilities(self._capabilities_from_profile(row), cached_caps)
35774
+ merged = self._capabilities_from_profile(stored)
35459
35775
  row["capabilities"] = merged
35460
35776
  stored["capabilities"] = merged
35461
35777
  stored["request_timeout"] = row["request_timeout"]
@@ -36222,7 +36538,7 @@ class SessionState:
36222
36538
  continue
36223
36539
  caps = parse_capability_overrides(centry.get("capabilities", {}))
36224
36540
  clean_cache[key] = {
36225
- "capabilities": merge_multimodal_capabilities(default_multimodal_capabilities(), caps),
36541
+ "capabilities": caps,
36226
36542
  "details": centry.get("details", {}) if isinstance(centry.get("details"), dict) else {},
36227
36543
  "updated_at": float(centry.get("updated_at", 0.0) or 0.0),
36228
36544
  "provider": str(centry.get("provider", "")),
@@ -36482,6 +36798,11 @@ class SessionState:
36482
36798
  "role": str(_pq.get("role", "") or "agent"),
36483
36799
  "ts": float(_pq.get("ts", 0.0) or 0.0),
36484
36800
  }
36801
+ if isinstance(_pq.get("goal_proposal"), dict) and str(_pq["goal_proposal"].get("objective", "") or "").strip():
36802
+ self.pending_user_question["goal_proposal"] = {
36803
+ "objective": trim(str(_pq["goal_proposal"].get("objective", "")).strip(), GOAL_OBJECTIVE_MAX_CHARS),
36804
+ "max_turns": int(_pq["goal_proposal"].get("max_turns", 0) or 0),
36805
+ }
36485
36806
  for _pq_scope_key in (
36486
36807
  "kind",
36487
36808
  "parent_step_id",
@@ -36561,6 +36882,12 @@ class SessionState:
36561
36882
  }
36562
36883
  )
36563
36884
  self.user_bubble_log = clean_bubbles[-MAX_USER_BUBBLE_LOG:]
36885
+ self.goal_state = self._goal_normalize_state(raw.get("goal_state"))
36886
+ self.goal_preferences = self._goal_normalize_preferences(raw.get("goal_preferences"))
36887
+ if self.goal_state.get("status") == "active" and not bool(getattr(self, "running", False)):
36888
+ # A saved active goal does not restart turns on its own
36889
+ # after a server restart; the user resumes it.
36890
+ self._goal_set_status("paused", "server restarted; use /goal resume to continue")
36564
36891
  self.run_generation = int(raw.get("run_generation", self.run_generation) or self.run_generation)
36565
36892
  self._sync_llm_gate_generation()
36566
36893
  self.agent_round_index = int(raw.get("agent_round_index", self.agent_round_index) or 0)
@@ -37046,6 +37373,8 @@ class SessionState:
37046
37373
  "deferred_start_seq": int(deferred_start_seq_snapshot),
37047
37374
  "scheduler_visible_inputs": scheduler_visible_inputs_snapshot,
37048
37375
  "user_bubble_log": self.user_bubble_log[-MAX_USER_BUBBLE_LOG:],
37376
+ "goal_state": copy.deepcopy(self.goal_state or {}),
37377
+ "goal_preferences": dict(self.goal_preferences or {}),
37049
37378
  "run_generation": int(self.run_generation),
37050
37379
  "agent_round_index": int(self.agent_round_index),
37051
37380
  "current_phase": str(self.current_phase or "idle"),
@@ -40481,6 +40810,9 @@ class SessionState:
40481
40810
  user_profile_text = f"{user_profile_block}\n\n" if user_profile_block else ""
40482
40811
  task_memory_block = self._blackboard_memory_context_markdown(max_chars=3200)
40483
40812
  task_memory_text = f"{task_memory_block}\n\n" if task_memory_block else ""
40813
+ goal_block = self._goal_prompt_block()
40814
+ if goal_block:
40815
+ task_memory_text = f"{goal_block}\n\n{task_memory_text}"
40484
40816
  mcp_block = self._mcp_prompt_block()
40485
40817
  mcp_text = f"{mcp_block}\n\n" if mcp_block else ""
40486
40818
  # Dynamic skill awareness — unified hint
@@ -40652,6 +40984,7 @@ class SessionState:
40652
40984
  self.last_context_actual_prompt_tokens = prompt
40653
40985
  self.last_context_actual_completion_tokens = int(usage.get("completion_tokens", 0) or 0)
40654
40986
  self.last_context_actual_total_tokens = int(usage.get("total_tokens", 0) or 0)
40987
+ self._goal_note_usage(self.last_context_actual_total_tokens or prompt + self.last_context_actual_completion_tokens)
40655
40988
  self.last_context_actual_source = str(usage.get("source", "model-usage") or "model-usage")
40656
40989
  self.last_context_actual_context_label = trim(str(context_label or ""), 80)
40657
40990
  self.last_context_actual_ts = now_ts()
@@ -54708,7 +55041,10 @@ body{padding:18px}
54708
55041
  if fn.get("arguments") not in (None, "")
54709
55042
  else candidate.get("arguments", candidate.get("input", candidate))
54710
55043
  )
54711
- items = self._todo_payload_items(payload, limit=40) if isinstance(payload, dict) else []
55044
+ source_args = decode_structured_todo_container(payload)
55045
+ if not isinstance(source_args, dict):
55046
+ source_args, _ = parse_tool_arguments_with_error(payload)
55047
+ items = self._todo_payload_items(source_args, limit=40)
54712
55048
  if not items:
54713
55049
  items = self._extract_text_items_from_raw_args(payload)
54714
55050
  clean_items: list[object] = []
@@ -54722,12 +55058,17 @@ body{padding:18px}
54722
55058
  if content:
54723
55059
  clean_items.append(content)
54724
55060
  if clean_items:
55061
+ recovered_args = {"items": clean_items}
55062
+ cursor = self._todo_payload_in_progress_index(source_args)
55063
+ recovered_args["in_progress_index"] = 0 if cursor is None else cursor
55064
+ if "preparation" in source_args:
55065
+ recovered_args["preparation"] = source_args["preparation"]
54725
55066
  return {
54726
55067
  "id": make_id("tool"),
54727
55068
  "type": "function",
54728
55069
  "function": {
54729
55070
  "name": "TodoWriteRescue",
54730
- "arguments": {"items": clean_items, "in_progress_index": 0},
55071
+ "arguments": recovered_args,
54731
55072
  },
54732
55073
  }
54733
55074
  return None
@@ -54816,7 +55157,8 @@ body{padding:18px}
54816
55157
  short_instruction = (
54817
55158
  "The previous completed responses contained reasoning but no final action. "
54818
55159
  "Return one preparation action: observe or ask_user if material context is missing; "
54819
- "use TodoWrite with an honest preparation assessment only when ready. Do not invent readiness to escape this retry."
55160
+ "use TodoWrite with an honest preparation assessment only when ready. Do not invent readiness to escape this retry. "
55161
+ + SINGLE_NO_PLAN_TODO_PREPARATION_INSTRUCTION
54820
55162
  if bootstrap
54821
55163
  else
54822
55164
  "The previous completed responses contained reasoning but no final action. "
@@ -54872,7 +55214,8 @@ body{padding:18px}
54872
55214
  second_instruction = (
54873
55215
  "/no_think\nThinking is disabled for this compatibility retry. "
54874
55216
  "Take one real preparation action. Continue observation or ask_user for missing context; "
54875
- "submit TodoWrite with preparation only if ready. Output no analysis."
55217
+ "submit TodoWrite with preparation only if ready. Output no analysis. "
55218
+ + SINGLE_NO_PLAN_TODO_PREPARATION_INSTRUCTION
54876
55219
  if bootstrap
54877
55220
  else
54878
55221
  "/no_think\nThinking is disabled for this compatibility retry. "
@@ -56399,6 +56742,9 @@ body{padding:18px}
56399
56742
  if canonicalize_tool_name(tool_choice) in {"TodoWrite", "TodoWriteRescue"}:
56400
56743
  tool_choice = ""
56401
56744
  tools = guarded_tools
56745
+ media_inputs, media_tool_call_ids = self._media_inputs_for_tool_results(messages, media_inputs)
56746
+ if media_tool_call_ids:
56747
+ self._emit_multimodal_attach_status(scope=context_label, media_inputs=media_inputs)
56402
56748
  system = self._inject_runtime_environment_context(system)
56403
56749
  estimated_prompt_tokens = self._estimate_model_call_prompt_tokens(
56404
56750
  messages,
@@ -56516,6 +56862,7 @@ body{padding:18px}
56516
56862
  context_label=context_label,
56517
56863
  )
56518
56864
  self._mark_tool_messages_seen(messages)
56865
+ self._acknowledge_media_tool_results(media_tool_call_ids)
56519
56866
  return response
56520
56867
  except OllamaError as exc:
56521
56868
  if visible_response_stream:
@@ -56640,6 +56987,7 @@ body{padding:18px}
56640
56987
  context_label=f"{context_label}:no-media",
56641
56988
  )
56642
56989
  self._mark_tool_messages_seen(messages)
56990
+ self._acknowledge_media_tool_results(media_tool_call_ids)
56643
56991
  return response
56644
56992
  except OllamaError:
56645
56993
  if visible_response_stream:
@@ -58973,69 +59321,44 @@ body{padding:18px}
58973
59321
 
58974
59322
 
58975
59323
  def _run_read_media(self, fp: Path, rel: str, media_type: str) -> str:
58976
- """Read a media file and return description or inject into multimodal context."""
59324
+ """Read a media file and queue it for the model consuming this tool result."""
58977
59325
  if not fp.exists():
58978
59326
  return f"Error: file not found: {rel}"
58979
- caps = self._capabilities_from_profile()
58980
- cap_key = f"input_{media_type}"
58981
59327
  file_size = fp.stat().st_size
58982
59328
  size_kb = file_size / 1024
58983
- if bool(caps.get(cap_key, False)) and file_size < 20 * 1024 * 1024:
58984
- # Model supports this media type — check format compatibility first
58985
- ext = fp.suffix.lower()
58986
- if media_type == "image" and ext == ".svg":
58987
- # SVG: read as text source code instead of injecting as image
58988
- try:
58989
- svg_text = fp.read_text(encoding="utf-8", errors="replace")
58990
- return (
58991
- f"[SVG file: {rel} ({size_kb:.1f} KB)]\n"
58992
- f"SVG source code (use for analysis, do not send as image):\n"
58993
- f"```svg\n{trim(svg_text, 12000)}\n```"
58994
- )
58995
- except Exception as exc:
58996
- return f"Error reading SVG file: {exc}"
58997
- if media_type == "image" and ext in IMAGE_FORMATS_NEED_CONVERSION:
58998
- # Try converting to a safe format via Pillow
58999
- converted, conv_mime, method = _convert_image_to_safe_format(fp)
59000
- if converted:
59001
- b64 = base64.b64encode(converted).decode("ascii")
59002
- mime = conv_mime
59003
- else:
59004
- return (
59005
- f"[{media_type} file: {rel} ({size_kb:.1f} KB, format={ext})] "
59006
- f"Note: format {ext} could not be converted for native vision. "
59007
- f"File exists at {fp}. Use bash tools to process it if needed."
59008
- )
59009
- else:
59010
- # Safe format — encode directly
59011
- try:
59012
- b64 = base64.b64encode(fp.read_bytes()).decode("ascii")
59013
- mime = guess_mime_from_name(fp.name)
59014
- except Exception as exc:
59015
- return f"Error reading {media_type} file: {exc}"
59016
- media_item = {
59017
- "type": media_type,
59018
- "data_b64": b64,
59019
- "mime": mime,
59020
- "name": fp.name,
59021
- "workspace_path": str(rel),
59022
- }
59023
- # Store for injection into next API call
59024
- with self.lock:
59025
- self._pending_media_inputs.append(media_item)
59329
+ label = f"[{media_type} file: {rel} ({size_kb:.1f} KB)]"
59330
+ if file_size <= 0 or file_size >= 20 * 1024 * 1024:
59331
+ return f"{label} Native input requires a nonempty file smaller than 20 MB."
59332
+ ext = fp.suffix.lower()
59333
+ if media_type == "image" and ext == ".svg":
59334
+ svg_text = fp.read_text(encoding="utf-8", errors="replace")
59335
+ return f"[SVG file: {rel} ({size_kb:.1f} KB)]\nSVG source code:\n```svg\n{trim(svg_text, 12000)}\n```"
59336
+ caps = self._ensure_media_input_capabilities({media_type})
59337
+ if not caps.get(f"input_{media_type}"):
59026
59338
  return (
59027
- f"[{media_type} file loaded: {rel} ({size_kb:.1f} KB, {mime})] "
59028
- f"The {media_type} has been attached to the conversation for native {media_type} analysis. "
59029
- f"Describe or analyze it directly."
59339
+ f"{label} Native {media_type} input is unavailable for the active model. "
59340
+ "Use a text-based tool if needed."
59030
59341
  )
59342
+ if media_type == "image" and ext in IMAGE_FORMATS_NEED_CONVERSION:
59343
+ data, mime, _ = _convert_image_to_safe_format(fp)
59344
+ if not data or len(data) >= 20 * 1024 * 1024:
59345
+ return f"{label} Could not convert {ext} to a supported image below 20 MB."
59031
59346
  else:
59032
- # Model doesn't support this media type — return metadata only
59033
- reason = "model does not support" if not caps.get(cap_key) else "file too large"
59034
- return (
59035
- f"[{media_type} file: {rel} ({size_kb:.1f} KB)] "
59036
- f"Note: {reason} native {media_type} input. "
59037
- f"File exists at {fp}. Use bash tools to process it if needed."
59038
- )
59347
+ data, mime = fp.read_bytes(), guess_mime_from_name(fp.name)
59348
+ media_item = {
59349
+ "type": media_type,
59350
+ "data_b64": base64.b64encode(data).decode("ascii"),
59351
+ "mime": mime,
59352
+ "name": fp.name,
59353
+ "workspace_path": str(rel),
59354
+ "read_call_id": str(getattr(_READ_DISPATCH_CONTEXT, "tool_call_id", "") or ""),
59355
+ }
59356
+ with self.lock:
59357
+ self._pending_media_inputs = [*self._pending_media_inputs[-7:], media_item]
59358
+ return (
59359
+ f"[{media_type} file loaded: {rel} ({size_kb:.1f} KB, {mime})] "
59360
+ "The file is queued for native analysis in the next model request."
59361
+ )
59039
59362
 
59040
59363
  def _tool_result_context_content(
59041
59364
  self,
@@ -59499,7 +59822,9 @@ body{padding:18px}
59499
59822
  if name == "bash":
59500
59823
  out = self._dispatch_tool(name, args if isinstance(args, dict) else {}, str(agent_type or ""))
59501
59824
  elif name == "read_file":
59502
- out = self._dispatch_tool(name, args if isinstance(args, dict) else {}, str(agent_type or ""))
59825
+ out = self._dispatch_tool(
59826
+ name, args if isinstance(args, dict) else {}, str(agent_type or ""), tool_call_id=tc["id"],
59827
+ )
59503
59828
  elif name == "write_file":
59504
59829
  out = self._dispatch_tool(name, args if isinstance(args, dict) else {}, str(agent_type or ""))
59505
59830
  elif name == "edit_file":
@@ -80308,6 +80633,23 @@ body{padding:18px}
80308
80633
  goal = self._unwrap_program_ide_task_text(goal)
80309
80634
  if not goal:
80310
80635
  return {}
80636
+ if bool(getattr(self, "_goal_continuation_turn", False)):
80637
+ # A goal turn continues the same task: keep the level, mode and
80638
+ # plan restored from the blackboard instead of classifying again.
80639
+ self._goal_continuation_turn = False
80640
+ if int(self.runtime_task_level or 0) in TASK_LEVEL_CHOICES:
80641
+ return {
80642
+ "level": int(self.runtime_task_level or 0),
80643
+ "execution_mode": self._effective_execution_mode(),
80644
+ "participants": list(self.runtime_participants),
80645
+ "assigned_expert": str(self.runtime_assigned_expert or ""),
80646
+ "scale_preference": str(self.runtime_scale_preference or "balanced"),
80647
+ "round_budget": int(self.runtime_round_budget or 0),
80648
+ "requires_user_confirmation": False,
80649
+ "requires_todos": self._runtime_level_requires_todos(),
80650
+ "inherit_previous_state": True,
80651
+ "source": "goal-continuation",
80652
+ }
80311
80653
  # --- User override short-circuit: user manually set level, skip manager ---
80312
80654
  _utlo = int(getattr(self, 'user_task_level_override', 0) or 0)
80313
80655
  if _utlo > 0 and _utlo in TASK_LEVEL_CHOICES:
@@ -83867,7 +84209,10 @@ body{padding:18px}
83867
84209
  fn = spec.get("function", {}) if isinstance(spec, dict) else {}
83868
84210
  name = str(fn.get("name", "") or "").strip()
83869
84211
  canonical = canonicalize_tool_name(name)
83870
- if canonical in {"TodoWrite", "TodoWriteRescue"} or canonical in read_names:
84212
+ if canonical in {"TodoWrite", "TodoWriteRescue"}:
84213
+ tools.append(self._single_no_plan_todo_writer_spec(spec))
84214
+ continue
84215
+ if canonical in read_names:
83871
84216
  tools.append(spec)
83872
84217
  continue
83873
84218
  # Keep this capability check generic for dynamically mounted MCP
@@ -83987,7 +84332,7 @@ body{padding:18px}
83987
84332
  allowed_commands = {
83988
84333
  "pwd", "ls", "find", "rg", "grep", "egrep", "fgrep", "cat", "head", "tail",
83989
84334
  "sed", "awk", "cut", "sort", "uniq", "wc", "file", "stat", "du", "tree",
83990
- "realpath", "readlink", "env", "which", "type", "echo", "printf", "git",
84335
+ "realpath", "readlink", "env", "which", "whoami", "type", "echo", "printf", "git",
83991
84336
  }
83992
84337
  segments = re.split(r"\s*(?:&&|\|\||[;|])\s*", text)
83993
84338
  for segment in segments:
@@ -84052,9 +84397,11 @@ body{padding:18px}
84052
84397
  return False
84053
84398
  return True
84054
84399
 
84055
- def _single_no_plan_todo_is_perception_result(self, item: dict | None) -> bool:
84056
- """Return true for a successful, read-only observation result."""
84057
- if not isinstance(item, dict) or not bool(item.get("ok", False)):
84400
+ def _single_no_plan_todo_is_perception_result(
84401
+ self, item: dict | None, *, require_success: bool = True,
84402
+ ) -> bool:
84403
+ """Classify observation results and, optionally, failed observation attempts."""
84404
+ if not isinstance(item, dict) or (require_success and not item.get("ok", False)):
84058
84405
  return False
84059
84406
  name = canonicalize_tool_name(item.get("name", ""))
84060
84407
  args = item.get("args", {}) if isinstance(item.get("args"), dict) else {}
@@ -84125,6 +84472,25 @@ body{padding:18px}
84125
84472
  return True
84126
84473
  return False
84127
84474
 
84475
+ def _single_no_plan_todo_writer_spec(self, spec: dict) -> dict:
84476
+ """Advertise the first-list requirements without changing update tools."""
84477
+ if not getattr(self, "_task_preparation_required", False) or self._runtime_task_level_for_todo_policy() < 1:
84478
+ return spec
84479
+ fn = spec["function"]
84480
+ properties = fn["parameters"]["properties"]
84481
+ preparation = properties["preparation"]
84482
+ return tool_def(
84483
+ fn["name"],
84484
+ "Initialize the Todo list once you understand the task and its current state. "
84485
+ "Send the preparation assessment and ordered items together, with exactly one in_progress item.",
84486
+ {
84487
+ "preparation": {**preparation, "required": list(preparation["properties"])},
84488
+ "items": properties["items"],
84489
+ "in_progress_index": properties["in_progress_index"],
84490
+ },
84491
+ ["preparation", "items"],
84492
+ )
84493
+
84128
84494
  def _single_no_plan_todo_bootstrap_tools(self, *, include_perception: bool = False) -> list[dict]:
84129
84495
  """Return the tools available while establishing the first Todo graph.
84130
84496
 
@@ -84144,7 +84510,7 @@ body{padding:18px}
84144
84510
  # explicit writers accepted by the bootstrap gate below.
84145
84511
  name = str(fn.get("name", "") or "").strip()
84146
84512
  if name in allowed:
84147
- tools.append(spec)
84513
+ tools.append(self._single_no_plan_todo_writer_spec(spec))
84148
84514
  return tools
84149
84515
 
84150
84516
  def _single_no_plan_todo_filter_bootstrap_calls(self, tool_calls: object) -> tuple[list, list[str]]:
@@ -84227,6 +84593,7 @@ body{padding:18px}
84227
84593
  "one TodoWrite or TodoWriteRescue call with suitable next actions and the preparation assessment. "
84228
84594
  "Do not create a list while context is materially missing. ask_user is available for a necessary "
84229
84595
  "clarification. Do not call implementation tools or finish_task.\n"
84596
+ f"{SINGLE_NO_PLAN_TODO_PREPARATION_INSTRUCTION}\n"
84230
84597
  "</single-no-plan-todo-bootstrap>"
84231
84598
  ),
84232
84599
  "ts": now_ts(),
@@ -84264,6 +84631,7 @@ body{padding:18px}
84264
84631
  "once ready, submit the model's own evidence-based TodoWrite or TodoWriteRescue and preparation "
84265
84632
  "assessment, preserving ordered stages and exactly one in_progress item. "
84266
84633
  "Do not manufacture a checklist merely to escape this phase.\n"
84634
+ f"{SINGLE_NO_PLAN_TODO_PREPARATION_INSTRUCTION}\n"
84267
84635
  "</single-no-plan-todo-bootstrap-retry>"
84268
84636
  ),
84269
84637
  "ts": now_ts(),
@@ -84995,6 +85363,9 @@ body{padding:18px}
84995
85363
  base = base + read_context_note + " "
84996
85364
  if web_search_context_note:
84997
85365
  base = base + web_search_context_note + " "
85366
+ goal_note = self._goal_prompt_block()
85367
+ if goal_note:
85368
+ base = base + goal_note + " "
84998
85369
  if task_memory_note:
84999
85370
  base = base + task_memory_note + " "
85000
85371
  if long_content_memory_note:
@@ -85236,7 +85607,7 @@ body{padding:18px}
85236
85607
  "resume", "continue", "resumeexisting", "inprogressindex", "activeindex",
85237
85608
  "currentindex", "nextindex", "updatemode", "mode", "operation", "update",
85238
85609
  "action", "revisionreason", "reason", "changereason", "why",
85239
- "revisionevidence", "references", "planupdates", "options", "meta", "control",
85610
+ "revisionevidence", "references", "planupdates", "options", "meta", "control", "preparation",
85240
85611
  "tool", "toolname", "name", "type", "function", "arguments", "input",
85241
85612
  "role", "toolcallid", "finishreason", "index", "choices", "usage",
85242
85613
  }
@@ -86074,10 +86445,8 @@ body{padding:18px}
86074
86445
  "task_preparation_required",
86075
86446
  "Before initializing Todos, understand the actual goal and current state, consider available skills, "
86076
86447
  "and read selected workflows completely. Continue read-only discovery or ask_user for material gaps. "
86077
- "When ready, resubmit the same intended new rows (omit invented ids) with preparation="
86078
- '{"goal":"brief understood objective","state":"relevant observed or user-provided state",'
86079
- '"skills":"selection or reason no skill is relevant","basis":"user_context|observed_context|continuation",'
86080
- '"ready":true,"missing":[]}. One read is not proof of readiness; no fixed read count is required.')
86448
+ "When ready, resubmit the same intended new rows (omit invented ids). "
86449
+ + SINGLE_NO_PLAN_TODO_PREPARATION_INSTRUCTION)
86081
86450
  goal_summary = str(preparation.get("goal", "") or "").strip()
86082
86451
  state_summary = str(preparation.get("state", "") or "").strip()
86083
86452
  skill_decision = str(preparation.get("skills", "") or "").strip()
@@ -87569,16 +87938,20 @@ body{padding:18px}
87569
87938
  # Safe auto-repair only for todo tools; file/code tools require regenerate.
87570
87939
  if canonicalize_tool_name(name) not in {"TodoWrite", "TodoWriteRescue"}:
87571
87940
  return False, ""
87572
- items = self._todo_payload_items(raw_args, limit=40) if isinstance(raw_args, dict) else []
87941
+ source = decode_structured_todo_container(raw_args)
87942
+ if not isinstance(source, dict):
87943
+ source, _ = parse_tool_arguments_with_error(raw_args)
87944
+ items = self._todo_payload_items(source, limit=40)
87573
87945
  if not items:
87574
87946
  items = self._extract_text_items_from_raw_args(raw_args)
87575
87947
  if not items:
87576
87948
  return False, "no recoverable todo items from malformed arguments"
87949
+ cursor = self._todo_payload_in_progress_index(source)
87950
+ repaired_args = {"items": items, "in_progress_index": 0 if cursor is None else cursor, "resume": True}
87951
+ if "preparation" in source:
87952
+ repaired_args["preparation"] = source["preparation"]
87577
87953
  try:
87578
- output = self._dispatch_tool(
87579
- "TodoWrite",
87580
- {"items": items, "in_progress_index": 0, "resume": True},
87581
- )
87954
+ output = self._dispatch_tool("TodoWrite", repaired_args)
87582
87955
  return True, output
87583
87956
  except Exception as exc:
87584
87957
  return False, f"rescue failed: {exc}"
@@ -87976,6 +88349,28 @@ body{padding:18px}
87976
88349
  allow_free_text = args.get("allow_free_text", True)
87977
88350
  if not isinstance(allow_free_text, bool):
87978
88351
  allow_free_text = str(allow_free_text or "").strip().lower() not in {"false", "0", "no", "off"}
88352
+ goal_proposal: dict = {}
88353
+ goal_condition = str(args.get("goal_condition", "") or "").strip()
88354
+ if goal_condition:
88355
+ if not bool((getattr(self, "goal_preferences", None) or {}).get("allow_model_proposals", False)):
88356
+ return (
88357
+ "Error: goal proposals are off in this session, so goal_condition was not shown to the user. "
88358
+ "Continue the task; do not propose a goal again."
88359
+ )
88360
+ if (getattr(self, "goal_state", None) or {}).get("status") in {"active", "paused"}:
88361
+ return "Error: this session already has a goal; do not propose another. Continue the current goal."
88362
+ if len(goal_condition) > GOAL_OBJECTIVE_MAX_CHARS:
88363
+ return f"Error: goal_condition is longer than {GOAL_OBJECTIVE_MAX_CHARS} characters; state one checkable condition."
88364
+ accept_label, decline_label = GOAL_PROPOSAL_LABELS.get(
88365
+ normalize_ui_language(getattr(self, "ui_language", "")), GOAL_PROPOSAL_LABELS["en"]
88366
+ )
88367
+ goal_proposal = {"objective": goal_condition, "max_turns": self._goal_default_max_turns()}
88368
+ options = [
88369
+ {"label": accept_label, "value": GOAL_PROPOSAL_ACCEPT},
88370
+ {"label": decline_label, "value": GOAL_PROPOSAL_DECLINE},
88371
+ ]
88372
+ allow_free_text = False
88373
+ question = trim(f"{question}\n\n/goal {goal_condition}", 2000 + GOAL_OBJECTIVE_MAX_CHARS)
87979
88374
  # If neither free text nor options are available the user could never answer;
87980
88375
  # fall back to allowing free text.
87981
88376
  if not options and not allow_free_text:
@@ -87987,6 +88382,7 @@ body{padding:18px}
87987
88382
  "allow_free_text": bool(allow_free_text),
87988
88383
  "role": self._sanitize_agent_role(role_key) or (role_key or "agent"),
87989
88384
  "ts": now_ts(),
88385
+ **({"goal_proposal": goal_proposal} if goal_proposal else {}),
87990
88386
  }
87991
88387
  # Flag consumed by both run loops to break-and-pause without finalizing.
87992
88388
  self._ask_user_pause_pending = True
@@ -87999,13 +88395,17 @@ body{padding:18px}
87999
88395
  "options": list(options),
88000
88396
  "allow_free_text": bool(allow_free_text),
88001
88397
  "role": self.pending_user_question["role"],
88398
+ **({"goal_proposal": dict(goal_proposal)} if goal_proposal else {}),
88002
88399
  },
88003
88400
  )
88004
88401
  except Exception:
88005
88402
  pass
88006
88403
  opt_hint = ""
88007
88404
  if options:
88008
- opt_hint = " Options presented: " + " | ".join(options[:8]) + "."
88405
+ # Options may be {label, value} rows; list the values the user can send.
88406
+ opt_hint = " Options presented: " + " | ".join(_ask_user_option_value(option) for option in options[:8]) + "."
88407
+ if goal_proposal:
88408
+ opt_hint += " If the user accepts, the goal is set and this run continues as its first turn."
88009
88409
  return (
88010
88410
  "Question surfaced to the user; the run is now paused and awaiting their reply. "
88011
88411
  "Do not take further action — execution will resume automatically when the user responds."
@@ -88308,6 +88708,8 @@ body{padding:18px}
88308
88708
  # context counts as "already visible". Tools run serially within a
88309
88709
  # session, so an attribute is enough here.
88310
88710
  _READ_DISPATCH_CONTEXT.read_role = role_key
88711
+ previous_tool_call_id = getattr(_READ_DISPATCH_CONTEXT, "tool_call_id", "")
88712
+ _READ_DISPATCH_CONTEXT.tool_call_id = str(tool_call_id or "")
88311
88713
  try:
88312
88714
  out = self._run_read(
88313
88715
  rel,
@@ -88326,6 +88728,7 @@ body{padding:18px}
88326
88728
  )
88327
88729
  finally:
88328
88730
  _READ_DISPATCH_CONTEXT.read_role = ""
88731
+ _READ_DISPATCH_CONTEXT.tool_call_id = previous_tool_call_id
88329
88732
  coordinator = getattr(self, "collaboration_write_coordinator", None)
88330
88733
  if coordinator is not None and not str(out).startswith("Error"):
88331
88734
  try:
@@ -89655,6 +90058,7 @@ body{padding:18px}
89655
90058
 
89656
90059
  def submit_user_message(self, content: str):
89657
90060
  start_worker = False
90061
+ accepted_goal_proposal: dict | None = None
89658
90062
  dropped_stale_inputs = 0
89659
90063
  removed_runtime_hints = 0
89660
90064
  acquired = False
@@ -89807,6 +90211,10 @@ body{padding:18px}
89807
90211
  clean_goal,
89808
90212
  question=_pending_user_question,
89809
90213
  )
90214
+ _proposal = _pending_user_question.get("goal_proposal")
90215
+ if isinstance(_proposal, dict) and str(clean_goal or "").strip() == GOAL_PROPOSAL_ACCEPT:
90216
+ # Applied after the session lock is released (goal_lock is taken first elsewhere).
90217
+ accepted_goal_proposal = dict(_proposal, asked_at=float(_pending_user_question.get("ts", 0.0) or 0.0))
89810
90218
  self.pending_user_question = None
89811
90219
  self._ask_user_pause_pending = False
89812
90220
  self.runtime_reclassify_required = False
@@ -89838,6 +90246,8 @@ body{padding:18px}
89838
90246
  self._mark_runtime_goal_reset_pending(clean_goal, reason="new-user-message")
89839
90247
  self.running = True
89840
90248
  self.run_started_at = now_ts()
90249
+ self._goal_continuation_turn = False
90250
+ self._goal_turn_started_at = self.run_started_at
89841
90251
  self.run_last_heartbeat = self.run_started_at
89842
90252
  self.collaboration_agent_last_heartbeat = 0.0
89843
90253
  self.collaboration_agent_current_file = ""
@@ -89846,7 +90256,7 @@ body{padding:18px}
89846
90256
  self.current_phase = "starting"
89847
90257
  self.current_tool_name = ""
89848
90258
  self.updated_at = now_ts()
89849
- self._emit("message", {"role": "user", "text": content, "summary": "user message"})
90259
+ self._emit("message", {"role": "user", "text": content, "summary": "user message", "user_input": True})
89850
90260
  # _emit(message) performs the immediate durable event persist.
89851
90261
  # Do not write the same complete encrypted state a second time.
89852
90262
  start_worker = True
@@ -89887,6 +90297,8 @@ body{padding:18px}
89887
90297
  "live_input": True,
89888
90298
  "best_effort": bool(row.get("best_effort", False)),
89889
90299
  }
90300
+ if accepted_goal_proposal:
90301
+ self._goal_accept_proposal(accepted_goal_proposal)
89890
90302
  try:
89891
90303
  self._maybe_auto_rename_session_title("message-accepted")
89892
90304
  except Exception:
@@ -89923,6 +90335,12 @@ body{padding:18px}
89923
90335
  # owns the session lock. Set the flag and terminate Bash first, then do
89924
90336
  # the visible/persisted bookkeeping on a best-effort short lock.
89925
90337
  self.cancel_requested = True
90338
+ with self.goal_lock:
90339
+ interrupt_goal = bool(self.goal_state) and self.goal_state.get("status") == "active" and bool(self.running)
90340
+ if interrupt_goal:
90341
+ self._goal_set_status("paused", "interrupted by the user")
90342
+ if interrupt_goal:
90343
+ self._goal_emit("paused", "Goal paused: the run was interrupted; /goal resume continues it")
89926
90344
  _proc = getattr(self, "_running_bash_proc", None)
89927
90345
  if _proc is not None:
89928
90346
  try:
@@ -89961,6 +90379,758 @@ body{padding:18px}
89961
90379
  except Exception:
89962
90380
  pass
89963
90381
 
90382
+ # ── Goal mode ──────────────────────────────────────────────────────────
90383
+ # One completion condition per session. The user sets it with /goal; the
90384
+ # runtime keeps starting turns until a separate evaluator call finds the
90385
+ # condition met in the run's evidence, judges it impossible, a budget runs
90386
+ # out, or the goal stalls. Interrupts pause the goal.
90387
+
90388
+ @staticmethod
90389
+ def _goal_parse_amount(raw: str, unit_scale: dict) -> int:
90390
+ match = re.fullmatch(r"(\d+(?:\.\d+)?)([a-z]*)", str(raw or "").strip().lower())
90391
+ if not match or match.group(2) not in unit_scale:
90392
+ raise ValueError(f"invalid amount: {raw}")
90393
+ return int(float(match.group(1)) * unit_scale[match.group(2)])
90394
+
90395
+ @staticmethod
90396
+ def parse_plan_command(text: str) -> dict | None:
90397
+ """Parse '/plan …'. Returns None when the text is not a plan command.
90398
+
90399
+ ``/plan`` turns plan mode on; ``/plan on|off|auto`` sets it;
90400
+ ``/plan <task>`` turns it on and returns the task to submit.
90401
+ """
90402
+ match = re.match(r"^/plan(?:\s+|$)([\s\S]*)$", str(text or "").strip(), flags=re.IGNORECASE)
90403
+ if not match:
90404
+ return None
90405
+ rest = match.group(1).strip()
90406
+ if rest.lower() in PLAN_MODE_USER_CHOICES:
90407
+ return {"preference": rest.lower(), "task": ""}
90408
+ return {"preference": "on", "task": rest}
90409
+
90410
+ def plan_command(self, command: dict) -> dict:
90411
+ """Apply a parsed /plan command: the same setting as the composer's plan button."""
90412
+ pref = str((command or {}).get("preference", "on") or "on").strip().lower()
90413
+ if pref not in PLAN_MODE_USER_CHOICES:
90414
+ pref = "on"
90415
+ self.plan_mode_user_preference = pref
90416
+ self._schedule_persist_delayed(0.2)
90417
+ summary = {
90418
+ "on": "Plan mode on: the agent proposes a plan before it works",
90419
+ "off": "Plan mode off",
90420
+ "auto": "Plan mode auto: the agent decides per task",
90421
+ }[pref]
90422
+ task = str((command or {}).get("task", "") or "").strip()
90423
+ try:
90424
+ self._emit("slash_command", {
90425
+ "command": "plan", "phase": "plan_mode", "mode": pref, "summary": summary,
90426
+ **({"action": "task"} if task else {}),
90427
+ })
90428
+ except Exception:
90429
+ pass
90430
+ return {"ok": True, "slash_command": "plan", "plan_mode": pref, "summary": summary}
90431
+
90432
+ @classmethod
90433
+ def parse_goal_command(cls, text: str) -> dict | None:
90434
+ """Parse '/goal …'. Returns None when the text is not a goal command.
90435
+
90436
+ Forms: ``/goal`` or ``/goal status``; ``/goal pause|resume|clear``;
90437
+ ``/goal propose on|off`` (model goal proposals, which need the user's
90438
+ confirmation); ``/goal [--turns N] [--tokens N[k|m]] [--time N[s|m|h]] <condition>``.
90439
+ """
90440
+ raw = str(text or "").strip()
90441
+ match = re.match(r"^/goal(?:\s+|$)([\s\S]*)$", raw, flags=re.IGNORECASE)
90442
+ if not match:
90443
+ return None
90444
+ rest = match.group(1).strip()
90445
+ word = rest.lower()
90446
+ if word in {"", "status", "show"}:
90447
+ return {"action": "status"}
90448
+ if word in {"pause", "resume", "clear"}:
90449
+ return {"action": word}
90450
+ if word in {"stop", "off", "cancel"}:
90451
+ return {"action": "clear"}
90452
+ propose = re.fullmatch(r"propose\s+(on|off)", word)
90453
+ if propose:
90454
+ return {"action": "preferences", "allow_model_proposals": propose.group(1) == "on"}
90455
+ budgets: dict = {}
90456
+ flag = re.compile(r"^--(turns|tokens|time)(?:=|\s+)(\S+)\s*", flags=re.IGNORECASE)
90457
+ while True:
90458
+ found = flag.match(rest)
90459
+ if not found:
90460
+ break
90461
+ name, value = found.group(1).lower(), found.group(2)
90462
+ rest = rest[found.end():]
90463
+ if name == "turns":
90464
+ budgets["max_turns"] = cls._goal_parse_amount(value, {"": 1})
90465
+ elif name == "tokens":
90466
+ budgets["token_budget"] = cls._goal_parse_amount(value, {"": 1, "k": 1000, "m": 1_000_000})
90467
+ else:
90468
+ budgets["time_budget_seconds"] = cls._goal_parse_amount(value, {"": 60, "s": 1, "m": 60, "h": 3600})
90469
+ objective = rest.strip()
90470
+ if not objective:
90471
+ raise ValueError("goal condition required: /goal <condition>")
90472
+ if len(objective) > GOAL_OBJECTIVE_MAX_CHARS:
90473
+ raise ValueError(f"goal condition is longer than {GOAL_OBJECTIVE_MAX_CHARS} characters")
90474
+ if "max_turns" in budgets and not 1 <= int(budgets["max_turns"]) <= GOAL_MAX_TURNS_LIMIT:
90475
+ raise ValueError(f"--turns must be between 1 and {GOAL_MAX_TURNS_LIMIT}")
90476
+ return {"action": "set", "objective": objective, **budgets}
90477
+
90478
+ def _goal_default_max_turns(self) -> int:
90479
+ """Turn budget of a goal set without --turns: the session preference, else the admin default."""
90480
+ prefs = getattr(self, "goal_preferences", None) or {}
90481
+ for value in (prefs.get("max_turns"), getattr(self, "goal_default_turns", GOAL_DEFAULT_MAX_TURNS)):
90482
+ try:
90483
+ turns = int(value or 0)
90484
+ except (TypeError, ValueError):
90485
+ turns = 0
90486
+ if turns > 0:
90487
+ return max(1, min(GOAL_MAX_TURNS_LIMIT, turns))
90488
+ return GOAL_DEFAULT_MAX_TURNS
90489
+
90490
+ @staticmethod
90491
+ def _goal_normalize_preferences(raw: object) -> dict:
90492
+ """Composer goal-menu choices; budgets of 0 fall back to the defaults."""
90493
+ src = raw if isinstance(raw, dict) else {}
90494
+
90495
+ def _int(key: str, limit: int) -> int:
90496
+ try:
90497
+ return max(0, min(limit, int(src.get(key, 0) or 0)))
90498
+ except (TypeError, ValueError):
90499
+ return 0
90500
+
90501
+ return {
90502
+ "max_turns": _int("max_turns", GOAL_MAX_TURNS_LIMIT),
90503
+ "token_budget": _int("token_budget", GOAL_TOKEN_BUDGET_LIMIT),
90504
+ "time_budget_seconds": _int("time_budget_seconds", GOAL_TIME_BUDGET_LIMIT_SECONDS),
90505
+ "allow_model_proposals": bool(src.get("allow_model_proposals", False)),
90506
+ }
90507
+
90508
+ def goal_public_preferences(self) -> dict:
90509
+ """Composer goal-menu state; ``default_turns`` is the admin default (--goal_turns)."""
90510
+ prefs = self._goal_normalize_preferences(getattr(self, "goal_preferences", None))
90511
+ try:
90512
+ default_turns = max(1, min(GOAL_MAX_TURNS_LIMIT, int(getattr(self, "goal_default_turns", 0) or 0)))
90513
+ except (TypeError, ValueError):
90514
+ default_turns = GOAL_DEFAULT_MAX_TURNS
90515
+ prefs["default_turns"] = default_turns
90516
+ prefs["effective_turns"] = int(prefs.get("max_turns", 0) or 0) or default_turns
90517
+ prefs["max_turns_limit"] = GOAL_MAX_TURNS_LIMIT
90518
+ return prefs
90519
+
90520
+ def goal_set_preferences(self, updates: dict) -> dict:
90521
+ """Merge composer goal-menu changes; returns the stored preferences."""
90522
+ merged = dict(self.goal_preferences or {})
90523
+ merged.update({key: value for key, value in (updates or {}).items() if key in GOAL_PREFERENCE_KEYS})
90524
+ self.goal_preferences = self._goal_normalize_preferences(merged)
90525
+ self._schedule_persist_delayed(0.2)
90526
+ return dict(self.goal_preferences)
90527
+
90528
+ def _goal_normalize_state(self, raw: object) -> dict:
90529
+ src = raw if isinstance(raw, dict) else {}
90530
+ objective = trim(str(src.get("objective", "") or "").strip(), GOAL_OBJECTIVE_MAX_CHARS)
90531
+ status = str(src.get("status", "") or "").strip().lower()
90532
+ if not objective or status not in GOAL_STATUSES:
90533
+ return {}
90534
+
90535
+ def _num(key: str, cast=int, default=0, row: dict | None = None):
90536
+ try:
90537
+ return max(0, cast((row if row is not None else src).get(key, default) or default))
90538
+ except Exception:
90539
+ return default
90540
+
90541
+ raw_verdicts = src.get("verdicts") if isinstance(src.get("verdicts"), list) else []
90542
+ verdicts = [
90543
+ {
90544
+ "turn": _num("turn", row=row),
90545
+ "verdict": str(row.get("verdict", "") or "")[:20],
90546
+ "reason": trim(str(row.get("reason", "") or ""), 600),
90547
+ "next_step": trim(str(row.get("next_step", "") or ""), 400),
90548
+ "ts": _num("ts", float, 0.0, row=row),
90549
+ }
90550
+ for row in raw_verdicts[-GOAL_VERDICT_HISTORY_MAX:]
90551
+ if isinstance(row, dict)
90552
+ ]
90553
+ return {
90554
+ "id": str(src.get("id", "") or make_id("goal")),
90555
+ "objective": objective,
90556
+ "status": status,
90557
+ "status_reason": trim(str(src.get("status_reason", "") or ""), 400),
90558
+ "created_at": _num("created_at", float, 0.0) or now_ts(),
90559
+ "updated_at": _num("updated_at", float, 0.0) or now_ts(),
90560
+ "active_since": _num("active_since", float, 0.0) if status == "active" else 0.0,
90561
+ "time_used_seconds": _num("time_used_seconds", float, 0.0),
90562
+ "turns": _num("turns"),
90563
+ "max_turns": min(GOAL_MAX_TURNS_LIMIT, _num("max_turns") or self._goal_default_max_turns()),
90564
+ "token_budget": _num("token_budget"),
90565
+ "tokens_used": _num("tokens_used"),
90566
+ "time_budget_seconds": _num("time_budget_seconds"),
90567
+ "no_progress_streak": _num("no_progress_streak"),
90568
+ "error_streak": _num("error_streak"),
90569
+ "evaluation_failures": _num("evaluation_failures"),
90570
+ "verdicts": verdicts,
90571
+ }
90572
+
90573
+ def _goal_time_used(self, state: dict | None = None, at: float | None = None) -> float:
90574
+ goal = state if isinstance(state, dict) else (self.goal_state or {})
90575
+ used = float(goal.get("time_used_seconds", 0.0) or 0.0)
90576
+ since = float(goal.get("active_since", 0.0) or 0.0)
90577
+ if goal.get("status") == "active" and since > 0:
90578
+ used += max(0.0, float(at or now_ts()) - since)
90579
+ return used
90580
+
90581
+ def _goal_set_status(self, status: str, reason: str = "") -> None:
90582
+ """Change the goal status, folding active time into the total."""
90583
+ goal = self.goal_state
90584
+ if not goal or status not in GOAL_STATUSES:
90585
+ return
90586
+ stamp = now_ts()
90587
+ if goal.get("status") == "active" and status != "active":
90588
+ goal["time_used_seconds"] = self._goal_time_used(goal, stamp)
90589
+ goal["active_since"] = 0.0
90590
+ elif status == "active" and goal.get("status") != "active":
90591
+ goal["active_since"] = stamp
90592
+ goal["status"] = status
90593
+ goal["status_reason"] = trim(str(reason or ""), 400)
90594
+ goal["updated_at"] = stamp
90595
+
90596
+ def goal_public_state(self) -> dict:
90597
+ """Goal fields for snapshots, the IDE feed and command replies."""
90598
+ goal = self.goal_state or {}
90599
+ if not goal:
90600
+ return {}
90601
+ verdicts = list(goal.get("verdicts") or [])
90602
+ return {
90603
+ "id": str(goal.get("id", "")),
90604
+ "objective": str(goal.get("objective", "")),
90605
+ "status": str(goal.get("status", "")),
90606
+ "status_reason": str(goal.get("status_reason", "")),
90607
+ "turns": int(goal.get("turns", 0) or 0),
90608
+ "max_turns": int(goal.get("max_turns", 0) or 0),
90609
+ "tokens_used": int(goal.get("tokens_used", 0) or 0),
90610
+ "token_budget": int(goal.get("token_budget", 0) or 0),
90611
+ "time_used_seconds": round(self._goal_time_used(goal), 1),
90612
+ "time_budget_seconds": int(goal.get("time_budget_seconds", 0) or 0),
90613
+ "created_at": float(goal.get("created_at", 0.0) or 0.0),
90614
+ "updated_at": float(goal.get("updated_at", 0.0) or 0.0),
90615
+ "evaluating": bool(getattr(self, "goal_evaluating", False)),
90616
+ "active_since": float(goal.get("active_since", 0.0) or 0.0),
90617
+ "time_banked_seconds": round(float(goal.get("time_used_seconds", 0.0) or 0.0), 1),
90618
+ "last_verdict": dict(verdicts[-1]) if verdicts else {},
90619
+ "verdicts": [dict(row) for row in verdicts[-8:]],
90620
+ }
90621
+
90622
+ def _goal_emit(self, phase: str, summary: str, **extra) -> None:
90623
+ """Publish one goal card for the web and IDE feeds."""
90624
+ data = {"phase": phase, "summary": trim(str(summary or ""), 600), "goal": self.goal_public_state()}
90625
+ data.update({key: value for key, value in extra.items() if value not in (None, "")})
90626
+ try:
90627
+ self._emit("goal", data)
90628
+ except Exception:
90629
+ pass
90630
+
90631
+ def _goal_note_usage(self, total_tokens: int) -> None:
90632
+ goal = self.goal_state
90633
+ if goal and goal.get("status") == "active" and int(total_tokens or 0) > 0:
90634
+ goal["tokens_used"] = int(goal.get("tokens_used", 0) or 0) + int(total_tokens)
90635
+
90636
+ def _goal_accept_proposal(self, proposal: dict) -> None:
90637
+ """The user accepted an ask_user goal proposal: set the goal; the resumed run is its first turn."""
90638
+ objective = str((proposal or {}).get("objective", "") or "").strip()
90639
+ if not objective or len(objective) > GOAL_OBJECTIVE_MAX_CHARS:
90640
+ return
90641
+ self.goal_command({"action": "set", "objective": objective, "source": "proposal"})
90642
+ asked_at = float((proposal or {}).get("asked_at", 0.0) or 0.0)
90643
+ with self.goal_lock:
90644
+ goal = self.goal_state or {}
90645
+ # The evaluator reads the conversation from the question on, so the work
90646
+ # that led to the proposal counts as evidence.
90647
+ if goal and 0.0 < asked_at < float(goal.get("created_at", 0.0) or 0.0):
90648
+ goal["created_at"] = asked_at
90649
+
90650
+ def _goal_proposal_prompt_block(self) -> str:
90651
+ if not bool((getattr(self, "goal_preferences", None) or {}).get("allow_model_proposals", False)):
90652
+ return ""
90653
+ if (getattr(self, "goal_state", None) or {}).get("status") in {"active", "paused"}:
90654
+ return ""
90655
+ return (
90656
+ "<goal-proposals>The user allows you to propose a session goal. When the task is long or has a checkable"
90657
+ " end state (tests pass, a build succeeds, a file meets a stated check), you may call ask_user once with"
90658
+ " goal_condition set to one verifiable completion condition and a one-sentence question. The goal starts"
90659
+ " only if the user accepts; then the runtime keeps starting turns until an evaluator finds the condition"
90660
+ " met. Do not propose a goal for short questions or chat, and do not propose again after the user"
90661
+ " declines.</goal-proposals>"
90662
+ )
90663
+
90664
+ def _goal_prompt_block(self) -> str:
90665
+ """Model-facing goal anchor, rebuilt every request so compaction cannot drop it."""
90666
+ goal = self.goal_state or {}
90667
+ if goal.get("status") != "active":
90668
+ return self._goal_proposal_prompt_block()
90669
+ turn = int(goal.get("turns", 0) or 0) + 1
90670
+ lines = [
90671
+ f"<active-goal turn=\"{turn}\" max_turns=\"{int(goal.get('max_turns', 0) or 0)}\">",
90672
+ "The user set this completion condition with /goal. It stays the objective of every turn until it holds:",
90673
+ str(goal.get("objective", "")),
90674
+ "After each turn a separate evaluator, which sees only this conversation, decides whether the condition holds."
90675
+ " Work on the part of the condition that is still unmet, verify it with a real check (run the tests, the build or"
90676
+ " a listing) and leave that output in the conversation. A claim without visible evidence does not count."
90677
+ " Do not ask the user for routine confirmation. If the condition cannot be met in this environment, state the"
90678
+ " blocker and the evidence for it plainly.",
90679
+ ]
90680
+ verdicts = list(goal.get("verdicts") or [])
90681
+ if verdicts:
90682
+ last = verdicts[-1]
90683
+ lines.append(f"Last evaluator verdict ({last.get('verdict', '')}): {last.get('reason', '')}")
90684
+ if str(last.get("next_step", "") or "").strip():
90685
+ lines.append(f"Evaluator's next step: {last.get('next_step', '')}")
90686
+ lines.append("</active-goal>")
90687
+ return "\n".join(lines)
90688
+
90689
+ def goal_command(self, command: dict) -> dict:
90690
+ """Apply a parsed /goal command to this session's goal state.
90691
+
90692
+ ``set`` returns ``start_text``: the caller submits it as the user's
90693
+ message, which starts the first turn. ``resume`` returns
90694
+ ``resume_run`` when the session is idle and the next turn must start.
90695
+ """
90696
+ action = str((command or {}).get("action", "status") or "status")
90697
+ out: dict = {"ok": True, "goal_command": True, "action": action}
90698
+ phase, summary = action, ""
90699
+ with self.goal_lock:
90700
+ goal = self.goal_state
90701
+ status = str(goal.get("status", "") or "") if goal else ""
90702
+ if action == "set":
90703
+ stamp = now_ts()
90704
+ prefs = self.goal_preferences or {}
90705
+ self.goal_state = {
90706
+ "id": make_id("goal"),
90707
+ "objective": str(command.get("objective", "")).strip(),
90708
+ "status": "active",
90709
+ "status_reason": "",
90710
+ "created_at": stamp,
90711
+ "updated_at": stamp,
90712
+ "active_since": stamp,
90713
+ "time_used_seconds": 0.0,
90714
+ "turns": 0,
90715
+ "max_turns": int(command.get("max_turns", 0) or 0) or self._goal_default_max_turns(),
90716
+ "token_budget": int(command.get("token_budget", prefs.get("token_budget", 0)) or 0),
90717
+ "tokens_used": 0,
90718
+ "time_budget_seconds": int(command.get("time_budget_seconds", prefs.get("time_budget_seconds", 0)) or 0),
90719
+ "no_progress_streak": 0,
90720
+ "error_streak": 0,
90721
+ "evaluation_failures": 0,
90722
+ "verdicts": [],
90723
+ }
90724
+ out["start_text"] = self.goal_state["objective"]
90725
+ summary = (
90726
+ "Goal set from the agent's proposal" if command.get("source") == "proposal" else "Goal set"
90727
+ ) + (" (replaced the previous goal)" if goal else "")
90728
+ elif action == "pause":
90729
+ if status != "active":
90730
+ out.update(ok=False, error="no active goal to pause")
90731
+ else:
90732
+ self._goal_set_status("paused", "paused by the user")
90733
+ summary = "Goal paused"
90734
+ elif action == "resume":
90735
+ if status != "paused":
90736
+ out.update(ok=False, error="no paused goal to resume" if status != "active" else "goal is already active")
90737
+ else:
90738
+ self._goal_set_status("active", "")
90739
+ for key in ("no_progress_streak", "error_streak", "evaluation_failures"):
90740
+ self.goal_state[key] = 0
90741
+ out["resume_run"] = not bool(getattr(self, "running", False))
90742
+ summary = "Goal resumed"
90743
+ elif action == "preferences":
90744
+ self.goal_set_preferences({
90745
+ key: command[key] for key in GOAL_PREFERENCE_KEYS if key in (command or {})
90746
+ })
90747
+ proposals = bool((self.goal_preferences or {}).get("allow_model_proposals", False))
90748
+ summary = "Model goal proposals " + ("on: the agent may propose a goal for you to confirm" if proposals else "off")
90749
+ elif action == "clear":
90750
+ if not goal:
90751
+ out.update(ok=False, error="no goal is set")
90752
+ else:
90753
+ self._goal_set_status("paused", "cleared by the user")
90754
+ summary = "Goal cleared"
90755
+ else:
90756
+ summary = "Goal status" if goal else "No goal is set"
90757
+ out["goal"] = self.goal_public_state()
90758
+ out["preferences"] = self.goal_public_preferences()
90759
+ if action == "clear" and out.get("ok"):
90760
+ out["goal"]["status"] = "cleared"
90761
+ self.goal_state = {}
90762
+ if out.get("ok"):
90763
+ extra: dict = {"goal": out["goal"]} if action == "clear" else {}
90764
+ if action == "preferences":
90765
+ extra["mode"] = "on" if out["preferences"].get("allow_model_proposals") else "off"
90766
+ if action == "set" and (command or {}).get("source") == "proposal":
90767
+ extra["origin"] = "proposal"
90768
+ self._goal_emit(phase, summary, **extra)
90769
+ if action != "status":
90770
+ self._schedule_persist_delayed(0.2)
90771
+ else:
90772
+ self._goal_emit("error", str(out.get("error", "")))
90773
+ out["summary"] = summary or str(out.get("error", ""))
90774
+ return out
90775
+
90776
+ def _goal_turn_evidence(self, max_chars: int = GOAL_EVIDENCE_MAX_CHARS) -> str:
90777
+ """What the evaluator may judge: the conversation since the goal was set.
90778
+
90779
+ Newest rows win the character budget, so the last turn's checks are
90780
+ always present; older work appears as far as the budget allows,
90781
+ including the compaction summary that replaced earlier rows.
90782
+ """
90783
+ goal = self.goal_state or {}
90784
+ since = float(goal.get("created_at", 0.0) or 0.0) - 1.0
90785
+ with self.lock:
90786
+ rows = [dict(row) for row in self.messages if isinstance(row, dict)]
90787
+ tool_names: dict[str, str] = {}
90788
+ for row in rows:
90789
+ for call in row.get("tool_calls") or []:
90790
+ if isinstance(call, dict):
90791
+ fn = call.get("function") if isinstance(call.get("function"), dict) else {}
90792
+ tool_names[str(call.get("id", ""))] = str(fn.get("name", "") or "tool")
90793
+ blocks: list[str] = []
90794
+ used = 0
90795
+ for row in reversed(rows):
90796
+ if float(row.get("ts", 0.0) or 0.0) < since:
90797
+ break
90798
+ role = str(row.get("role", "") or "")
90799
+ text = self._runtime_message_text(row).strip()
90800
+ if role == "user":
90801
+ if self._runtime_message_control_tag(row) == "compact-resume" or text.lower().startswith("<compact-resume"):
90802
+ block = "EARLIER WORK (compaction summary):\n" + trim(text, 4000)
90803
+ elif self._is_external_user_message_for_goal_tracking(row):
90804
+ block = "USER: " + trim(text, 1500)
90805
+ else:
90806
+ continue
90807
+ elif role == "assistant":
90808
+ parts = []
90809
+ clean = strip_thinking_content(text).strip()
90810
+ if clean:
90811
+ parts.append("AGENT: " + trim(clean, 2000))
90812
+ for call in row.get("tool_calls") or []:
90813
+ fn = call.get("function") if isinstance(call, dict) and isinstance(call.get("function"), dict) else {}
90814
+ parts.append(f"CALL {fn.get('name', 'tool')}: {trim(str(fn.get('arguments', '') or ''), 400)}")
90815
+ if not parts:
90816
+ continue
90817
+ block = "\n".join(parts)
90818
+ elif role == "tool":
90819
+ name = tool_names.get(str(row.get("tool_call_id", "")), "tool")
90820
+ body = text if len(text) <= 2400 else text[:700] + "\n…\n" + text[-1700:]
90821
+ block = f"RESULT {name}:\n{body}"
90822
+ else:
90823
+ continue
90824
+ if used + len(block) > max_chars:
90825
+ blocks.append("[older rows omitted]")
90826
+ break
90827
+ blocks.append(block)
90828
+ used += len(block) + 2
90829
+ blocks.reverse()
90830
+ try:
90831
+ todos = self.todo.render() if self.todo.snapshot() else ""
90832
+ except Exception:
90833
+ todos = ""
90834
+ if todos:
90835
+ blocks.append("TODO LIST:\n" + trim(todos, 3000))
90836
+ return "\n\n".join(blocks)
90837
+
90838
+ def _build_goal_evaluator_client(self) -> OllamaClient:
90839
+ """Fresh client for the evaluator; uses the arbiter model when one is set."""
90840
+ client = OllamaClient(self.ollama.base_url, self.ollama.model)
90841
+ active_profile = dict(self.model_profiles.get(self.active_profile_id, {}))
90842
+ if active_profile:
90843
+ try:
90844
+ client.apply_profile(active_profile)
90845
+ except Exception:
90846
+ pass
90847
+ model_override = str(getattr(self, "arbiter_model", "") or "").strip()
90848
+ if model_override:
90849
+ client.model = model_override
90850
+ client.thinking_stream = False
90851
+ client.timeout = GOAL_EVALUATOR_TIMEOUT_SECONDS
90852
+ client.request_gate = self._ensure_llm_gate()
90853
+ client.set_telemetry(
90854
+ getattr(self, "telemetry_callback", None),
90855
+ context_provider=lambda: {
90856
+ "session_id": self.id,
90857
+ "app_id": str((self.app_binding or {}).get("app_id", "") or ""),
90858
+ },
90859
+ name="goal_eval",
90860
+ )
90861
+ return client
90862
+
90863
+ def _goal_evaluate(self, evidence: str) -> dict:
90864
+ """Ask a model that did not do the work whether the condition holds.
90865
+
90866
+ Returns {"verdict": met|not_met|impossible, "reason", "next_step"} or
90867
+ {"verdict": "error", "reason"} when no usable answer came back.
90868
+ """
90869
+ goal = self.goal_state or {}
90870
+ system = (
90871
+ "You are the goal evaluator for an autonomous coding agent. You did not do the work. "
90872
+ "Decide from the evidence alone whether the user's completion condition holds now.\n"
90873
+ "- met: the evidence shows every part of the condition, for example test output with passing "
90874
+ "results, a command with exit 0, or a listing that shows the required files. The agent saying "
90875
+ "it is done is not evidence. Constraints in the condition (things that must not change) must not be "
90876
+ "visibly violated.\n"
90877
+ "- impossible: the evidence shows the condition cannot be met in this environment, for example "
90878
+ "missing credentials or access, contradictory requirements, or a decision only the user can make, "
90879
+ "and more turns would not change that.\n"
90880
+ "- not_met: anything else. Name the single most useful next step.\n"
90881
+ "If the condition contains a turn or time limit, judge it against the counters given.\n"
90882
+ "Answer with JSON only: {\"verdict\":\"met|not_met|impossible\",\"reason\":\"<=60 words, cite the "
90883
+ "evidence\",\"next_step\":\"<=40 words, empty when met\"}"
90884
+ )
90885
+ system = self._inject_runtime_environment_context(system)
90886
+ counters = (
90887
+ f"turn {int(goal.get('turns', 0) or 0)} of at most {int(goal.get('max_turns', 0) or 0)}; "
90888
+ f"time used {int(self._goal_time_used(goal))} s; tokens used {int(goal.get('tokens_used', 0) or 0)}"
90889
+ )
90890
+ prompt = (
90891
+ f"COMPLETION CONDITION:\n{goal.get('objective', '')}\n\nCOUNTERS: {counters}\n\n"
90892
+ f"EVIDENCE (oldest first):\n{evidence or '(no rows)'}"
90893
+ )
90894
+ last_error = ""
90895
+ for attempt in range(GOAL_EVALUATOR_ATTEMPTS):
90896
+ if self.cancel_requested:
90897
+ return {"verdict": "error", "reason": "interrupted"}
90898
+ try:
90899
+ rsp = self._build_goal_evaluator_client().chat(
90900
+ [{"role": "user", "content": prompt}],
90901
+ system=system,
90902
+ max_tokens=GOAL_EVALUATOR_MAX_TOKENS,
90903
+ temperature=0.0,
90904
+ think=False,
90905
+ stream_thinking=False,
90906
+ label="goal_eval",
90907
+ request_timeout=GOAL_EVALUATOR_TIMEOUT_SECONDS,
90908
+ )
90909
+ except Exception as exc:
90910
+ last_error = trim(str(exc), 240) or exc.__class__.__name__
90911
+ time.sleep(min(5.0, 1.0 + attempt * 2.0))
90912
+ continue
90913
+ raw = str((rsp or {}).get("content", "") or "")
90914
+ payload = extract_json_object_from_text(raw, {}) or extract_json_object_from_text(
90915
+ str((rsp or {}).get("thinking", "") or ""), {}
90916
+ )
90917
+ verdict = str(payload.get("verdict", "") or "").strip().lower().replace("-", "_").replace(" ", "_")
90918
+ if verdict in {"met", "not_met", "impossible"}:
90919
+ return {
90920
+ "verdict": verdict,
90921
+ "reason": trim(str(payload.get("reason", "") or ""), 600),
90922
+ "next_step": trim(str(payload.get("next_step", "") or ""), 400) if verdict != "met" else "",
90923
+ }
90924
+ last_error = "evaluator reply had no verdict: " + trim(raw, 160)
90925
+ return {"verdict": "error", "reason": last_error or "no evaluator reply"}
90926
+
90927
+ def _goal_waiting_for_user(self) -> str:
90928
+ """Why the run stopped for the user, if it did; the goal then waits for the reply."""
90929
+ if isinstance(getattr(self, "pending_user_question", None), dict):
90930
+ return "the agent asked you a question"
90931
+ if bool(getattr(self, "runtime_plan_proposal", None)) and not bool(getattr(self, "runtime_plan_approved", False)):
90932
+ return "a plan is waiting for your choice"
90933
+ if bool(getattr(self, "runtime_confirmation_needed", False)) and int(getattr(self, "runtime_task_level", 0) or 0) == 5:
90934
+ return "the task needs your confirmation"
90935
+ return ""
90936
+
90937
+ def _goal_turn_tool_calls(self, since: float) -> int:
90938
+ with self.lock:
90939
+ from_messages = sum(
90940
+ len(row.get("tool_calls") or [])
90941
+ for row in self.messages
90942
+ if isinstance(row, dict) and row.get("role") == "assistant" and float(row.get("ts", 0.0) or 0.0) >= since
90943
+ )
90944
+ from_events = sum(
90945
+ 1
90946
+ for op in self.operations
90947
+ if isinstance(op, dict) and op.get("type") == "tool_start" and float(op.get("ts", 0.0) or 0.0) >= since
90948
+ )
90949
+ # Compaction can remove this turn's rows from messages; events keep them.
90950
+ return max(from_messages, from_events)
90951
+
90952
+ def _goal_has_unapplied_user_input(self) -> bool:
90953
+ with self.live_input_queue_lock:
90954
+ rows = list(self.pending_user_inputs or [])
90955
+ return any(
90956
+ isinstance(row, dict) and str(row.get("content", "") or "").strip() and not int(row.get("applied_count", 0) or 0)
90957
+ for row in rows
90958
+ )
90959
+
90960
+ @staticmethod
90961
+ def _goal_error_needs_user(error: BaseException | None) -> bool:
90962
+ """Errors more turns cannot fix: rejected credentials, unknown model, bad request."""
90963
+ status = int(getattr(error, "status", 0) or 0) if error is not None else 0
90964
+ return status in {400, 401, 403, 404}
90965
+
90966
+ def _goal_after_run(self, run_error: BaseException | None = None) -> dict | None:
90967
+ """Evaluate the active goal once a run ends; return the next turn's directive or None."""
90968
+ with self.goal_lock:
90969
+ goal = self.goal_state
90970
+ if not goal or goal.get("status") != "active":
90971
+ return None
90972
+ goal_id = str(goal.get("id", ""))
90973
+ if self.cancel_requested:
90974
+ with self.goal_lock:
90975
+ if self.goal_state.get("id") == goal_id and self.goal_state.get("status") == "active":
90976
+ self._goal_set_status("paused", "interrupted by the user")
90977
+ self._goal_emit("paused", "Goal paused: the run was interrupted")
90978
+ return None
90979
+ waiting = self._goal_waiting_for_user()
90980
+ if waiting:
90981
+ self._goal_emit("waiting", f"Goal waiting: {waiting}")
90982
+ return None
90983
+ if self._goal_has_unapplied_user_input():
90984
+ # The user's message starts the next run; the goal is evaluated after it.
90985
+ self._goal_emit("deferred", "Goal continues after your new message")
90986
+ return None
90987
+ if run_error is not None and self._goal_error_needs_user(run_error):
90988
+ with self.goal_lock:
90989
+ if self.goal_state.get("id") == goal_id:
90990
+ self._goal_set_status("paused", "the model request failed: " + trim(str(run_error), 240))
90991
+ self._goal_emit("paused", "Goal paused: the model request failed; fix the model settings, then /goal resume")
90992
+ return None
90993
+ since = float(getattr(self, "_goal_turn_started_at", 0.0) or 0.0) or float(self.run_started_at or 0.0)
90994
+ tool_calls = self._goal_turn_tool_calls(since)
90995
+ self.goal_evaluating = True
90996
+ self.current_phase = "goal-evaluating"
90997
+ self._goal_emit("evaluating", "Checking the goal condition")
90998
+ try:
90999
+ verdict = self._goal_evaluate(self._goal_turn_evidence())
91000
+ finally:
91001
+ self.goal_evaluating = False
91002
+ directive = None
91003
+ with self.goal_lock:
91004
+ goal = self.goal_state
91005
+ if not goal or goal.get("id") != goal_id or goal.get("status") != "active":
91006
+ return None # paused, cleared or replaced while the evaluator ran
91007
+ goal["turns"] = turn = int(goal.get("turns", 0) or 0) + 1
91008
+ kind = str(verdict.get("verdict", "error"))
91009
+ goal["evaluation_failures"] = int(goal.get("evaluation_failures", 0) or 0) + 1 if kind == "error" else 0
91010
+ goal["error_streak"] = int(goal.get("error_streak", 0) or 0) + 1 if run_error is not None else 0
91011
+ goal["no_progress_streak"] = int(goal.get("no_progress_streak", 0) or 0) + 1 if tool_calls == 0 else 0
91012
+ goal.setdefault("verdicts", []).append({
91013
+ "turn": turn, "verdict": kind, "reason": str(verdict.get("reason", "")),
91014
+ "next_step": str(verdict.get("next_step", "")), "ts": now_ts(),
91015
+ })
91016
+ goal["verdicts"] = goal["verdicts"][-GOAL_VERDICT_HISTORY_MAX:]
91017
+ goal["updated_at"] = now_ts()
91018
+ tokens, budget = int(goal.get("tokens_used", 0) or 0), int(goal.get("token_budget", 0) or 0)
91019
+ seconds, time_budget = self._goal_time_used(goal), int(goal.get("time_budget_seconds", 0) or 0)
91020
+ if kind == "met":
91021
+ self._goal_set_status("complete", str(verdict.get("reason", "")))
91022
+ phase, summary = "complete", "Goal achieved"
91023
+ elif kind == "impossible":
91024
+ self._goal_set_status("impossible", str(verdict.get("reason", "")))
91025
+ phase, summary = "impossible", "Goal stopped: the evaluator judged the condition impossible"
91026
+ elif goal["evaluation_failures"] >= GOAL_EVALUATION_FAILURE_PAUSE:
91027
+ self._goal_set_status("paused", "the evaluator failed: " + str(verdict.get("reason", "")))
91028
+ phase, summary = "paused", f"Goal paused: the evaluator failed {goal['evaluation_failures']} times in a row"
91029
+ elif goal["error_streak"] >= GOAL_ERROR_PAUSE_TURNS:
91030
+ self._goal_set_status("paused", "runs failed: " + trim(str(run_error), 240))
91031
+ phase, summary = "paused", f"Goal paused: {goal['error_streak']} runs in a row ended with an error"
91032
+ elif goal["no_progress_streak"] >= GOAL_NO_PROGRESS_PAUSE_TURNS:
91033
+ self._goal_set_status("paused", "no tool calls in the last turns")
91034
+ phase, summary = "paused", f"Goal paused: no tool calls in {goal['no_progress_streak']} turns in a row"
91035
+ elif turn >= (int(goal.get("max_turns", 0) or 0) or self._goal_default_max_turns()):
91036
+ self._goal_set_status("budget_limited", f"turn budget of {goal.get('max_turns')} reached")
91037
+ phase, summary = "budget_limited", f"Goal stopped: the turn budget of {goal.get('max_turns')} is used up"
91038
+ elif budget and tokens >= budget:
91039
+ self._goal_set_status("budget_limited", f"token budget of {budget} reached")
91040
+ phase, summary = "budget_limited", f"Goal stopped: {tokens} of {budget} tokens used"
91041
+ elif time_budget and seconds >= time_budget:
91042
+ self._goal_set_status("budget_limited", f"time budget of {time_budget} s reached")
91043
+ phase, summary = "budget_limited", f"Goal stopped: the time budget of {time_budget} s is used up"
91044
+ else:
91045
+ phase, summary = "continue", f"Goal not met yet; starting turn {turn + 1}"
91046
+ directive = {
91047
+ "goal_id": goal_id, "turn": turn + 1, "verdict": kind,
91048
+ "reason": str(verdict.get("reason", "")), "next_step": str(verdict.get("next_step", "")),
91049
+ }
91050
+ self._goal_emit(phase, summary, verdict=kind, reason=str(verdict.get("reason", "")),
91051
+ next_step=str(verdict.get("next_step", "")), turn=turn, tool_calls=tool_calls)
91052
+ return directive
91053
+
91054
+ def _goal_continuation_text(self, directive: dict) -> str:
91055
+ goal = self.goal_state or {}
91056
+ lines = [
91057
+ f"<{GOAL_CONTINUATION_TAG} turn=\"{int(directive.get('turn', 0) or 0)}\" max_turns=\"{int(goal.get('max_turns', 0) or 0)}\">",
91058
+ "The goal is not met yet. Continue working toward it in this turn; do not wait for the user.",
91059
+ f"Goal: {goal.get('objective', '')}",
91060
+ ]
91061
+ if str(directive.get("reason", "") or "").strip():
91062
+ lines.append(f"Evaluator: {directive.get('reason', '')}")
91063
+ if str(directive.get("next_step", "") or "").strip():
91064
+ lines.append(f"Next step: {directive.get('next_step', '')}")
91065
+ lines.append(
91066
+ "Re-check the current state before acting; earlier turns may have changed it. End the turn with visible "
91067
+ "evidence for each part of the condition you completed."
91068
+ )
91069
+ lines.append(f"</{GOAL_CONTINUATION_TAG}>")
91070
+ return "\n".join(lines)
91071
+
91072
+ def _goal_prepare_continuation_locked(self, directive: dict) -> bool:
91073
+ """Set up the next goal turn in place of a new user message. Caller holds self.lock.
91074
+
91075
+ The task's level, plan and Todo list carry over; a run that ended with
91076
+ finish_current_task is reopened so the next turn does not stop at once.
91077
+ """
91078
+ goal = self.goal_state or {}
91079
+ if goal.get("status") != "active" or goal.get("id") != directive.get("goal_id"):
91080
+ return False
91081
+ bb = self._ensure_blackboard()
91082
+ if self._blackboard_is_finished_or_aborted(bb):
91083
+ bb["approval"] = {"approved": False, "by": "", "note": "", "ts": 0.0}
91084
+ bb["completion"] = self._new_completion_state()
91085
+ bb["status"] = "CODING"
91086
+ bb["manager_summary_attempts"] = 0
91087
+ self._restore_runtime_policy_from_blackboard_locked()
91088
+ self.runtime_confirmation_needed = False
91089
+ self.runtime_reclassify_required = False
91090
+ self.runtime_reclassify_goal = ""
91091
+ self._mark_runtime_goal_reset_handled(reason="goal-continuation", clear_reclassify=True)
91092
+ self.run_generation = int(self.run_generation) + 1
91093
+ self._sync_llm_gate_generation()
91094
+ self.messages.append(
91095
+ self._runtime_control_message(
91096
+ self._goal_continuation_text(directive),
91097
+ control_tag=GOAL_CONTINUATION_TAG,
91098
+ ui_data={"goal_id": goal.get("id", ""), "turn": int(directive.get("turn", 0) or 0)},
91099
+ ui_visible=False,
91100
+ )
91101
+ )
91102
+ stamp = now_ts()
91103
+ self._goal_continuation_turn = True
91104
+ self._goal_turn_started_at = stamp
91105
+ self.running = True
91106
+ self.run_started_at = stamp
91107
+ self.run_last_heartbeat = stamp
91108
+ self.run_recovered_at = 0.0
91109
+ self.run_recovered_reason = ""
91110
+ self.current_phase = "starting"
91111
+ self.current_tool_name = ""
91112
+ self.updated_at = stamp
91113
+ return True
91114
+
91115
+ def goal_resume_run(self) -> bool:
91116
+ """Start the next goal turn on an idle session after /goal resume."""
91117
+ goal = self.goal_state or {}
91118
+ if goal.get("status") != "active":
91119
+ return False
91120
+ directive = {"goal_id": goal.get("id", ""), "turn": int(goal.get("turns", 0) or 0) + 1}
91121
+ last = (goal.get("verdicts") or [{}])[-1]
91122
+ directive.update(reason=str(last.get("reason", "") or ""), next_step=str(last.get("next_step", "") or ""))
91123
+ with self.lock:
91124
+ if bool(self.running):
91125
+ return False
91126
+ self._reset_runtime_state_locked(purge_runtime_hints=True)
91127
+ if not self._goal_prepare_continuation_locked(directive):
91128
+ return False
91129
+ self._persist()
91130
+ self._emit("status", {"summary": f"goal turn {directive['turn']} started"})
91131
+ threading.Thread(target=self._agent_worker, daemon=True).start()
91132
+ return True
91133
+
89964
91134
  def _reviewer_approval_log_gate(self, board: dict | None = None) -> tuple[bool, str]:
89965
91135
  bb = board if isinstance(board, dict) else self._ensure_blackboard()
89966
91136
  logs = bb.get("execution_logs", []) if isinstance(bb.get("execution_logs"), list) else []
@@ -94696,6 +95866,7 @@ body{padding:18px}
94696
95866
 
94697
95867
  def _agent_worker(self):
94698
95868
  single_role = "developer"
95869
+ goal_run_error: BaseException | None = None
94699
95870
  try:
94700
95871
  self.kernel_runtime_degraded = False
94701
95872
  kernel_runtime = getattr(self, "kernel_runtime", None)
@@ -95074,7 +96245,8 @@ body{padding:18px}
95074
96245
  "The prior response completed internal reasoning but emitted no TodoWrite action. "
95075
96246
  "Use the existing observations to decide whether preparation is complete. If material context is missing, "
95076
96247
  "choose the next read-only discovery or ask_user; otherwise submit your own TodoWrite with "
95077
- "the brief preparation assessment. Do not manufacture a checklist to satisfy a turn count."
96248
+ "the brief preparation assessment. Do not manufacture a checklist to satisfy a turn count. "
96249
+ + SINGLE_NO_PLAN_TODO_PREPARATION_INSTRUCTION
95078
96250
  )
95079
96251
  if bootstrap_thinking_signal:
95080
96252
  continuation += (
@@ -95114,6 +96286,11 @@ body{padding:18px}
95114
96286
  bootstrap_invalid_tool_call = False
95115
96287
  bootstrap_dropped_calls: list[str] = []
95116
96288
  if bootstrap_waiting_for_turn:
96289
+ if not tool_calls and text.strip():
96290
+ recovered_call = self._recover_inline_todo_tool_call(text)
96291
+ if recovered_call and "preparation" in recovered_call["function"]["arguments"]:
96292
+ tool_calls = [recovered_call]
96293
+ text = ""
95117
96294
  # Read-only calls are deliberately allowed during the
95118
96295
  # adaptive bootstrap so the model can gather missing
95119
96296
  # evidence. Only side-effect calls are dropped.
@@ -95122,7 +96299,7 @@ body{padding:18px}
95122
96299
  bootstrap_invalid_tool_call = not tool_calls
95123
96300
  self._emit(
95124
96301
  "status",
95125
- {"summary": "Todo bootstrap dropped side-effect calls: " + trim("; ".join(bootstrap_dropped_calls), 300)},
96302
+ {"summary": "Todo bootstrap withheld calls: " + trim("; ".join(bootstrap_dropped_calls), 300)},
95126
96303
  )
95127
96304
  if not tool_calls and not str(text or "").strip() and not str(thinking_text or "").strip():
95128
96305
  text = "Todo bootstrap turn produced no TodoWrite action."
@@ -95995,6 +97172,7 @@ body{padding:18px}
95995
97172
  interrupted_in_tools = False
95996
97173
  single_round_tool_results: list[dict] = []
95997
97174
  single_round_has_perception = False
97175
+ single_round_has_failed_perception = False
95998
97176
  single_round_has_mutation = False
95999
97177
  single_round_has_todo = False
96000
97178
  bootstrap_todo_success = False
@@ -96215,6 +97393,14 @@ body{padding:18px}
96215
97393
  )
96216
97394
  if self._single_no_plan_todo_is_perception_result(result_item):
96217
97395
  single_round_has_perception = True
97396
+ failed_bootstrap_probe = (
97397
+ bootstrap_waiting_for_turn
97398
+ and not skip_dispatch
97399
+ and not result_item["ok"]
97400
+ and self._single_no_plan_todo_is_perception_result(result_item, require_success=False)
97401
+ )
97402
+ if failed_bootstrap_probe:
97403
+ single_round_has_failed_perception = True
96218
97404
  if self._single_no_plan_todo_is_mutation_result(result_item):
96219
97405
  single_round_has_mutation = True
96220
97406
  self.single_no_plan_todo_bootstrap_write_seen = True
@@ -96280,16 +97466,19 @@ body{padding:18px}
96280
97466
  if is_control_feedback:
96281
97467
  self.todo_write_issue_count = 0
96282
97468
  self.todo_last_issue = ""
97469
+ outcome = str(result_item.get("control_outcome", "") or "")
97470
+ if outcome.startswith("task_preparation_") or outcome == "selected_skill_reading_required":
97471
+ todo_control_summary = f"Todo preparation requires follow-up ({outcome})"
97472
+ elif outcome == "todo_no_progress":
97473
+ todo_control_summary = "todo unchanged; continue current task execution"
97474
+ else:
97475
+ todo_control_summary = (
97476
+ "todo control gate preserved canonical current-step subtasks; "
97477
+ "continue the existing in_progress item"
97478
+ )
96283
97479
  self._emit(
96284
97480
  "status",
96285
- {
96286
- "summary": (
96287
- "todo unchanged; continue current task execution"
96288
- if result_item.get("control_outcome") == "todo_no_progress" else
96289
- "todo control gate preserved canonical current-step subtasks; "
96290
- "continue the existing in_progress item"
96291
- )
96292
- },
97481
+ {"summary": todo_control_summary},
96293
97482
  )
96294
97483
  elif state == "ok":
96295
97484
  used_todo = True
@@ -96347,6 +97536,8 @@ body{padding:18px}
96347
97536
  "result_ok": bool(result_item.get("ok", False)),
96348
97537
  "result_status": "ok" if result_item.get("ok", False) else "error",
96349
97538
  }
97539
+ if failed_bootstrap_probe:
97540
+ tool_message["content"] += "\n\n" + SINGLE_NO_PLAN_TODO_OBSERVATION_RETRY
96350
97541
  if result_item.get("exit_code") is not None:
96351
97542
  tool_message["exit_code"] = int(result_item.get("exit_code"))
96352
97543
  # Not yet seen by the model: protected from microcompact
@@ -96509,16 +97700,21 @@ body{padding:18px}
96509
97700
  "status",
96510
97701
  {"summary": "Todo bootstrap kept open: model reported preparation gaps; observation continues"},
96511
97702
  )
96512
- elif single_round_has_perception and not single_round_has_mutation:
96513
- # The adaptive bootstrap may legitimately contain one
96514
- # or more read-only calls before the writer call. Keep
96515
- # the gate active and let the model choose the next
96516
- # observation or emit TodoWrite on the following turn.
97703
+ elif not single_round_has_mutation and (
97704
+ single_round_has_perception
97705
+ or (single_round_has_failed_perception and not single_round_has_todo)
97706
+ ):
97707
+ # Even a denied or failed read is a preparation action.
97708
+ # The next turn can correct it without losing a writer attempt.
96517
97709
  consecutive_empty_action_rounds = 0
96518
97710
  bootstrap_thinking_signal = ""
96519
97711
  self._emit(
96520
97712
  "status",
96521
- {"summary": "Todo bootstrap perception continued; awaiting model TodoWrite action"},
97713
+ {"summary": (
97714
+ "Todo bootstrap perception continued; awaiting model TodoWrite action"
97715
+ if single_round_has_perception
97716
+ else "Todo bootstrap kept open: read-only probe failed; try a focused observation"
97717
+ )},
96522
97718
  )
96523
97719
  else:
96524
97720
  bootstrap_failure_state = self._single_no_plan_todo_bootstrap_failure(
@@ -97027,6 +98223,7 @@ body{padding:18px}
97027
98223
  self._blackboard_set_status("PAUSED", f"budget exhausted but finish blocked: {finish_result.get('reason', '')}")
97028
98224
  self._emit("status", {"summary": f"Budget exhausted ({self.max_agent_rounds} rounds). finish={finish_result.get('reason', '')}"})
97029
98225
  except CircuitBreakerTriggered as exc:
98226
+ goal_run_error = exc
97030
98227
  note = trim(str(exc), 320) or "Circuit breaker triggered."
97031
98228
  self._emit("status", {"summary": f"hard-stop: {note}"})
97032
98229
  self.messages.append({"role": "assistant", "content": note, "ts": now_ts(), "agent_role": single_role})
@@ -97040,11 +98237,13 @@ body{padding:18px}
97040
98237
  },
97041
98238
  )
97042
98239
  except OllamaError as exc:
98240
+ goal_run_error = exc
97043
98241
  if self.cancel_requested or int(getattr(exc, "status", 0) or 0) == 499:
97044
98242
  self._emit("status", {"summary": "run interrupted"})
97045
98243
  else:
97046
98244
  self._emit("error", {"summary": f"agent error: {exc}", "trace": traceback.format_exc()})
97047
98245
  except Exception as exc:
98246
+ goal_run_error = exc
97048
98247
  self._emit("error", {"summary": f"agent error: {exc}", "trace": traceback.format_exc()})
97049
98248
  finally:
97050
98249
  if self.todo.has_open_items() and not self.cancel_requested and not getattr(self, "_loop_stop_requested", {}):
@@ -97063,6 +98262,17 @@ body{padding:18px}
97063
98262
  self._generate_run_completion_summary()
97064
98263
  except Exception:
97065
98264
  pass
98265
+ # Goal mode: judge the condition before the run releases its slot,
98266
+ # so the next turn can start without a gap.
98267
+ goal_directive = None
98268
+ goal_turn_started = False
98269
+ try:
98270
+ loop_stop = getattr(self, "_loop_stop_requested", {})
98271
+ goal_directive = self._goal_after_run(
98272
+ goal_run_error or (RuntimeError("repeated-evidence loop was stopped") if loop_stop else None)
98273
+ )
98274
+ except Exception as exc:
98275
+ self._emit("status", {"summary": f"goal evaluation failed: {trim(str(exc), 200)}"})
97066
98276
  requeued_pending_inputs: list[dict] = []
97067
98277
  discarded_pending_inputs = 0
97068
98278
  removed_runtime_hints = 0
@@ -97083,8 +98293,15 @@ body{padding:18px}
97083
98293
  continue
97084
98294
  requeued_pending_inputs.append(row)
97085
98295
  removed_runtime_hints = self._reset_runtime_state_locked(purge_runtime_hints=True)
97086
- self.running = False
97087
- self.scheduler_starting = False
98296
+ if goal_directive and not requeued_pending_inputs:
98297
+ try:
98298
+ goal_turn_started = self._goal_prepare_continuation_locked(goal_directive)
98299
+ except Exception as exc:
98300
+ goal_turn_started = False
98301
+ self._emit("status", {"summary": f"goal turn could not start: {trim(str(exc), 200)}"})
98302
+ if not goal_turn_started:
98303
+ self.running = False
98304
+ self.scheduler_starting = False
97088
98305
  self.run_last_heartbeat = now_ts()
97089
98306
  self.updated_at = now_ts()
97090
98307
  self._persist()
@@ -97114,8 +98331,14 @@ body{padding:18px}
97114
98331
  self._emit("status", {"summary": _note})
97115
98332
  except Exception:
97116
98333
  pass
97117
- self._emit("status", {"summary": "run finished"})
97118
- cb = self.run_finished_callback
98334
+ if goal_turn_started:
98335
+ # The session keeps its run slot across goal turns; the
98336
+ # finish callback runs once, after the last turn.
98337
+ self._emit("status", {"summary": f"goal turn {int(goal_directive.get('turn', 0) or 0)} started"})
98338
+ threading.Thread(target=self._agent_worker, daemon=True).start()
98339
+ else:
98340
+ self._emit("status", {"summary": "run finished"})
98341
+ cb = None if goal_turn_started else self.run_finished_callback
97119
98342
  if cb:
97120
98343
  try:
97121
98344
  cb(str(self.owner_user_id or ""), self.id)
@@ -97362,6 +98585,15 @@ body{padding:18px}
97362
98585
  inferred_assistant_role = self._sanitize_agent_role(self.active_agent_role)
97363
98586
  inferred_bus_target_role = ""
97364
98587
  message_start = max(0, len(self.messages) - msg_window)
98588
+ # Compaction can replace a long user message with a file-buffer
98589
+ # pointer. The bubble log keeps the text under the same timestamp.
98590
+ bubble_text_by_ts: dict[int, str] = {}
98591
+ for entry in getattr(self, "user_bubble_log", None) or []:
98592
+ if isinstance(entry, dict) and str(entry.get("text", "") or "").strip():
98593
+ try:
98594
+ bubble_text_by_ts[int(round(float(entry.get("ts", 0.0) or 0.0) * 1000))] = str(entry["text"]).strip()
98595
+ except Exception:
98596
+ pass
97365
98597
  for msg_index, msg in enumerate(self.messages[message_start:], start=message_start):
97366
98598
  if self._is_ui_hidden_runtime_message(msg):
97367
98599
  continue
@@ -97393,6 +98625,29 @@ body{padding:18px}
97393
98625
  and all(str(name or "").strip().lower() in {"route_to_next_agent", "routetonext_agent"} for name in tool_names)
97394
98626
  )
97395
98627
  text = msg.get("content", "")
98628
+ # Only messages the user wrote count as user input. Runtime
98629
+ # guidance, loaded skills and compaction markers use the user
98630
+ # role on the wire but are not the user's words.
98631
+ is_user_input = bool(
98632
+ role_key == "user"
98633
+ and msg_type == "message"
98634
+ and runtime_projection is None
98635
+ and not (isinstance(msg, dict) and msg.get("_skill_notify"))
98636
+ and isinstance(text, str)
98637
+ )
98638
+ if is_user_input and text.lstrip().startswith(UI_COMPACT_RESUME_ARCHIVED_MARKER):
98639
+ continue
98640
+ if is_user_input and text.startswith("[file_buffer:"):
98641
+ try:
98642
+ ts_key = int(round(float(msg.get("ts", 0.0) or 0.0) * 1000))
98643
+ except Exception:
98644
+ ts_key = 0
98645
+ if ts_key in bubble_text_by_ts:
98646
+ text = bubble_text_by_ts[ts_key]
98647
+ else:
98648
+ summary = re.search(r"\ssummary=([\s\S]*)\]\s*$", text)
98649
+ if summary and self._is_runtime_internal_message({"role": "user", "content": summary.group(1)}):
98650
+ continue
97396
98651
  if (
97397
98652
  msg_type == "plan_notice"
97398
98653
  and not str(text or "").strip()
@@ -97472,6 +98727,8 @@ body{padding:18px}
97472
98727
  }
97473
98728
  if isinstance(msg, dict) and int(msg.get("seq", 0) or 0) > 0:
97474
98729
  row["seq"] = int(msg.get("seq", 0) or 0)
98730
+ if is_user_input:
98731
+ row["user_input"] = True
97475
98732
  if isinstance(msg, dict) and isinstance(msg.get("data"), dict):
97476
98733
  public_data = dict(msg.get("data") or {})
97477
98734
  if (
@@ -97551,6 +98808,7 @@ body{padding:18px}
97551
98808
  "ts": ts_f,
97552
98809
  "text": text,
97553
98810
  "retained": True,
98811
+ "user_input": True,
97554
98812
  }
97555
98813
  )
97556
98814
  def operation_feed_id(op: dict) -> str:
@@ -97684,6 +98942,34 @@ body{padding:18px}
97684
98942
  if agent_role:
97685
98943
  row["agent_role"] = agent_role
97686
98944
  conversation_feed.append(row)
98945
+ elif t == "slash_command":
98946
+ d = op.get("data", {}) if isinstance(op.get("data"), dict) else {}
98947
+ conversation_feed.append(
98948
+ {
98949
+ "id": operation_feed_id(op),
98950
+ "seq": int(op.get("seq", 0) or 0),
98951
+ "role": "system",
98952
+ "type": "slash_command",
98953
+ "ts": op.get("ts", 0),
98954
+ "text": str(d.get("summary", "") or ""),
98955
+ "data": dict(d),
98956
+ }
98957
+ )
98958
+ elif t == "goal":
98959
+ d = op.get("data", {}) if isinstance(op.get("data"), dict) else {}
98960
+ if str(d.get("phase", "") or "") == "evaluating":
98961
+ continue # transient; the goal bar shows it
98962
+ conversation_feed.append(
98963
+ {
98964
+ "id": operation_feed_id(op),
98965
+ "seq": int(op.get("seq", 0) or 0),
98966
+ "role": "system",
98967
+ "type": "goal",
98968
+ "ts": op.get("ts", 0),
98969
+ "text": str(d.get("summary", "") or "Goal"),
98970
+ "data": dict(d),
98971
+ }
98972
+ )
97687
98973
  elif t in {"tool_start", "tool_result"}:
97688
98974
  d = op.get("data", {})
97689
98975
  tool_name = str(d.get("name", "") or d.get("tool", "") or "").strip()
@@ -97912,6 +99198,8 @@ body{padding:18px}
97912
99198
  "blackboard": blackboard_view,
97913
99199
  "queued_user_inputs_count": len(self.pending_user_inputs),
97914
99200
  "pending_user_question": (dict(self.pending_user_question) if isinstance(self.pending_user_question, dict) else None),
99201
+ "goal": self.goal_public_state(),
99202
+ "goal_preferences": self.goal_public_preferences(),
97915
99203
  "scheduler_queued_inputs_count": sum(
97916
99204
  1 for row in self.scheduler_visible_inputs
97917
99205
  if isinstance(row, dict) and str(row.get("scheduler_status", "queued") or "queued") == "queued"
@@ -97990,7 +99278,11 @@ body{padding:18px}
97990
99278
  "session_files_root": str(self.files_root),
97991
99279
  "llm_model_catalog": model_catalog,
97992
99280
  "messages": visible_messages,
97993
- "conversation_feed": conversation_feed[-conversation_window:],
99281
+ "conversation_feed": _bounded_ui_feed_window(
99282
+ conversation_feed,
99283
+ conversation_window,
99284
+ UI_PINNED_USER_ROWS_LITE if lite else UI_PINNED_USER_ROWS_FULL,
99285
+ ),
97994
99286
  "uploads": upload_view,
97995
99287
  "todos": todo_view,
97996
99288
  "tasks": task_view,
@@ -98050,6 +99342,7 @@ body{padding:18px}
98050
99342
  cached["recovered_reason"] = str(getattr(self, "run_recovered_reason", cached.get("recovered_reason", "")) or "")
98051
99343
  cached["degraded"] = True
98052
99344
  cached["degraded_reason"] = trim(reason, 220)
99345
+ cached["goal"] = self.goal_public_state()
98053
99346
  if uploads_view and not cached.get("uploads"):
98054
99347
  cached["uploads"] = uploads_view
98055
99348
  # The gate has its own lock, so the live value is readable even
@@ -98579,6 +99872,7 @@ class SessionManager:
98579
99872
  self.single_no_plan_todo_enabled = bool(cfg_single_todo_enabled)
98580
99873
  self.single_no_plan_todo_prompt = str(cfg_single_todo_prompt or "").strip()
98581
99874
  self.read_context_policy = DEFAULT_READ_CONTEXT_POLICY
99875
+ self.goal_default_turns = GOAL_DEFAULT_MAX_TURNS
98582
99876
  self.tool_memory_policy = DEFAULT_TOOL_MEMORY_POLICY
98583
99877
  self.upload_callback = upload_callback
98584
99878
  self.reference_prepare_callback = reference_prepare_callback
@@ -99018,6 +100312,7 @@ class SessionManager:
99018
100312
  sess.auto_task_level_ceiling = normalize_auto_task_level_ceiling(
99019
100313
  getattr(self, "auto_task_level_ceiling", DEFAULT_AUTO_TASK_LEVEL_CEILING)
99020
100314
  )
100315
+ sess.goal_default_turns = int(getattr(self, "goal_default_turns", GOAL_DEFAULT_MAX_TURNS) or GOAL_DEFAULT_MAX_TURNS)
99021
100316
  set_session_llm_concurrency_on_runtime(
99022
100317
  sess,
99023
100318
  getattr(self, "session_llm_concurrency", DEFAULT_SESSION_LLM_CONCURRENCY),
@@ -100292,7 +101587,9 @@ class SessionManager:
100292
101587
 
100293
101588
  def _probe_user_active_capabilities(self, force_probe: bool = False):
100294
101589
  profile = self._active_profile()
100295
- if not profile or not self._user_profile_is_runnable(profile):
101590
+ if not profile or not self._user_profile_is_runnable(profile) or (
101591
+ FAST_START_DEFER_CAPABILITY_PROBE and not force_probe
101592
+ ):
100296
101593
  return
100297
101594
  client = OllamaClient(
100298
101595
  str(profile.get("base_url", self.ollama_base) or self.ollama_base),
@@ -100308,18 +101605,17 @@ class SessionManager:
100308
101605
  )
100309
101606
  client.apply_profile(profile)
100310
101607
  client.set_telemetry(self.telemetry_callback, context_provider=lambda: {}, name="capability_probe")
100311
- caps = client.probe_multimodal_capabilities(force=True if force_probe else False)
101608
+ caps = client.probe_multimodal_capabilities(force=force_probe)
101609
+ probe_entry = client.probe_cache_entry()
101610
+ observed = probe_entry.get("observed_capabilities", caps)
101611
+ model = str(profile.get("model", "") or "")
100312
101612
  merged = merge_multimodal_capabilities(
100313
- merge_multimodal_capabilities(
100314
- infer_model_multimodal_capabilities(str(profile.get("provider", "")), str(profile.get("model", ""))),
100315
- parse_capability_overrides(profile.get("capabilities", {})),
100316
- ),
100317
- caps,
101613
+ infer_model_multimodal_capabilities(str(profile.get("provider", "")), model),
101614
+ {**observed, **resolve_configured_media_capabilities(profile, model)},
100318
101615
  )
100319
101616
  profile["capabilities"] = merged
100320
101617
  self.user_model_profiles[self.user_active_profile_id] = profile
100321
101618
  self._persist_user_prefs()
100322
- probe_entry = client.probe_cache_entry()
100323
101619
  probe_details = probe_entry.get("details", {}) if isinstance(probe_entry, dict) else {}
100324
101620
  probe_updated_at = float(
100325
101621
  (probe_entry.get("updated_at", now_ts()) if isinstance(probe_entry, dict) else now_ts()) or now_ts()
@@ -100328,16 +101624,18 @@ class SessionManager:
100328
101624
  if self.user_active_profile_id not in sess.model_profiles:
100329
101625
  continue
100330
101626
  row = dict(sess.model_profiles[self.user_active_profile_id])
100331
- row["capabilities"] = merged
100332
- sess.model_profiles[self.user_active_profile_id] = row
100333
101627
  cache_key = sess._profile_cache_key(row)
101628
+ if cache_key != sess._profile_cache_key(profile):
101629
+ continue
100334
101630
  sess.multimodal_capability_cache[cache_key] = {
100335
- "capabilities": merged,
101631
+ "capabilities": observed,
100336
101632
  "details": probe_details if isinstance(probe_details, dict) else {},
100337
101633
  "updated_at": probe_updated_at,
100338
101634
  "provider": str(row.get("provider", "")),
100339
101635
  "model": str(row.get("model", "")),
100340
101636
  }
101637
+ row["capabilities"] = sess._capabilities_from_profile(row)
101638
+ sess.model_profiles[self.user_active_profile_id] = row
100341
101639
  if sess.active_profile_id == self.user_active_profile_id:
100342
101640
  sess.ollama.apply_profile(row)
100343
101641
  sess.updated_at = now_ts()
@@ -101086,6 +102384,115 @@ class SessionManager:
101086
102384
  "catalog_revision": catalog_revision,
101087
102385
  }
101088
102386
 
102387
+
102388
+ # One mark per service: a rounded tile with a two-stop gradient and a white
102389
+ # glyph drawn on a 32 x 32 grid. The web agent keeps its existing mark.
102390
+ SERVICE_LOGOS: dict[str, dict[str, str]] = {
102391
+ "web-agent": {
102392
+ "title": "Clouds Coder",
102393
+ "colors": "#3b82f6,#14b8a6",
102394
+ "glyph": "<path d='M12.5 11.5 8 16l4.5 4.5M19.5 11.5 24 16l-4.5 4.5M17.4 9.8l-2.8 12.4'/>",
102395
+ },
102396
+ "admin": {
102397
+ "title": "Clouds Coder Admin",
102398
+ "colors": "#64748b,#1e293b",
102399
+ "glyph": "<path d='M16 7.2l7 2.7v5.3c0 4.4-2.9 7.8-7 9.4-4.1-1.6-7-5-7-9.4V9.9z'/><path d='M12.6 16.1l2.4 2.4 4.5-4.7'/>",
102400
+ },
102401
+ "skills-studio": {
102402
+ "title": "Skills Studio",
102403
+ "colors": "#f59e0b,#ea580c",
102404
+ "glyph": (
102405
+ "<path d='M8.5 23.5l10-10'/>"
102406
+ "<path d='M21.2 6.8l1.1 2.7 2.7 1.1-2.7 1.1-1.1 2.7-1.1-2.7-2.7-1.1 2.7-1.1z' fill='#fff'/>"
102407
+ "<path d='M12.5 8v3.4M10.8 9.7h3.4M23 18.5v3M21.5 20h3'/>"
102408
+ ),
102409
+ },
102410
+ "rag-admin": {
102411
+ "title": "RAG Admin",
102412
+ "colors": "#10b981,#0f766e",
102413
+ "glyph": (
102414
+ "<ellipse cx='14' cy='10.2' rx='6' ry='2.5'/>"
102415
+ "<path d='M8 10.2v9.6c0 1.4 2.7 2.5 6 2.5M20 10.2v3.6M8 15c0 1.4 2.7 2.5 6 2.5'/>"
102416
+ "<circle cx='21' cy='20' r='3.1'/><path d='M23.3 22.3l2.3 2.3'/>"
102417
+ ),
102418
+ },
102419
+ "code-admin": {
102420
+ "title": "Code Library Admin",
102421
+ "colors": "#8b5cf6,#6d28d9",
102422
+ "glyph": (
102423
+ "<path d='M12.6 8.5c-1.9 0-2.7.8-2.7 2.5v2.3c0 1.3-.7 2.1-2 2.2 1.3.1 2 .9 2 2.2V20c0 1.7.8 2.5 2.7 2.5'/>"
102424
+ "<path d='M19.4 8.5c1.9 0 2.7.8 2.7 2.5v2.3c0 1.3.7 2.1 2 2.2-1.3.1-2 .9-2 2.2V20c0 1.7-.8 2.5-2.7 2.5'/>"
102425
+ "<path d='M14.6 17.4l2.8-3.2' stroke-width='1.8'/>"
102426
+ "<circle cx='14' cy='18.2' r='1.7' fill='#fff' stroke='none'/>"
102427
+ "<circle cx='18' cy='13.4' r='1.7' fill='#fff' stroke='none'/>"
102428
+ ),
102429
+ },
102430
+ "mcp-service": {
102431
+ "title": "MCP Service",
102432
+ "colors": "#f43f5e,#be123c",
102433
+ "glyph": "<path d='M13 7.5V12M19 7.5V12M10.5 12h11v3.6a5.5 5.5 0 0 1-11 0z'/><path d='M16 21.1v3.6'/>",
102434
+ },
102435
+ "ide": {
102436
+ "title": "Clouds Coder IDE",
102437
+ "colors": "#0ea5e9,#1d4ed8",
102438
+ "glyph": "<rect x='6.8' y='8' width='18.4' height='16' rx='2.6'/><path d='M6.8 12.2h18.4M11 16l2.6 2.2L11 20.4M16.4 20.4h4.6'/>",
102439
+ },
102440
+ "collaboration": {
102441
+ "title": "Clouds Coder Collaboration",
102442
+ "colors": "#22c55e,#15803d",
102443
+ "glyph": (
102444
+ "<circle cx='12.6' cy='12.4' r='2.9'/><circle cx='20.4' cy='13.4' r='2.4'/>"
102445
+ "<path d='M7.2 23c.6-3.2 2.7-5 5.4-5s4.8 1.8 5.4 5M18.8 18.3c2.6-.3 4.9 1.3 5.6 4.7'/>"
102446
+ ),
102447
+ },
102448
+ }
102449
+
102450
+
102451
+ def service_logo_svg(service: str, size: int = 32, uid: str = "mark") -> str:
102452
+ """Inline SVG mark for one service; uid keeps gradient ids unique per page."""
102453
+ logo = SERVICE_LOGOS.get(service) or SERVICE_LOGOS["web-agent"]
102454
+ start, end = logo["colors"].split(",")
102455
+ grad = f"cc-logo-{service}-{uid}"
102456
+ return (
102457
+ f"<svg class='cc-service-logo' data-service='{service}' data-uid='{uid}' viewBox='0 0 32 32'"
102458
+ f" width='{int(size)}' height='{int(size)}' role='img'"
102459
+ f" aria-label='{logo['title']}' xmlns='http://www.w3.org/2000/svg'>"
102460
+ f"<defs><linearGradient id='{grad}' x1='0' y1='0' x2='1' y2='1'>"
102461
+ f"<stop offset='0' stop-color='{start}'/><stop offset='1' stop-color='{end}'/></linearGradient></defs>"
102462
+ f"<rect width='32' height='32' rx='9' fill='url(#{grad})'/>"
102463
+ "<g fill='none' stroke='#fff' stroke-width='2.2' stroke-linecap='round' stroke-linejoin='round'>"
102464
+ f"{logo['glyph']}</g></svg>"
102465
+ )
102466
+
102467
+
102468
+ def service_favicon_link(service: str) -> str:
102469
+ """<link rel=icon> with the service mark as an inline SVG data URI."""
102470
+ svg = service_logo_svg(service, 32, "favicon").replace("#", "%23")
102471
+ return f'<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,{svg}">'
102472
+
102473
+
102474
+ _SERVICE_LOGO_MARKER_RE = re.compile(r"<!--cc-(favicon|logo):([a-z-]+)(?::([a-z0-9-]+):([0-9]+))?-->")
102475
+ _SERVICE_LOGO_SVG_RE = re.compile(r"<svg class='cc-service-logo' data-service='[a-z-]+' data-uid='([a-z0-9-]+)' viewBox='0 0 32 32' width='([0-9]+)'.*?</svg>", re.S)
102476
+ _SERVICE_FAVICON_RE = re.compile(r'<link rel="icon" type="image/svg\+xml" href="data:image/svg\+xml,[^"]*">')
102477
+
102478
+
102479
+ def embed_service_logos(html: str) -> str:
102480
+ """Replace <!--cc-favicon:SERVICE--> and <!--cc-logo:SERVICE:UID:SIZE--> markers."""
102481
+ def render(match: re.Match) -> str:
102482
+ kind, service, uid, size = match.groups()
102483
+ if kind == "favicon":
102484
+ return service_favicon_link(service)
102485
+ return service_logo_svg(service, int(size or 32), uid or "mark")
102486
+
102487
+ return _SERVICE_LOGO_MARKER_RE.sub(render, str(html or ""))
102488
+
102489
+
102490
+ def rebrand_service_logos(html: str, service: str) -> str:
102491
+ """Draw every embedded mark and the favicon of a page as another service."""
102492
+ text = _SERVICE_LOGO_SVG_RE.sub(lambda m: service_logo_svg(service, int(m.group(2)), m.group(1)), str(html or ""))
102493
+ return _SERVICE_FAVICON_RE.sub(lambda _m: service_favicon_link(service), text)
102494
+
102495
+
101089
102496
  INDEX_HTML = r"""<!doctype html>
101090
102497
  <html lang="zh-CN" data-cc-shell="agent-v2">
101091
102498
  <head>
@@ -101095,6 +102502,7 @@ INDEX_HTML = r"""<!doctype html>
101095
102502
  <meta name="clouds-coder-webui-shell" content="agent-v2">
101096
102503
  <meta name="color-scheme" content="light dark">
101097
102504
  <title>Clouds Coder</title>
102505
+ <!--cc-favicon:web-agent-->
101098
102506
  <script>
101099
102507
  (function(){try{var t=localStorage.getItem('cc_ui_theme')||'system';var d=t==='dark'||(t==='system'&&window.matchMedia&&matchMedia('(prefers-color-scheme: dark)').matches);document.documentElement.setAttribute('data-theme',d?'dark':'light');document.documentElement.setAttribute('data-theme-pref',t);if(localStorage.getItem('cc_ui_sidebar')==='0')document.documentElement.classList.add('cc-sidebar-collapsed');if(localStorage.getItem('cc_ui_inspector')==='0')document.documentElement.classList.add('cc-inspector-collapsed');}catch(_){}})();
101100
102508
  </script>
@@ -101116,7 +102524,7 @@ window.MathJax={
101116
102524
  <aside id="sidebar" class="sidebar" aria-label="Sessions">
101117
102525
  <div class="sidebar-head">
101118
102526
  <a class="brand" href="/" aria-label="Clouds Coder">
101119
- <span class="brand-mark" aria-hidden="true"><svg viewBox="0 0 32 32" width="28" height="28"><defs><linearGradient id="ccBrandGrad" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#3b82f6"/><stop offset="1" stop-color="#14b8a6"/></linearGradient></defs><rect width="32" height="32" rx="9" fill="url(#ccBrandGrad)"/><path d="M12.5 11.5 8 16l4.5 4.5M19.5 11.5 24 16l-4.5 4.5M17.4 9.8l-2.8 12.4" fill="none" stroke="#fff" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/></svg></span>
102527
+ <span class="brand-mark" aria-hidden="true"><!--cc-logo:web-agent:brand:28--></span>
101120
102528
  <span class="brand-text"><strong data-i18n="app_title">Clouds Coder</strong><small data-i18n="ui_brand_tagline">Coding agent workspace</small></span>
101121
102529
  </a>
101122
102530
  <button id="sidebarCollapseBtn" class="icon-btn ic ic-panel-left" type="button" data-i18n-title="ui_toggle_sidebar" data-i18n-aria="ui_toggle_sidebar" title="Toggle sidebar" aria-label="Toggle sidebar"></button>
@@ -101208,6 +102616,7 @@ window.MathJax={
101208
102616
  </div>
101209
102617
  <div class="composer">
101210
102618
  <div id="askUserCard" class="ask-user-card" style="display:none"></div>
102619
+ <div id="goalBar" class="goal-bar" hidden></div>
101211
102620
  <div id="promptComposerShell" class="composer-shell">
101212
102621
  <div id="ccAttachTray" class="cc-attach-tray" hidden data-i18n-title="ui_attach_hint" title="Attached files upload when you press Send"></div>
101213
102622
  <div class="prompt-wrapper">
@@ -101239,6 +102648,10 @@ window.MathJax={
101239
102648
  </div>
101240
102649
  </div>
101241
102650
  <button id="planModeBtn" class="subtle chip-btn ic ic-plan" type="button" title="Toggle Plan Mode" data-i18n-title="ui_plan_toggle">Plan: Auto</button>
102651
+ <div id="goalDropdown" class="popup-dropdown goal-dropdown" hidden>
102652
+ <button id="goalMenuBtn" class="subtle chip-btn caret ic ic-goal" type="button" aria-haspopup="true">Goal</button>
102653
+ <div id="goalMenu" class="popup-menu popup-menu-wide goal-menu" style="display:none"></div>
102654
+ </div>
101242
102655
  </div>
101243
102656
  <div class="composer-send">
101244
102657
  <div id="ctxLive" class="ctx-live" title="Remaining context budget">
@@ -101461,6 +102874,7 @@ window.MathJax={
101461
102874
  </body>
101462
102875
  </html>
101463
102876
  """
102877
+ INDEX_HTML = embed_service_logos(INDEX_HTML)
101464
102878
 
101465
102879
  APP_CSS = r""".ic::before{content:"";display:inline-block;flex:0 0 auto;width:var(--ic-size,16px);height:var(--ic-size,16px);background-color:currentColor;-webkit-mask:var(--ic) center/contain no-repeat;mask:var(--ic) center/contain no-repeat;vertical-align:-3px}
101466
102880
  .ic-plus{--ic:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='1.9' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M12 5v14M5 12h14'/%3E%3C/svg%3E")}
@@ -103071,7 +104485,7 @@ function _deltaEnsureSnapshot(){if(!S.snap||typeof S.snap!=='object')return fals
103071
104485
  function _deltaPushLimited(arr,row,maxCount){if(!Array.isArray(arr))return;if(!row||typeof row!=='object')return;arr.push(row);const maxN=Math.max(20,Number(maxCount)||120);if(arr.length>maxN){arr.splice(0,arr.length-maxN)}}
103072
104486
  function _deltaAdoptAgentRole(data){if(!_deltaEnsureSnapshot())return'';const role=_chatVirtAgentRoleKey(data?.agent_role);if(!role)return'';S.snap.agent_active_role=role;return role}
103073
104487
  function _deltaAppendActivity(type,data,ts){if(!_deltaEnsureSnapshot())return;const d=(data&&typeof data==='object')?data:{};const summary=String(d.summary||d.text||d.name||type||'').trim();if(!summary)return;_deltaPushLimited(S.snap.activity,{ts:Number(ts||Date.now()/1000),type:String(type||''),summary:summary},DELTA_MAX_ACTIVITY)}
103074
- function _deltaAppendConversationRow(row){if(!_deltaEnsureSnapshot())return;_deltaPushLimited(S.snap.conversation_feed,row,DELTA_MAX_FEED)}
104488
+ function _deltaAppendConversationRow(row){if(!_deltaEnsureSnapshot()||!row||typeof row!=='object')return;const feed=S.snap.conversation_feed;feed.push(row);let extra=feed.length-Math.max(20,Number(DELTA_MAX_FEED)||120);/* Trim the oldest rows first and the user's own messages last. */for(let i=0;i<feed.length&&extra>0;){if(feed[i]&&feed[i].user_input){i+=1;continue}feed.splice(i,1);extra-=1}if(extra>0)feed.splice(0,extra)}
103075
104489
  function _deltaRemoveSchedulerQueued(queueId=0,text=''){
103076
104490
  if(!_deltaEnsureSnapshot())return 0;
103077
104491
  const qid=Number(queueId||0);
@@ -103322,6 +104736,7 @@ function _deltaApplyRuntimeEvent(evt){
103322
104736
  text=String(data.data.body||'');
103323
104737
  }
103324
104738
  const msgRow={role:role,text:text,ts:ts,type:rowType};
104739
+ if(role==='user'&&data.user_input)msgRow.user_input=true;
103325
104740
  if(data&&typeof data==='object'&&data.data&&typeof data.data==='object')msgRow.data={...data.data};
103326
104741
  if(rowType==='scheduler_queued'){
103327
104742
  msgRow.scheduler_status=schedulerStatus||'queued';
@@ -105586,6 +107001,8 @@ function _chatVirtBuildMessageNode(m){
105586
107001
  else if(m.type==='upload'&&m.data)kind='upload';
105587
107002
  else if(m.type==='command'&&m.data)kind='command';
105588
107003
  else if(m.type==='web_search'&&m.data)kind='web_search';
107004
+ else if(m.type==='goal'&&m.data)kind='goal';
107005
+ else if(m.type==='slash_command'&&m.data)kind='slash_command';
105589
107006
  else if(parsedWebSearchText)kind='web_search';
105590
107007
  else if(m.type==='live_thinking')kind='live_thinking';
105591
107008
  else if(m.type==='live_response')kind='live_response';
@@ -105815,6 +107232,16 @@ function _chatVirtBuildMessageNode(m){
105815
107232
  d.innerHTML=_chatVirtToolPlanHtml(tools,rolePill);
105816
107233
  return d;
105817
107234
  }
107235
+ if(kind==='slash_command'){
107236
+ d.innerHTML=_slashCommandCardHtml(m.data);
107237
+ d.setAttribute('data-math-request',`${String(m._vk||'')}:slash`);
107238
+ return d;
107239
+ }
107240
+ if(kind==='goal'){
107241
+ d.innerHTML=_goalCardHtml(m.data);
107242
+ d.setAttribute('data-math-request',`${String(m._vk||'')}:goal`);
107243
+ return d;
107244
+ }
105818
107245
  if(kind==='web_search'){
105819
107246
  const info=(m&&typeof m.data==='object'&&Object.keys(m.data||{}).length)?m.data:(parsedWebSearchText||{});
105820
107247
  const phase=String(info.phase||'').trim();
@@ -106724,7 +108151,7 @@ function _opsTailSignature(rows,count,mapper){const arr=Array.isArray(rows)?rows
106724
108151
  function fmtCompactAge(ts){const n=Number(ts||0);if(!n)return '';const secs=Math.max(0,Math.floor(Date.now()/1000-n));if(secs<2)return t('compact_just_now');if(secs<60)return secs+'s '+t('compact_ago');const mins=Math.floor(secs/60);if(mins<60)return mins+'m '+t('compact_ago');const hrs=Math.floor(mins/60);if(hrs<24)return hrs+'h '+t('compact_ago');return Math.floor(hrs/24)+'d '+t('compact_ago');}
106725
108152
  function fmtLastCompact(snap){const reason=snap?.last_compact_reason||'';if(!reason)return '-';const age=fmtCompactAge(snap?.last_compact_ts);return age?(reason+' · '+age):reason;}
106726
108153
  function answerAskUser(text){const val=String(text||'').trim();if(!val||!S.activeId)return;const promptEl=E('prompt');if(promptEl){promptEl.value=val;}sendMessage();}
106727
- function renderAskUserCard(){const card=E('askUserCard');if(!card)return;const pq=S.snap?.pending_user_question;const show=!S.snap?.running&&pq&&String(pq.question||'').trim();if(!show){if(card.style.display!=='none'){card.style.display='none';card.innerHTML='';}return;}const q=String(pq.question||'').trim();const opts=Array.isArray(pq.options)?pq.options.filter(o=>String(o||'').trim()):[];const allowFree=pq.allow_free_text!==false;const role=String(pq.role||'agent');const roleLabel=role&&role!=='agent'?_chatVirtAgentRoleLabel(role):'';let btns='';if(opts.length){btns='<div class="ask-user-options">'+opts.map((o,i)=>`<button type="button" class="ask-user-opt" data-ask-idx="${i}">${esc(String(o))}</button>`).join('')+'</div>';}const hint=allowFree?esc(t('ask_user_free_hint')):esc(t('ask_user_pick_hint'));const html=`<div class="ask-user-head"><span class="ask-user-badge">${esc(t('ask_user_title'))}</span>${roleLabel?`<span class="ask-user-role">${esc(roleLabel)}</span>`:''}</div><div class="ask-user-q">${esc(q)}</div>${btns}<div class="ask-user-hint">${hint}</div>`;if(card.innerHTML!==html){card.innerHTML=html;card.querySelectorAll('.ask-user-opt').forEach(b=>{b.addEventListener('click',()=>{const idx=parseInt(b.getAttribute('data-ask-idx')||'-1',10);if(idx>=0&&idx<opts.length)answerAskUser(opts[idx]);});});}card.style.display='';}
108154
+ function renderAskUserCard(){const card=E('askUserCard');if(!card)return;const pq=S.snap?.pending_user_question;const show=!S.snap?.running&&pq&&String(pq.question||'').trim();if(!show){if(card.style.display!=='none'){card.style.display='none';card.innerHTML='';}return;}const q=String(pq.question||'').trim();const _ov=o=>(o&&typeof o==='object')?String(o.value||o.label||''):String(o||'');const _ol=o=>(o&&typeof o==='object')?String(o.label||o.value||''):String(o||'');const opts=Array.isArray(pq.options)?pq.options.filter(o=>_ov(o).trim()):[];const allowFree=pq.allow_free_text!==false;const role=String(pq.role||'agent');const roleLabel=role&&role!=='agent'?_chatVirtAgentRoleLabel(role):'';let btns='';if(opts.length){btns='<div class="ask-user-options">'+opts.map((o,i)=>`<button type="button" class="ask-user-opt" data-ask-idx="${i}"${o&&typeof o==='object'&&o.description?` title="${esc(String(o.description))}"`:''}>${esc(_ol(o))}</button>`).join('')+'</div>';}const hint=allowFree?esc(t('ask_user_free_hint')):esc(t('ask_user_pick_hint'));const html=`<div class="ask-user-head"><span class="ask-user-badge">${esc(t('ask_user_title'))}</span>${roleLabel?`<span class="ask-user-role">${esc(roleLabel)}</span>`:''}</div><div class="ask-user-q">${esc(q)}</div>${btns}<div class="ask-user-hint">${hint}</div>`;if(card.innerHTML!==html){card.innerHTML=html;card.querySelectorAll('.ask-user-opt').forEach(b=>{b.addEventListener('click',()=>{const idx=parseInt(b.getAttribute('data-ask-idx')||'-1',10);if(idx>=0&&idx<opts.length)answerAskUser(_ov(opts[idx]));});});}card.style.display='';}
106728
108155
  function modelTokenBudgetText(task=false){const row=S.snap?.model_token_budget||{},used=Number(task?row.task_used:row.used)||0,limit=Number(task?row.task_limit:row.run_limit)||0;return `${used.toLocaleString()} / ${limit>0?limit.toLocaleString():'∞'}`}
106729
108156
  function renderRuntimeStatus(){const uiState=S.staticMode?(S.frozen?'static':'live'):'live';const boolWord=v=>t(v?'state_on':'state_off');const activeRole=String(S.snap?.agent_active_role||'').trim();const activeRoleLabel=activeRole?_chatVirtAgentRoleLabel(activeRole):'-';const _awaitingUser=!S.snap?.running&&S.snap?.pending_user_question&&String(S.snap?.pending_user_question?.question||'').trim();const _submission=_reconcileSubmissionState(S.activeId,S.snap);const _stateVal=S.snap?.running?t('running'):(S.snap?.scheduler_starting?t('starting'):(_submission?_submissionStatusLabel(_submission):(_awaitingUser?t('rt_awaiting_user'):t('idle'))));const _stateTone=_awaitingUser&&!_submission?'state-awaiting':((S.snap?.running||S.snap?.scheduler_starting||_submission)?'state-running':'state-idle');const runtimeItems=[{label:t('rt_session'),value:S.snap?.id||'-',mono:true},{label:t('rt_model'),value:S.snap?.model||'-',mono:true},{label:t('rt_thinking'),value:boolWord(S.snap?.thinking)},{label:t('rt_thinking_stream'),value:boolWord(S.snap?.thinking_stream)},{label:t('rt_response_stream'),value:boolWord(S.snap?.response_stream)},{label:t('rt_mode'),value:S.snap?.execution_mode||S.config?.execution_mode||'sync'},{label:t('rt_active_agent'),value:activeRoleLabel},{label:t('rt_blackboard'),value:S.snap?.blackboard?.status||'-'},{label:t('rt_task'),value:S.snap?.blackboard?.task_profile?.task_type||'-'},{label:t('rt_complexity'),value:S.snap?.blackboard?.task_profile?.complexity||'-'},{label:t('rt_judgement'),value:S.snap?.blackboard?.manager_judgement?.progress||'-'},{label:t('rt_budget'),value:S.snap?.blackboard?.task_profile?.round_budget??'-'},{label:t('rt_remaining'),value:S.snap?.blackboard?.manager_judgement?.remaining_rounds??'-'},{label:t('rt_blackboard_cycles'),value:S.snap?.blackboard?.manager_cycles??'-'},{label:t('rt_round_limit'),value:S.snap?.max_agent_rounds||'-'},{label:t('rt_round'),value:S.snap?.agent_round_index??'-'},{label:t('rt_phase'),value:S.snap?.agent_phase||t('idle')},{label:t('rt_queued_inputs'),value:S.snap?.queued_user_inputs_count??0},{label:t('rt_run_timeout'),value:`${S.snap?.max_run_seconds??'-'}s`},{label:t('rt_ctx_used'),value:S.snap?.context_tokens_estimate??'-'},{label:t('rt_ctx_limit'),value:S.snap?.context_effective_token_limit||S.snap?.context_token_upper_bound||'-'},{label:t('rt_ctx_mode'),value:t(S.snap?.context_token_limit_locked?'rt_manual_lock':'rt_adaptive')},{label:t('rt_ctx_left'),value:formatContextLeft(S.snap)},{label:t('rt_truncation'),value:S.snap?.truncation_count||0},{label:t('rt_trunc_retry'),value:S.snap?.live_truncation_attempts||0},{label:t('rt_trunc_tokens'),value:S.snap?.live_truncation_tokens||0},{label:t('rt_archive'),value:S.snap?.compact_segments_count||0},{label:'完整归档记录',value:S.snap?.full_history_records||0},{label:'累计 Token / 总配额',value:modelTokenBudgetText()},{label:'步骤 Token / 配额',value:modelTokenBudgetText(true)},{label:'输入缓存命中',value:S.snap?.model_token_budget?.cache?.reported_calls?`${(100*Number(S.snap.model_token_budget.cache.hit_ratio||0)).toFixed(1)}%`:'未知'},{label:t('rt_last_compact'),value:fmtLastCompact(S.snap)},{label:t('rt_ollama'),value:S.snap?.ollama_base_url||'-',mono:true,wide:true},{label:t('rt_files'),value:S.snap?.session_files_root||'-',mono:true,wide:true},{label:t('rt_ui_mode'),value:uiState},{label:t('rt_state'),value:_stateVal,tone:_stateTone}];setHtmlIfChanged('status',runtimeItems.map(item=>_runtimePillHtml(item.label,item.value,item)).join('')+agentContextChipsHtml(S.snap),'runtimeStatus')}
106730
108157
  function renderPlanLevelControls(){const _pmBtn=E('planModeBtn');if(_pmBtn){const _pm=S.snap?.plan_mode_preference||'auto';setTextIfChanged(_pmBtn,ccPlanModeLabel(_pm))}updateLevelBtn(S.snap?.user_task_level||0)}
@@ -106753,7 +108180,7 @@ function renderUserProcesses(){const host=E('userProcesses');if(!host)return;con
106753
108180
  async function refreshUserProcesses(force=false){if(USER_PROCESS_STATE.inFlight)return;if(!force&&Date.now()-Number(USER_PROCESS_STATE.lastLoadedAt||0)<1800)return;USER_PROCESS_STATE.inFlight=true;try{const out=await api('/api/processes?limit=100');USER_PROCESS_STATE.rows=Array.isArray(out.processes)?out.processes:[];USER_PROCESS_STATE.counts=out.counts||{};USER_PROCESS_STATE.lastLoadedAt=Date.now();if(USER_PROCESS_STATE.detailId&&!USER_PROCESS_STATE.rows.some(row=>String(row.id||'')===USER_PROCESS_STATE.detailId)){USER_PROCESS_STATE.detailId='';USER_PROCESS_STATE.detail=null}renderUserProcesses()}finally{USER_PROCESS_STATE.inFlight=false}}
106754
108181
  async function loadUserProcessDetail(id){const key=String(id||'');if(!key)return;if(USER_PROCESS_STATE.detailId===key){USER_PROCESS_STATE.detailId='';USER_PROCESS_STATE.detail=null;renderUserProcesses();return}const out=await api('/api/processes/'+encodeURIComponent(key));USER_PROCESS_STATE.detailId=key;USER_PROCESS_STATE.detail=out.process||null;renderUserProcesses()}
106755
108182
  async function stopUserProcess(id){const key=String(id||'');if(!key||!confirm('确定停止后台进程 '+key+' 吗?'))return;await api('/api/processes/'+encodeURIComponent(key)+'/stop',{method:'POST',body:JSON.stringify({reason:'user requested from process panel'})});await refreshUserProcesses(true)}
106756
- function renderBoardsOptimized(){const ops=S.snap?.operations||[];renderRuntimeStatus();renderAskUserCard();renderCtxLive(S.snap);renderPlanLevelControls();_renderBridgeSyncFromSnapshot(S.snap||{});renderTodoTaskPanels();renderUserProcesses();refreshUserProcesses(false).catch(()=>{});renderActivityPanel();renderCommandsPanel(ops);renderDiffsPanel(ops);renderCatalogPanel();renderFilesPanelFromBoards(ops);renderUploadList();renderDownloadLinks();renderSkillsEntryLink()}
108183
+ function renderBoardsOptimized(){const ops=S.snap?.operations||[];renderRuntimeStatus();renderAskUserCard();renderGoalBar();renderGoalChip();renderCtxLive(S.snap);renderPlanLevelControls();_renderBridgeSyncFromSnapshot(S.snap||{});renderTodoTaskPanels();renderUserProcesses();refreshUserProcesses(false).catch(()=>{});renderActivityPanel();renderCommandsPanel(ops);renderDiffsPanel(ops);renderCatalogPanel();renderFilesPanelFromBoards(ops);renderUploadList();renderDownloadLinks();renderSkillsEntryLink()}
106757
108184
  function renderBoards(){renderBoardsOptimized();return;const uiState=S.staticMode?(S.frozen?'static':'live'):'live';const boolWord=v=>t(v?'state_on':'state_off');const activeRole=String(S.snap?.agent_active_role||'').trim();const activeRoleLabel=activeRole?_chatVirtAgentRoleLabel(activeRole):'-';const runtimeItems=[{label:t('rt_session'),value:S.snap?.id||'-',mono:true},{label:t('rt_model'),value:S.snap?.model||'-',mono:true},{label:t('rt_thinking'),value:boolWord(S.snap?.thinking)},{label:t('rt_thinking_stream'),value:boolWord(S.snap?.thinking_stream)},{label:t('rt_response_stream'),value:boolWord(S.snap?.response_stream)},{label:t('rt_mode'),value:S.snap?.execution_mode||S.config?.execution_mode||'sync'},{label:t('rt_active_agent'),value:activeRoleLabel},{label:t('rt_blackboard'),value:S.snap?.blackboard?.status||'-'},{label:t('rt_task'),value:S.snap?.blackboard?.task_profile?.task_type||'-'},{label:t('rt_complexity'),value:S.snap?.blackboard?.task_profile?.complexity||'-'},{label:t('rt_judgement'),value:S.snap?.blackboard?.manager_judgement?.progress||'-'},{label:t('rt_budget'),value:S.snap?.blackboard?.task_profile?.round_budget??'-'},{label:t('rt_remaining'),value:S.snap?.blackboard?.manager_judgement?.remaining_rounds??'-'},{label:t('rt_blackboard_cycles'),value:S.snap?.blackboard?.manager_cycles??'-'},{label:t('rt_round_limit'),value:S.snap?.max_agent_rounds||'-'},{label:t('rt_round'),value:S.snap?.agent_round_index??'-'},{label:t('rt_phase'),value:S.snap?.agent_phase||t('idle')},{label:t('rt_queued_inputs'),value:S.snap?.queued_user_inputs_count??0},{label:t('rt_run_timeout'),value:`${S.snap?.max_run_seconds??'-'}s`},{label:t('rt_ctx_used'),value:S.snap?.context_tokens_estimate??'-'},{label:t('rt_ctx_limit'),value:S.snap?.context_effective_token_limit||S.snap?.context_token_upper_bound||'-'},{label:t('rt_ctx_mode'),value:t(S.snap?.context_token_limit_locked?'rt_manual_lock':'rt_adaptive')},{label:t('rt_ctx_left'),value:formatContextLeft(S.snap)},{label:t('rt_truncation'),value:S.snap?.truncation_count||0},{label:t('rt_trunc_retry'),value:S.snap?.live_truncation_attempts||0},{label:t('rt_trunc_tokens'),value:S.snap?.live_truncation_tokens||0},{label:t('rt_archive'),value:S.snap?.compact_segments_count||0},{label:'完整归档记录',value:S.snap?.full_history_records||0},{label:'累计 Token / 总配额',value:modelTokenBudgetText()},{label:'步骤 Token / 配额',value:modelTokenBudgetText(true)},{label:'输入缓存命中',value:S.snap?.model_token_budget?.cache?.reported_calls?`${(100*Number(S.snap.model_token_budget.cache.hit_ratio||0)).toFixed(1)}%`:'未知'},{label:t('rt_last_compact'),value:fmtLastCompact(S.snap)},{label:t('rt_ollama'),value:S.snap?.ollama_base_url||'-',mono:true,wide:true},{label:t('rt_files'),value:S.snap?.session_files_root||'-',mono:true,wide:true},{label:t('rt_ui_mode'),value:uiState},{label:t('rt_state'),value:S.snap?.running?t('running'):t('idle'),tone:S.snap?.running?'state-running':'state-idle'}];E('status').innerHTML=runtimeItems.map(item=>_runtimePillHtml(item.label,item.value,item)).join('')+agentContextChipsHtml(S.snap);
106758
108185
  renderCtxLive(S.snap);
106759
108186
  const _pmBtn=E('planModeBtn');if(_pmBtn){const _pm=S.snap?.plan_mode_preference||'auto';_pmBtn.textContent=ccPlanModeLabel(_pm)}
@@ -106790,6 +108217,39 @@ function _normalizeModelCatalog(cat){const src=(cat&&typeof cat==='object')?cat:
106790
108217
  function _modelNameFromSelection(selection){const raw=String(selection||'').trim();if(!raw)return'';if(raw.includes('::')){const parts=raw.split('::',2);return String(parts[1]||parts[0]||'').trim()}return raw}
106791
108218
  function applyModelCatalog(cat){const norm=_normalizeModelCatalog(cat);const hasCat=!!(norm.options.length||norm.models.length||norm.selected);if(!hasCat)return false;S.modelOptions=norm.options;S.models=norm.models;S.config=S.config||{};if(norm.selected){S.config.model=norm.selected}else if(!String(S.config.model||'').trim()){const first=(norm.options[0]?.selection||norm.models[0]||'').trim();if(first)S.config.model=first}if(norm.thinking!==null)S.config.thinking=!!norm.thinking;if(norm.response_stream!==null)S.config.response_stream=!!norm.response_stream;renderModelControls();return true}
106792
108219
  function renderModelControls(){const sel=E('modelSelect');if(!sel)return;const active=document.activeElement===sel;const opts=S.modelOptions||[];const parts=[];if(opts.length){for(const it of opts){parts.push(`<option value=\"${esc(it.selection)}\">${esc(it.label||it.selection)}</option>`)}}else{const models=S.models||[];if(!models.length&&S.config?.model){parts.push(`<option value=\"${esc(S.config.model)}\">${esc(S.config.model)}</option>`)}for(const m of models){parts.push(`<option value=\"${esc(m)}\">${esc(m)}</option>`)}}const selected=String(S.config?.model||'').trim();let html=parts.join('');if(selected&&!parts.some(p=>p.includes(`value=\"${esc(selected)}\"`))){html+=`<option value=\"${esc(selected)}\">${esc(selected)}</option>`}setHtmlIfChanged('modelSelect',html,'modelSelect');if(selected&&sel.value!==selected&&!active)sel.value=selected}
108220
+ const CC_ACTIVE_SESSION_KEY='cc_active_session';
108221
+ function _rememberActiveSession(id){
108222
+ const sid=String(id||'').trim();
108223
+ if(!sid)return;
108224
+ // sessionStorage keeps each tab on its own session across reloads;
108225
+ // localStorage lets a new tab open the session viewed last.
108226
+ try{sessionStorage.setItem(CC_ACTIVE_SESSION_KEY,sid)}catch(_){}
108227
+ try{localStorage.setItem(CC_ACTIVE_SESSION_KEY,sid)}catch(_){}
108228
+ }
108229
+ function _rememberedSessionId(){
108230
+ let sid='';
108231
+ try{sid=String(sessionStorage.getItem(CC_ACTIVE_SESSION_KEY)||'')}catch(_){}
108232
+ if(!sid){try{sid=String(localStorage.getItem(CC_ACTIVE_SESSION_KEY)||'')}catch(_){}}
108233
+ return sid.trim();
108234
+ }
108235
+ async function _restoreRememberedSession(){
108236
+ const sid=_rememberedSessionId();
108237
+ if(!sid)return null;
108238
+ const row=S.sessionById.get(sid)||(Array.isArray(S.sessions)?S.sessions.find(item=>String(item?.id||'')===sid):null);
108239
+ if(row)return {id:sid,snapshot:null};
108240
+ // Older than the loaded catalog page, or hidden by a search: ask for it
108241
+ // directly. A deleted or foreign session fails here and falls back.
108242
+ try{
108243
+ const snap=await api('/api/sessions/'+encodeURIComponent(sid)+'?lite=1');
108244
+ if(snap&&String(snap.id||'')===sid){
108245
+ // Show it in the sidebar too; the catalog merge drops duplicates later.
108246
+ const listed={id:sid,title:String(snap.title||sid),title_origin:String(snap.title_origin||''),running:!!snap.running,updated_at:Number(snap.updated_at||0),created_at:Number(snap.created_at||0),message_count:Math.max(0,Number(snap.message_count||0)),ui_language:String(snap.ui_language||'')};
108247
+ S.sessions=mergeSessionRows(S.sessions,[listed],{append:true});
108248
+ return {id:sid,snapshot:snap};
108249
+ }
108250
+ }catch(_){}
108251
+ return null;
108252
+ }
106793
108253
  async function refreshSessions(opt={}){
106794
108254
  const useProvidedCfg=Object.prototype.hasOwnProperty.call(opt,'statsConfig');
106795
108255
  const useProvidedRows=Object.prototype.hasOwnProperty.call(opt,'sessions');
@@ -106805,9 +108265,17 @@ async function refreshSessions(opt={}){
106805
108265
  if(sig!==S.lastSessionsSig){S.lastSessionsSig=sig;renderSessions()}
106806
108266
  renderStats();
106807
108267
  let selectedId='';
106808
- if(!S.activeId&&S.sessions.length&&autoSelect){
106809
- selectedId=String(S.sessions[0]?.id||'').trim();
106810
- if(selectedId)await selectSession(selectedId,opt.selectOptions||{});
108268
+ if(!S.activeId&&autoSelect){
108269
+ // On the first load, reopen the session this tab was showing before the
108270
+ // reload; the first session in the list is only the fallback.
108271
+ const restore=!S.sessionsReady?await _restoreRememberedSession():null;
108272
+ if(restore&&!S.activeId){
108273
+ selectedId=restore.id;
108274
+ await selectSession(selectedId,restore.snapshot?{...(opt.selectOptions||{}),initialSnapshot:restore.snapshot}:(opt.selectOptions||{}));
108275
+ }else if(!S.activeId&&S.sessions.length){
108276
+ selectedId=String(S.sessions[0]?.id||'').trim();
108277
+ if(selectedId)await selectSession(selectedId,opt.selectOptions||{});
108278
+ }
106811
108279
  }
106812
108280
  // The welcome panel may show for "no session" only after the catalog has
106813
108281
  // loaded and the last session had its chance to be restored.
@@ -107147,6 +108615,7 @@ async function selectSession(id,opt={}){
107147
108615
  const catalogRow=S.sessionById.get(String(id||''))||(Array.isArray(S.sessions)?S.sessions.find(row=>String(row?.id||'')===String(id||'')):null)||{id};
107148
108616
  const initialSnapshot=(opt.initialSnapshot&&typeof opt.initialSnapshot==='object')?opt.initialSnapshot:_initialSessionSnapshot(catalogRow);
107149
108617
  S.activeId=id;
108618
+ _rememberActiveSession(id);
107150
108619
  if(initialSnapshot)S.snap=initialSnapshot;
107151
108620
  S.frozen=false;
107152
108621
  S.lastEventSeq=0;
@@ -107222,7 +108691,7 @@ async function deleteSession(){if(!S.activeId){showError(t('select_session_first
107222
108691
  async function applyModel(){const sel=E('modelSelect');const btn=E('applyModelBtn');const model=sel?.value||'';if(!model){showError(t('no_model_selected'));return}if(S.staticMode&&S.frozen)resumeAutoUpdates();S.config=S.config||{};const prevModel=String(S.config.model||'');const prevSnapModel=String(S.snap?.model||'');const prevSnapCatalog=(S.snap&&typeof S.snap==='object')?S.snap.llm_model_catalog:undefined;try{S.config.model=model;if(S.snap&&typeof S.snap==='object'){S.snap.model=_modelNameFromSelection(model)||S.snap.model;if(!S.snap.llm_model_catalog||typeof S.snap.llm_model_catalog!=='object')S.snap.llm_model_catalog={};S.snap.llm_model_catalog.selected=model}renderModelControls();renderStats();if(S.snap)renderBoards();if(sel)sel.disabled=true;if(btn)btn.disabled=true;const path=S.activeId?('/api/sessions/'+S.activeId+'/config/model'):'/api/config/model';const changed=await api(path,{method:'POST',body:JSON.stringify({selection:model,model})});if(changed?.note)showError(changed.note);else showError('');if(!applyModelCatalog(changed)){const cat=await loadModelCatalog();if(!applyModelCatalog(cat)){S.config.model=String(changed?.selected||model||'').trim();renderModelControls()}}if(S.snap&&typeof S.snap==='object'){const selected=String(S.config?.model||model||'').trim();const modelName=_modelNameFromSelection(selected);if(modelName)S.snap.model=modelName;if(changed&&typeof changed==='object')S.snap.llm_model_catalog=changed;renderBoards()}scheduleSnapshot({forceFull:true,delayMs:40,allowWhenFrozen:true})}catch(err){S.config.model=prevModel;if(S.snap&&typeof S.snap==='object'){if(prevSnapModel)S.snap.model=prevSnapModel;if(prevSnapCatalog!==undefined)S.snap.llm_model_catalog=prevSnapCatalog;renderBoards()}renderModelControls();renderStats();showError(err.message||String(err))}finally{if(sel)sel.disabled=false;if(btn)btn.disabled=false}}
107223
108692
 
107224
108693
  async function uploadLlmConfigFile(file){try{if(!S.activeId){showError(t('select_session_first'));return}if(!file){return}const arr=await file.arrayBuffer();const payload={filename:'LLM.config.json',mime:file.type||'application/json',content_b64:ab2b64(arr)};const out=await api('/api/sessions/'+S.activeId+'/uploads',{method:'POST',body:JSON.stringify(payload)});const note=String(out?.note||out?.model_catalog?.note||'').trim();if(!out?.model_catalog){showError(t('config_uploaded_no_profiles'));}else{showError(note||'');const modal=E('llmConfigModal');if(modal)modal.style.display='none'}const cat=out?.model_catalog||await loadModelCatalog();if(!applyModelCatalog(cat)){renderModelControls()}await refreshSnapshot({forceFull:true,allowWhenFrozen:true})}catch(err){showError(err.message||String(err))}}
107225
- async function sendMessage(){showError('');const promptEl=E('prompt');const promptText=promptEl.value.trim();const sessionId=String(S.activeId||'').trim();if(!promptText||!sessionId)return;if(S.staticMode&&S.frozen)resumeAutoUpdates();_setSubmissionState(sessionId,'submitting');promptEl.value='';try{const configuredWait=Number(S.config?.chat_upload_frontend_wait_ms);const handoffWait=Number.isFinite(configuredWait)?Math.max(0,Math.min(5000,configuredWait)):CHAT_UPLOAD_HANDOFF_WAIT_MS;const uploadWait=await waitForPendingUploads(handoffWait);if(uploadWait&&!uploadWait.ok&&(uploadWait.timeout||uploadWait.error)){showError(uploadWait.timeout?'上传仍在后台处理;任务已先提交,文件完成后会出现在工作区。':`上传继续在后台处理:${uploadWait.error.message||uploadWait.error}`)}const out=await api('/api/sessions/'+sessionId+'/message',{method:'POST',body:JSON.stringify({content:promptText})});_submissionStateFromAck(sessionId,out);S.lastDeltaTs=Date.now();if(String(S.activeId||'')===sessionId)scheduleSnapshot({forceFull:false,delayMs:40,allowWhenFrozen:true});scheduleSessionPoll(true);if(out&&out.queued&&!out.scheduler_started&&!out.deferred_start&&!out.live_input){const pos=Number(out.queue_position||0);const size=Number(out.queue_size||0);showError(`${t('event_scheduler_queued_title')}${pos?` · ${t('event_scheduler_queue_position')} ${pos}${size?`/${size}`:''}`:''}`)}}catch(err){_setSubmissionState(sessionId,'failed',{error:String(err?.message||err||'')});if(String(S.activeId||'')===sessionId&&!promptEl.value.trim())promptEl.value=promptText;showError(err.message||String(err))}}
108694
+ async function sendMessage(){showError('');const promptEl=E('prompt');const promptText=promptEl.value.trim();const sessionId=String(S.activeId||'').trim();if(!promptText||!sessionId)return;if(S.staticMode&&S.frozen)resumeAutoUpdates();_setSubmissionState(sessionId,'submitting');promptEl.value='';try{const configuredWait=Number(S.config?.chat_upload_frontend_wait_ms);const handoffWait=Number.isFinite(configuredWait)?Math.max(0,Math.min(5000,configuredWait)):CHAT_UPLOAD_HANDOFF_WAIT_MS;const uploadWait=await waitForPendingUploads(handoffWait);if(uploadWait&&!uploadWait.ok&&(uploadWait.timeout||uploadWait.error)){showError(uploadWait.timeout?'上传仍在后台处理;任务已先提交,文件完成后会出现在工作区。':`上传继续在后台处理:${uploadWait.error.message||uploadWait.error}`)}const out=await api('/api/sessions/'+sessionId+'/message',{method:'POST',body:JSON.stringify({content:promptText})});_submissionStateFromAck(sessionId,out);if(out&&(out.goal_command||out.slash_command)&&!out.running&&!out.queued&&!out.live_input&&!out.deferred_start&&!out.task_submitted&&S.submissionBySession)S.submissionBySession.delete(sessionId);if(out&&out.slash_command==='plan'&&S.snap){S.snap.plan_mode_preference=String(out.plan_mode||S.snap.plan_mode_preference||'auto');renderPlanLevelControls()}renderGoalChip();S.lastDeltaTs=Date.now();if(String(S.activeId||'')===sessionId)scheduleSnapshot({forceFull:false,delayMs:40,allowWhenFrozen:true});scheduleSessionPoll(true);if(out&&out.queued&&!out.scheduler_started&&!out.deferred_start&&!out.live_input){const pos=Number(out.queue_position||0);const size=Number(out.queue_size||0);showError(`${t('event_scheduler_queued_title')}${pos?` · ${t('event_scheduler_queue_position')} ${pos}${size?`/${size}`:''}`:''}`)}}catch(err){_setSubmissionState(sessionId,'failed',{error:String(err?.message||err||'')});if(String(S.activeId||'')===sessionId&&!promptEl.value.trim())promptEl.value=promptText;showError(err.message||String(err))}}
107226
108695
  async function interruptRun(){if(!S.activeId)return;if(S.staticMode&&S.frozen)resumeAutoUpdates();const sessionId=String(S.activeId||'');await api('/api/sessions/'+sessionId+'/interrupt',{method:'POST'});_setSubmissionState(sessionId,'complete');S.lastDeltaTs=Date.now();if(!S.es||S.es.readyState===2){scheduleSnapshot({forceFull:false,delayMs:140,allowWhenFrozen:true})}}
107227
108696
  async function compactNow(){if(!S.activeId)return;if(S.staticMode&&S.frozen)resumeAutoUpdates();await api('/api/sessions/'+S.activeId+'/compact',{method:'POST'});S.lastDeltaTs=Date.now();scheduleCompactRefreshBurst(COMPACT_AUTO_REFRESH_COUNT);if(!S.es||S.es.readyState===2){scheduleSnapshot({forceFull:false,delayMs:180,allowWhenFrozen:true})}}
107228
108697
  async function clearStaleTodos(){if(!S.activeId){showError(t('select_session_first'));return}if(S.staticMode&&S.frozen)resumeAutoUpdates();await api('/api/sessions/'+S.activeId+'/todos/clear-stale',{method:'POST'});S.lastDeltaTs=Date.now();if(!S.es||S.es.readyState===2){scheduleSnapshot({forceFull:false,delayMs:160,allowWhenFrozen:true})}}
@@ -107726,6 +109195,162 @@ applyMainI18n=function(){const out=_ccOrigApplyMainI18n.apply(this,arguments);tr
107726
109195
  window.addEventListener('DOMContentLoaded',()=>{try{ccBindShell()}catch(err){console.error('cc shell init failed',err)}});
107727
109196
  """
107728
109197
 
109198
+ APP_JS += r"""
109199
+ /* goal mode: status bar above the composer and cards in the conversation */
109200
+ Object.assign(I18N['en'],{goal_label:'Goal',goal_st_active:'Active',goal_st_paused:'Paused',goal_st_complete:'Achieved',goal_st_impossible:'Not possible',goal_st_budget_limited:'Budget used up',goal_st_cleared:'Cleared',goal_evaluating:'Checking the condition',goal_turn:'turn {n}/{max}',goal_tokens:'{n} tokens',goal_pause:'Pause',goal_resume:'Resume',goal_clear:'Clear',goal_reason:'Evaluator',goal_next:'Next step',goal_condition:'Condition',goal_ph_set:'Goal set',goal_ph_continue:'Goal not met yet',goal_ph_complete:'Goal achieved',goal_ph_impossible:'Goal judged impossible',goal_ph_budget_limited:'Goal budget used up',goal_ph_paused:'Goal paused',goal_ph_pause:'Goal paused',goal_ph_resume:'Goal resumed',goal_ph_clear:'Goal cleared',goal_ph_waiting:'Goal waiting for you',goal_ph_deferred:'Goal continues after your message',goal_ph_status:'Goal status',goal_ph_error:'Goal command not applied',goal_next_turn:'next: turn {n}',goal_hint:'Type /goal <condition> to set a goal; /goal pause, /goal resume, /goal clear'});
109201
+ Object.assign(I18N['zh-CN'],{goal_label:'目标',goal_st_active:'进行中',goal_st_paused:'已暂停',goal_st_complete:'已达成',goal_st_impossible:'无法达成',goal_st_budget_limited:'预算用尽',goal_st_cleared:'已清除',goal_evaluating:'正在检查完成条件',goal_turn:'第 {n}/{max} 轮',goal_tokens:'{n} tokens',goal_pause:'暂停',goal_resume:'继续',goal_clear:'清除',goal_reason:'评估',goal_next:'下一步',goal_condition:'完成条件',goal_ph_set:'已设定目标',goal_ph_continue:'目标尚未达成',goal_ph_complete:'目标已达成',goal_ph_impossible:'目标被判定为无法达成',goal_ph_budget_limited:'目标预算已用尽',goal_ph_paused:'目标已暂停',goal_ph_pause:'目标已暂停',goal_ph_resume:'目标已继续',goal_ph_clear:'目标已清除',goal_ph_waiting:'目标等待你的回复',goal_ph_deferred:'处理完你的新消息后继续目标',goal_ph_status:'目标状态',goal_ph_error:'目标命令未生效',goal_next_turn:'接下来:第 {n} 轮',goal_hint:'输入 /goal <完成条件> 设定目标;/goal pause、/goal resume、/goal clear'});
109202
+ Object.assign(I18N['zh-TW'],{goal_label:'目標',goal_st_active:'進行中',goal_st_paused:'已暫停',goal_st_complete:'已達成',goal_st_impossible:'無法達成',goal_st_budget_limited:'預算用盡',goal_st_cleared:'已清除',goal_evaluating:'正在檢查完成條件',goal_turn:'第 {n}/{max} 輪',goal_tokens:'{n} tokens',goal_pause:'暫停',goal_resume:'繼續',goal_clear:'清除',goal_reason:'評估',goal_next:'下一步',goal_condition:'完成條件',goal_ph_set:'已設定目標',goal_ph_continue:'目標尚未達成',goal_ph_complete:'目標已達成',goal_ph_impossible:'目標被判定為無法達成',goal_ph_budget_limited:'目標預算已用盡',goal_ph_paused:'目標已暫停',goal_ph_pause:'目標已暫停',goal_ph_resume:'目標已繼續',goal_ph_clear:'目標已清除',goal_ph_waiting:'目標等待你的回覆',goal_ph_deferred:'處理完你的新訊息後繼續目標',goal_ph_status:'目標狀態',goal_ph_error:'目標指令未生效',goal_next_turn:'接下來:第 {n} 輪',goal_hint:'輸入 /goal <完成條件> 設定目標;/goal pause、/goal resume、/goal clear'});
109203
+ Object.assign(I18N['ja'],{goal_label:'ゴール',goal_st_active:'実行中',goal_st_paused:'一時停止',goal_st_complete:'達成',goal_st_impossible:'達成不可',goal_st_budget_limited:'予算切れ',goal_st_cleared:'解除済み',goal_evaluating:'完了条件を確認中',goal_turn:'{n}/{max} ターン',goal_tokens:'{n} トークン',goal_pause:'一時停止',goal_resume:'再開',goal_clear:'解除',goal_reason:'評価',goal_next:'次の手順',goal_condition:'完了条件',goal_ph_set:'ゴールを設定しました',goal_ph_continue:'ゴールはまだ未達成です',goal_ph_complete:'ゴールを達成しました',goal_ph_impossible:'ゴールは達成不可と判定されました',goal_ph_budget_limited:'ゴールの予算を使い切りました',goal_ph_paused:'ゴールを一時停止しました',goal_ph_pause:'ゴールを一時停止しました',goal_ph_resume:'ゴールを再開しました',goal_ph_clear:'ゴールを解除しました',goal_ph_waiting:'ゴールはあなたの返答を待っています',goal_ph_deferred:'新しいメッセージの後でゴールを続けます',goal_ph_status:'ゴールの状態',goal_ph_error:'ゴールのコマンドは適用されませんでした',goal_next_turn:'次:{n} ターン目',goal_hint:'/goal <完了条件> でゴールを設定、/goal pause・/goal resume・/goal clear'});
109204
+ function _goalFmtDuration(sec){const s=Math.max(0,Math.round(Number(sec)||0));if(s<60)return s+'s';const m=Math.floor(s/60);if(m<60)return m+'m';return Math.floor(m/60)+'h '+String(m%60).padStart(2,'0')+'m'}
109205
+ function _goalFmtTokens(n){const v=Math.max(0,Number(n)||0);if(v>=1e6)return (v/1e6).toFixed(v>=1e7?0:1)+'M';if(v>=1e3)return (v/1e3).toFixed(v>=1e4?0:1)+'k';return String(Math.round(v))}
109206
+ function _goalElapsed(goal){const g=goal||{};let used=Number(g.time_used_seconds)||0;const since=Number(g.active_since)||0;if(g.status==='active'&&since>0){const live=(Number(g.time_banked_seconds)||0)+Date.now()/1000-since;if(live>=0)used=live}return used}
109207
+ function _goalTone(status){return status==='active'?'live':status==='complete'?'ok':status==='paused'?'warn':status==='cleared'?'neutral':'warn'}
109208
+ function _goalTurnNow(goal){const g=goal||{},done=Number(g.turns)||0,max=Number(g.max_turns)||0;return g.status==='active'&&(!max||done<max)?done+1:done}
109209
+ function _goalMeta(goal){const g=goal||{},parts=[];if(Number(g.max_turns)>0)parts.push(t('goal_turn',{n:_goalTurnNow(g),max:Number(g.max_turns)}));parts.push(_goalFmtDuration(_goalElapsed(g))+(Number(g.time_budget_seconds)>0?' / '+_goalFmtDuration(g.time_budget_seconds):''));if(Number(g.tokens_used)>0||Number(g.token_budget)>0)parts.push(t('goal_tokens',{n:_goalFmtTokens(g.tokens_used)+(Number(g.token_budget)>0?' / '+_goalFmtTokens(g.token_budget):'')}));return parts.join(' · ')}
109210
+ function _goalCardHtml(info){
109211
+ const d=(info&&typeof info==='object')?info:{};const g=(d.goal&&typeof d.goal==='object')?d.goal:{};
109212
+ const phase=String(d.phase||'status');const status=String(g.status||'');
109213
+ const title=t('goal_ph_'+phase)===('goal_ph_'+phase)?String(d.summary||t('goal_label')):t('goal_ph_'+phase);
109214
+ const pills=[];
109215
+ if(status)pills.push(_chatVirtEventPillHtml(t('goal_st_'+status),_goalTone(status)==='live'?'info':_goalTone(status)));
109216
+ if(Number(g.max_turns)>0)pills.push(_chatVirtEventPillHtml(t('goal_turn',{n:Number(d.turn)||_goalTurnNow(g),max:Number(g.max_turns)}),'neutral','mono'));
109217
+ const grid=[];
109218
+ if(d.reason)grid.push(_chatVirtEventCellHtml(t('goal_reason'),String(d.reason),{}));
109219
+ if(d.next_step&&phase!=='complete')grid.push(_chatVirtEventCellHtml(t('goal_next'),String(d.next_step),{}));
109220
+ const notes=[];
109221
+ if((phase==='error'||phase==='waiting'||phase==='deferred')&&d.summary)notes.push(`<div class="msg-event-note">${esc(String(d.summary||''))}</div>`);
109222
+ if(phase==='continue')notes.push(`<div class="msg-event-note">${esc(t('goal_next_turn',{n:(Number(d.turn)||0)+1}))}</div>`);
109223
+ if(phase==='preferences')notes.push(`<div class="msg-event-note">${esc(t(d.mode==='on'?'goal_propose_on':'goal_propose_off'))}</div>`);
109224
+ if(phase==='set'&&d.origin==='proposal')notes.push(`<div class="msg-event-note">${esc(t('goal_from_proposal'))}</div>`);
109225
+ if(status&&g.status_reason&&phase!=='continue'&&String(g.status_reason)!==String(d.reason||''))notes.push(`<div class="msg-event-note">${esc(String(g.status_reason))}</div>`);
109226
+ if(phase==='set'||phase==='status'){if(g.objective)grid.push(_chatVirtEventCellHtml(t('goal_condition'),String(g.objective),{}));if(status)notes.push(`<div class="msg-event-note mono">${esc(_goalMeta(g))}</div>`)}
109227
+ if(phase==='status'&&!status)notes.push(`<div class="msg-event-note">${esc(t('goal_hint'))}</div>`);
109228
+ const tone=phase==='complete'?'success':(phase==='continue'||phase==='set'||phase==='status'||phase==='resume')?'notice':'warning';
109229
+ const sub=(phase==='set'||phase==='status')?'':String(g.objective||'').slice(0,160);
109230
+ return _chatVirtEventCardHtml(title,sub,pills,grid,notes.length?`<div class="msg-event-body">${notes.join('')}</div>`:'',`msg-event-card-runtime msg-goal-card ${tone}`);
109231
+ }
109232
+ function renderGoalBar(){
109233
+ const bar=E('goalBar');if(!bar)return;
109234
+ const g=(S.snap&&S.snap.goal&&typeof S.snap.goal==='object')?S.snap.goal:{};
109235
+ const status=String(g.status||'');
109236
+ if(status!=='active'&&status!=='paused'){if(!bar.hidden){bar.hidden=true;bar.innerHTML=''}return}
109237
+ const last=(g.last_verdict&&typeof g.last_verdict==='object')?g.last_verdict:{};
109238
+ const state=g.evaluating?t('goal_evaluating'):t('goal_st_'+status);
109239
+ const reason=last.reason?`<div class="goal-bar-reason"><b>${esc(t('goal_reason'))}</b> ${esc(String(last.reason))}${last.next_step?` <b>${esc(t('goal_next'))}</b> ${esc(String(last.next_step))}`:''}</div>`:'';
109240
+ const acts=(status==='active'?[['pause',t('goal_pause')]]:[['resume',t('goal_resume')]]).concat([['clear',t('goal_clear')]]);
109241
+ const html=`<div class="goal-bar-main"><span class="goal-bar-mark ${_goalTone(status)}${g.evaluating?' busy':''}" aria-hidden="true"></span><span class="goal-bar-label">${esc(t('goal_label'))}</span><span class="goal-bar-state">${esc(state)}</span><span class="goal-bar-objective" title="${esc(String(g.objective||''))}">${esc(String(g.objective||''))}</span><span class="goal-bar-meta">${esc(_goalMeta(g))}</span><span class="goal-bar-actions">${acts.map(([a,l])=>`<button type="button" class="goal-bar-btn" data-goal-action="${a}">${esc(l)}</button>`).join('')}</span></div>${reason}`;
109242
+ if(bar.innerHTML!==html)bar.innerHTML=html;
109243
+ bar.hidden=false;bar.dataset.status=status;
109244
+ }
109245
+ async function goalAction(action){const sid=String(S.activeId||'').trim();if(!sid)return;try{await api('/api/sessions/'+sid+'/message',{method:'POST',body:JSON.stringify({content:'/goal '+action})})}catch(err){showError(String(err&&err.message||err))}scheduleSnapshot({forceFull:false,delayMs:60,allowWhenFrozen:true})}
109246
+ document.addEventListener('click',ev=>{const btn=ev.target&&ev.target.closest?ev.target.closest('[data-goal-action]'):null;if(!btn)return;ev.preventDefault();goalAction(String(btn.dataset.goalAction||''))});
109247
+ setInterval(()=>{if(S.snap&&S.snap.goal&&S.snap.goal.status==='active')renderGoalBar()},15000);
109248
+
109249
+ /* goal menu next to the plan button, and /plan cards */
109250
+ Object.assign(I18N['en'],{goal_menu_none:'No goal is set. Send /goal <condition> to start one.',goal_menu_budget:'Budget for the next /goal',goal_menu_turns:'Turns',goal_menu_tokens:'Tokens',goal_menu_time:'Time (min)',goal_menu_default:'default {n}',goal_menu_unlimited:'no limit',goal_menu_turn_note:'One goal turn is one whole agent run, and a run can use up to the Agent round limit. The default comes from Admin (Default goal turns).',goal_menu_propose:'Let the model propose a goal (needs your confirmation)',goal_menu_saved:'Saved',goal_menu_bad:'Use a number, e.g. 50000 or 50k',goal_ph_preferences:'Goal settings',goal_propose_on:'The agent may propose a goal; you confirm it first',goal_propose_off:'The agent will not propose goals',slash_plan_title:'Plan mode',slash_plan_note_on:'The agent proposes a plan before it works.',slash_plan_note_off:'The agent works without a plan proposal.',slash_plan_note_auto:'The agent decides per task.',slash_plan_task:'The task was sent.',goal_from_proposal:'Proposed by the agent and confirmed by you.'});
109251
+ Object.assign(I18N['zh-CN'],{goal_menu_none:'尚未设定目标。发送 /goal <完成条件> 开始。',goal_menu_budget:'下一个 /goal 的预算',goal_menu_turns:'轮数',goal_menu_tokens:'Tokens',goal_menu_time:'时间(分钟)',goal_menu_default:'默认 {n}',goal_menu_unlimited:'不限',goal_menu_turn_note:'目标的一轮是一次完整的智能体运行,每次运行最多可用到 Agent 最大轮数。默认值来自 Admin 的“目标默认轮数”。',goal_menu_propose:'允许模型提议目标(需确认)',goal_menu_saved:'已保存',goal_menu_bad:'请输入数字,例如 50000 或 50k',goal_ph_preferences:'目标设置',goal_propose_on:'智能体可以提议目标,需你确认后生效',goal_propose_off:'智能体不会提议目标',slash_plan_title:'计划模式',slash_plan_note_on:'智能体先提出计划再执行。',slash_plan_note_off:'智能体不提出计划,直接执行。',slash_plan_note_auto:'由智能体按任务决定。',slash_plan_task:'任务已发送。',goal_from_proposal:'由智能体提议,经你确认。'});
109252
+ Object.assign(I18N['zh-TW'],{goal_menu_none:'尚未設定目標。傳送 /goal <完成條件> 開始。',goal_menu_budget:'下一個 /goal 的預算',goal_menu_turns:'輪數',goal_menu_tokens:'Tokens',goal_menu_time:'時間(分鐘)',goal_menu_default:'預設 {n}',goal_menu_unlimited:'不限',goal_menu_turn_note:'目標的一輪是一次完整的智能體執行,每次執行最多可用到 Agent 最大輪數。預設值來自 Admin 的「目標預設輪數」。',goal_menu_propose:'允許模型提議目標(需確認)',goal_menu_saved:'已儲存',goal_menu_bad:'請輸入數字,例如 50000 或 50k',goal_ph_preferences:'目標設定',goal_propose_on:'智能體可以提議目標,需你確認後生效',goal_propose_off:'智能體不會提議目標',slash_plan_title:'計畫模式',slash_plan_note_on:'智能體先提出計畫再執行。',slash_plan_note_off:'智能體不提出計畫,直接執行。',slash_plan_note_auto:'由智能體依任務決定。',slash_plan_task:'任務已送出。',goal_from_proposal:'由智能體提議,經你確認。'});
109253
+ Object.assign(I18N['ja'],{goal_menu_none:'ゴールは未設定です。/goal <完了条件> を送ると始まります。',goal_menu_budget:'次の /goal の予算',goal_menu_turns:'ターン数',goal_menu_tokens:'トークン',goal_menu_time:'時間(分)',goal_menu_default:'既定 {n}',goal_menu_unlimited:'上限なし',goal_menu_turn_note:'ゴールの 1 ターンはエージェントの 1 回の実行で、1 回の実行では Agent 最大ラウンド数まで使えます。既定値は Admin の「ゴールの既定ターン数」です。',goal_menu_propose:'モデルによるゴールの提案を許可(確認が必要)',goal_menu_saved:'保存しました',goal_menu_bad:'数値を入力してください(例: 50000 または 50k)',goal_ph_preferences:'ゴールの設定',goal_propose_on:'エージェントがゴールを提案できます。設定する前に確認します',goal_propose_off:'エージェントはゴールを提案しません',slash_plan_title:'プランモード',slash_plan_note_on:'エージェントは作業前にプランを提案します。',slash_plan_note_off:'エージェントはプランを提案せずに作業します。',slash_plan_note_auto:'タスクごとにエージェントが判断します。',slash_plan_task:'タスクを送信しました。',goal_from_proposal:'エージェントが提案し、あなたが確認しました。'});
109254
+ function _goalPrefs(){return(S.snap&&S.snap.goal_preferences&&typeof S.snap.goal_preferences==='object')?S.snap.goal_preferences:{}}
109255
+ function _goalSnapStatus(){const g=(S.snap&&S.snap.goal&&typeof S.snap.goal==='object')?S.snap.goal:{};return String(g.status||'')}
109256
+ function _goalMenuVisible(){const st=_goalSnapStatus();const p=E('prompt');const typed=!!(p&&/^\s*\/goal(?:\s|$)/i.test(String(p.value||'')));return typed||st==='active'||st==='paused'||!!_goalPrefs().allow_model_proposals||S.openPopup==='goalMenu'}
109257
+ function _goalFmtTokenInput(n){const v=Number(n)||0;if(v<=0)return'';if(v%1000000===0)return(v/1000000)+'m';if(v%1000===0)return(v/1000)+'k';return String(v)}
109258
+ function _goalParseTokenInput(raw){const s=String(raw||'').trim().toLowerCase().replace(/[,_\s]/g,'');if(!s)return 0;const m=s.match(/^(\d+(?:\.\d+)?)(k|m)?$/);if(!m)return NaN;return Math.round(Number(m[1])*(m[2]==='m'?1000000:m[2]==='k'?1000:1))}
109259
+ function renderGoalMenuState(){
109260
+ const host=E('goalMenuState');if(!host)return;
109261
+ const g=(S.snap&&S.snap.goal&&typeof S.snap.goal==='object')?S.snap.goal:{};const st=String(g.status||'');
109262
+ let html;
109263
+ if(st==='active'||st==='paused'){
109264
+ const acts=(st==='active'?[['pause',t('goal_pause')]]:[['resume',t('goal_resume')]]).concat([['clear',t('goal_clear')]]);
109265
+ html=`<div class="goal-menu-status"><span class="goal-bar-mark ${_goalTone(st)}${g.evaluating?' busy':''}" aria-hidden="true"></span><b>${esc(g.evaluating?t('goal_evaluating'):t('goal_st_'+st))}</b><span class="goal-menu-meta mono">${esc(_goalMeta(g))}</span></div><div class="goal-menu-objective">${esc(String(g.objective||''))}</div><div class="goal-menu-actions">${acts.map(([a,l])=>`<button type="button" class="goal-bar-btn" data-goal-action="${a}">${esc(l)}</button>`).join('')}</div>`;
109266
+ }else html=`<div class="goal-menu-empty">${esc(t('goal_menu_none'))}</div>`;
109267
+ if(host.innerHTML!==html)host.innerHTML=html;
109268
+ }
109269
+ function renderGoalMenu(){
109270
+ const menu=E('goalMenu');if(!menu)return;
109271
+ const p=_goalPrefs();const def=Number(p.default_turns)||30;const lim=Number(p.max_turns_limit)||500;
109272
+ menu.innerHTML=`<div id="goalMenuState" class="goal-menu-sec"></div><div class="goal-menu-sec"><div class="goal-menu-h">${esc(t('goal_menu_budget'))}</div><div class="goal-menu-grid"><label>${esc(t('goal_menu_turns'))}<input id="goalPrefTurns" type="number" min="0" max="${lim}" step="1" inputmode="numeric" placeholder="${esc(t('goal_menu_default',{n:def}))}" value="${Number(p.max_turns)>0?Number(p.max_turns):''}"></label><label>${esc(t('goal_menu_tokens'))}<input id="goalPrefTokens" type="text" inputmode="numeric" placeholder="${esc(t('goal_menu_unlimited'))}" value="${esc(_goalFmtTokenInput(p.token_budget))}"></label><label>${esc(t('goal_menu_time'))}<input id="goalPrefTime" type="number" min="0" step="1" inputmode="numeric" placeholder="${esc(t('goal_menu_unlimited'))}" value="${Number(p.time_budget_seconds)>0?Math.round(Number(p.time_budget_seconds)/60):''}"></label></div><div class="goal-menu-note">${esc(t('goal_menu_turn_note'))}</div></div><label class="goal-menu-check"><input id="goalPrefPropose" type="checkbox"${p.allow_model_proposals?' checked':''}><span>${esc(t('goal_menu_propose'))}</span></label><div id="goalPrefStatus" class="goal-menu-foot" aria-live="polite"></div>`;
109273
+ renderGoalMenuState();
109274
+ }
109275
+ async function saveGoalPrefs(){
109276
+ const sid=String(S.activeId||'').trim();if(!sid)return;
109277
+ const status=E('goalPrefStatus');const turnsRaw=String(E('goalPrefTurns')?.value||'').trim();const tokens=_goalParseTokenInput(E('goalPrefTokens')?.value);const minutes=String(E('goalPrefTime')?.value||'').trim();
109278
+ const lim=Number(_goalPrefs().max_turns_limit)||500;const turns=turnsRaw?Math.round(Number(turnsRaw)):0;const mins=minutes?Number(minutes):0;
109279
+ if(!Number.isFinite(tokens)||!Number.isFinite(turns)||turns<0||turns>lim||!Number.isFinite(mins)||mins<0){if(status){status.textContent=t('goal_menu_bad');status.className='goal-menu-foot bad'}return}
109280
+ const body={max_turns:turns,token_budget:tokens,time_budget_seconds:Math.round(mins*60),allow_model_proposals:!!E('goalPrefPropose')?.checked};
109281
+ try{const out=await api('/api/sessions/'+encodeURIComponent(sid)+'/config/goal',{method:'POST',body:JSON.stringify(body)});if(S.snap&&out&&out.preferences)S.snap.goal_preferences=out.preferences;if(status){status.textContent=t('goal_menu_saved');status.className='goal-menu-foot ok'}renderGoalChip()}catch(err){if(status){status.textContent=String(err&&err.message||err);status.className='goal-menu-foot bad'}}
109282
+ }
109283
+ function renderGoalChip(){
109284
+ const wrap=E('goalDropdown'),btn=E('goalMenuBtn');if(!wrap||!btn)return;
109285
+ const show=_goalMenuVisible();if(wrap.hidden===show)wrap.hidden=!show;
109286
+ const st=_goalSnapStatus();const label=(st==='active'||st==='paused')?`${t('goal_label')}: ${t('goal_st_'+st)}`:t('goal_label');
109287
+ setTextIfChanged(btn,label);btn.classList.toggle('is-on',st==='active');btn.setAttribute('data-goal-status',st||'none');
109288
+ if(S.openPopup==='goalMenu')renderGoalMenuState();
109289
+ }
109290
+ function _slashCommandCardHtml(info){
109291
+ const d=(info&&typeof info==='object')?info:{};const mode=['on','off','auto'].includes(String(d.mode||''))?String(d.mode):'auto';
109292
+ if(String(d.command||'')!=='plan')return _chatVirtEventCardHtml(String(d.summary||'/'),'',[],[],'','msg-event-card-runtime notice');
109293
+ const notes=[`<div class="msg-event-note">${esc(t('slash_plan_note_'+mode))}</div>`];if(d.action==='task')notes.push(`<div class="msg-event-note">${esc(t('slash_plan_task'))}</div>`);
109294
+ return _chatVirtEventCardHtml(t('slash_plan_title'),'',[_chatVirtEventPillHtml(t('ui_plan_label',{mode:t('ui_plan_'+mode)}),mode==='on'?'info':'neutral')],[],`<div class="msg-event-body">${notes.join('')}</div>`,'msg-event-card-runtime msg-slash-card notice');
109295
+ }
109296
+ window.addEventListener('DOMContentLoaded',()=>{
109297
+ bindPopupButton('goalMenuBtn','goalMenu',(menu)=>{
109298
+ menu.addEventListener('click',ev=>{const b=ev.target&&ev.target.closest?ev.target.closest('[data-goal-action]'):null;if(!b)return;ev.preventDefault();goalAction(String(b.dataset.goalAction||''))});
109299
+ menu.addEventListener('change',ev=>{if(ev.target&&/^goalPref/.test(String(ev.target.id||'')))saveGoalPrefs()});
109300
+ });
109301
+ E('goalMenuBtn')?.addEventListener('click',()=>{if(S.openPopup==='goalMenu')renderGoalMenu();renderGoalChip()});
109302
+ E('prompt')?.addEventListener('input',renderGoalChip);
109303
+ renderGoalChip();
109304
+ });
109305
+ """
109306
+
109307
+ APP_CSS += r"""
109308
+ .goal-bar{border:1px solid var(--teal-line);border-radius:var(--r-lg);background:var(--teal-soft);padding:7px 10px;margin-bottom:8px;font-size:12.5px;color:var(--fg-2)}
109309
+ .goal-bar[data-status="paused"]{border-color:var(--amber-line);background:var(--amber-soft)}
109310
+ .goal-bar-main{display:flex;align-items:center;gap:8px;min-width:0}
109311
+ .goal-bar-mark{flex:0 0 auto;width:12px;height:12px;border-radius:50%;border:2px solid var(--teal);box-sizing:border-box;position:relative}
109312
+ .goal-bar-mark::after{content:"";position:absolute;inset:2px;border-radius:50%;background:var(--teal)}
109313
+ .goal-bar-mark.warn{border-color:var(--amber)}.goal-bar-mark.warn::after{background:var(--amber)}
109314
+ .goal-bar-mark.busy{animation:goalPulse 1.2s ease-in-out infinite}
109315
+ @keyframes goalPulse{50%{opacity:.35}}
109316
+ .goal-bar-label{font-weight:600;color:var(--fg)}
109317
+ .goal-bar-state{color:var(--teal);font-weight:500;white-space:nowrap}
109318
+ .goal-bar[data-status="paused"] .goal-bar-state{color:var(--amber)}
109319
+ .goal-bar-objective{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
109320
+ .goal-bar-meta{flex:0 0 auto;color:var(--muted);font-variant-numeric:tabular-nums;white-space:nowrap}
109321
+ .goal-bar-actions{flex:0 0 auto;display:flex;gap:4px}
109322
+ .goal-bar-btn{font:inherit;font-size:12px;padding:2px 8px;border-radius:6px;border:1px solid var(--line);background:var(--surface);color:var(--fg-2);cursor:pointer}
109323
+ .goal-bar-btn:hover{border-color:var(--line-strong);color:var(--fg)}
109324
+ .goal-bar-reason{margin-top:4px;padding-left:20px;color:var(--muted);overflow:hidden;text-overflow:ellipsis;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical}
109325
+ .goal-bar-reason b{color:var(--fg-2);font-weight:600}
109326
+ .msg-event-card-runtime.success{--tone:var(--ok);border-left:3px solid var(--ok)}
109327
+ .msg-goal-card .msg-event-note.mono{font-family:var(--mono,ui-monospace,monospace);font-size:12px}
109328
+ @media (max-width:640px){.goal-bar-meta{display:none}}
109329
+ .ic-goal{--ic:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='1.9' stroke-linecap='round' stroke-linejoin='round'%3E%3Ccircle cx='12' cy='12' r='8.5'/%3E%3Ccircle cx='12' cy='12' r='4.5'/%3E%3Ccircle cx='12' cy='12' r='.8' fill='black'/%3E%3C/svg%3E")}
109330
+ .goal-dropdown[hidden]{display:none!important}
109331
+ #goalMenuBtn.is-on{background:var(--teal-soft);color:var(--teal)}
109332
+ #goalMenuBtn[data-goal-status="paused"]{background:var(--amber-soft);color:var(--amber)}
109333
+ .popup-menu.goal-menu{width:min(360px,calc(100vw - 24px));padding:8px 10px;font-size:12.5px;color:var(--fg-2)}
109334
+ .goal-menu-sec{padding:4px 0 8px;border-bottom:1px solid var(--line)}
109335
+ .goal-menu-sec+.goal-menu-sec{padding-top:8px}
109336
+ .goal-menu-status{display:flex;align-items:center;gap:6px;min-width:0}
109337
+ .goal-menu-status b{color:var(--fg);font-weight:600;white-space:nowrap}
109338
+ .goal-menu-meta{margin-left:auto;color:var(--muted);font-size:11.5px;white-space:nowrap;font-variant-numeric:tabular-nums}
109339
+ .goal-menu-objective{margin:4px 0 6px 18px;color:var(--fg-2);overflow:hidden;display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;word-break:break-word}
109340
+ .goal-menu-actions{display:flex;gap:4px;margin-left:18px}
109341
+ .goal-menu-empty{color:var(--muted)}
109342
+ .goal-menu-h{font-weight:600;color:var(--fg);margin-bottom:6px}
109343
+ .goal-menu-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:6px}
109344
+ .goal-menu-grid label{display:flex;flex-direction:column;gap:3px;font-size:11.5px;color:var(--muted)}
109345
+ .goal-menu-grid input{box-sizing:border-box;width:100%;height:28px;padding:0 7px;border:1px solid var(--line);border-radius:6px;background:var(--surface);color:var(--fg);font:inherit;font-size:12.5px;font-variant-numeric:tabular-nums}
109346
+ .goal-menu-grid input:focus{outline:none;border-color:var(--teal)}
109347
+ .goal-menu-note{margin-top:6px;color:var(--muted);font-size:11.5px;line-height:1.45}
109348
+ .goal-menu-check{display:flex;align-items:flex-start;gap:7px;padding:8px 0 2px;cursor:pointer;color:var(--fg-2)}
109349
+ .goal-menu-check input{margin:2px 0 0;flex:0 0 auto}
109350
+ .goal-menu-foot{min-height:14px;font-size:11.5px;color:var(--muted)}
109351
+ .goal-menu-foot.ok{color:var(--ok)}.goal-menu-foot.bad{color:var(--danger,#d4453c)}
109352
+ """
109353
+
107729
109354
  APP_CSS += r"""
107730
109355
  .model-picker{display:inline-flex;align-items:center;gap:2px;max-width:min(36vw,380px);height:32px}.model-picker select{box-sizing:border-box;min-width:150px;max-width:min(22vw,230px);height:30px;min-height:30px;padding:0 28px 0 10px;line-height:1.2;border:0;border-radius:var(--r-sm) 0 0 var(--r-sm);appearance:none;-webkit-appearance:none;background:transparent url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath d='M3.5 4.75L6 2.25l2.5 2.5M3.5 7.25L6 9.75l2.5-2.5' fill='none' stroke='%238a93a3' stroke-width='1.4' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E") no-repeat right 9px center;font-size:12.5px;font-weight:550;color:var(--fg)}.model-picker select:focus-visible{box-shadow:none}.model-picker:focus-within{border-color:var(--brand-line);box-shadow:var(--ring)}.model-picker .hidden{display:none}.model-picker button{box-sizing:border-box;flex:0 0 auto;width:28px;height:28px;min-width:28px;min-height:28px;padding:0;display:inline-flex;align-items:center;justify-content:center;line-height:1;border:0;border-radius:var(--r-xs);background:transparent;color:var(--muted)}.model-picker button:hover{background:var(--hover);color:var(--fg)}.model-picker #modelManageBtn{font-size:17px!important;font-weight:500;line-height:1}
107731
109356
  .model-setting-row{display:flex;align-items:center;justify-content:space-between;gap:10px;padding:6px 10px;font-size:12.5px;color:var(--fg)}.model-setting-row select{min-width:130px;height:28px;padding:0 24px 0 8px;border:1px solid var(--line);border-radius:var(--r-xs);background-color:var(--surface)}.model-setting-check{display:flex;align-items:center;gap:8px;padding:5px 10px;font-size:12.5px}.model-setting-check input{accent-color:var(--brand)}
@@ -107791,17 +109416,18 @@ SKILLS_INDEX_HTML = """<!doctype html>
107791
109416
  <meta charset="utf-8">
107792
109417
  <meta name="viewport" content="width=device-width, initial-scale=1">
107793
109418
  <title>Fona Skills Studio</title>
109419
+ <!--cc-favicon:skills-studio-->
107794
109420
  <link rel="stylesheet" href="/assets/style.css">
107795
109421
  </head>
107796
109422
  <body>
107797
109423
  <div class="bg-layer"></div>
107798
109424
  <div class="app skills-app">
107799
109425
  <header>
107800
- <div>
109426
+ <div class="cc-brand-row"><!--cc-logo:skills-studio:header:40--><div>
107801
109427
  <h1>Fona Skills Studio</h1>
107802
109428
  <p>基于现有 WebUI 风格的图形化 Skills 制作平台</p>
107803
109429
  <p>Flowchart → LLM 解析 → SKILL.md 注入 ./skills</p>
107804
- </div>
109430
+ </div></div>
107805
109431
  <div class="actions">
107806
109432
  <select id="skillsLangSelect"></select>
107807
109433
  <select id="modelSelect"></select>
@@ -107940,8 +109566,10 @@ SKILLS_INDEX_HTML = """<!doctype html>
107940
109566
  </body>
107941
109567
  </html>
107942
109568
  """
109569
+ SKILLS_INDEX_HTML = embed_service_logos(SKILLS_INDEX_HTML)
107943
109570
 
107944
109571
  SKILLS_EXTRA_CSS = """
109572
+ header .cc-brand-row>.cc-service-logo{display:block;margin:0 0 10px;border-radius:11px}
107945
109573
  .skills-main{display:grid;grid-template-columns:minmax(280px,330px) minmax(560px,1fr) minmax(390px,500px);gap:12px;height:78vh;min-height:680px;max-height:78vh;align-items:stretch}
107946
109574
  .skills-app .panel{min-height:0;overflow:hidden}
107947
109575
  .skills-panel-left,.skills-panel-center,.skills-panel-right{display:flex;flex-direction:column;gap:8px;min-height:0}
@@ -108193,6 +109821,7 @@ ADMIN_INDEX_HTML = """<!doctype html>
108193
109821
  <meta charset="utf-8">
108194
109822
  <meta name="viewport" content="width=device-width,initial-scale=1">
108195
109823
  <title>Clouds Coder Admin</title>
109824
+ <!--cc-favicon:admin-->
108196
109825
  <link rel="stylesheet" href="/assets/admin.css">
108197
109826
  </head>
108198
109827
  <body>
@@ -108200,7 +109829,7 @@ ADMIN_INDEX_HTML = """<!doctype html>
108200
109829
  <header class="admin-header">
108201
109830
  <div>
108202
109831
  <div class="eyebrow">CONTROL PLANE</div>
108203
- <h1>Clouds Coder Admin</h1>
109832
+ <h1><!--cc-logo:admin:header:38-->Clouds Coder Admin</h1>
108204
109833
  <p>启动参数、运行统计与共享应用治理</p>
108205
109834
  </div>
108206
109835
  <div class="header-actions">
@@ -108513,6 +110142,7 @@ ADMIN_INDEX_HTML = """<!doctype html>
108513
110142
  </body>
108514
110143
  </html>
108515
110144
  """
110145
+ ADMIN_INDEX_HTML = embed_service_logos(ADMIN_INDEX_HTML)
108516
110146
 
108517
110147
  ADMIN_CSS = """
108518
110148
  :root{--bg:#f3f6fb;--surface:#fff;--surface2:#f7f9fc;--text:#172033;--muted:#667085;--line:#dce3ee;--brand:#2563eb;--brand2:#0f9f8f;--danger:#b42318;--warn:#b54708;--shadow:0 18px 44px rgba(27,39,71,.09)}
@@ -108533,6 +110163,7 @@ code{background:#eef2f7;padding:2px 5px;border-radius:5px}
108533
110163
  .admin-shell{max-width:1500px;margin:0 auto;padding:24px}
108534
110164
  .admin-header{display:flex;align-items:flex-start;justify-content:space-between;gap:24px;margin-bottom:18px}
108535
110165
  .admin-header h1{margin:4px 0 4px;font-size:2rem;letter-spacing:-.035em}
110166
+ .admin-header h1{display:flex;align-items:center;gap:12px}
108536
110167
  .admin-header p,.section-head p{margin:0;color:var(--muted)}
108537
110168
  .eyebrow{color:var(--brand);font-size:.72rem;font-weight:800;letter-spacing:.18em}
108538
110169
  .header-actions,.inline-actions,.action-bar{display:flex;align-items:center;gap:9px;flex-wrap:wrap}
@@ -108910,7 +110541,7 @@ const ADMIN_I18N_ROWS=[
108910
110541
  const ADMIN_CONFIG_I18N_ROWS=[
108911
110542
  ['network','网络','網路','ネットワーク','Network'],['runtime','运行时','執行階段','ランタイム','Runtime'],['evolution','演进','演進','進化','Evolution'],['live_input','实时输入','即時輸入','ライブ入力','Live Input'],['paths','路径','路徑','パス','Paths'],['services','服务','服務','サービス','Services'],['security','安全','安全性','セキュリティ','Security'],['webui','WebUI','WebUI','WebUI','WebUI'],['limits','限制','限制','制限','Limits'],['model','模型','模型','モデル','Model'],['arbiter','仲裁器','仲裁器','アービター','Arbiter'],
108912
110543
  ['Bind host','绑定主机','繫結主機','バインドホスト','Bind host'],['Agent port','Agent 端口','Agent 連接埠','Agent ポート','Agent port'],['Skills Studio port','Skills Studio 端口','Skills Studio 連接埠','Skills Studio ポート','Skills Studio port'],['RAG admin port','RAG 管理端口','RAG 管理連接埠','RAG 管理ポート','RAG admin port'],['Code admin port','代码管理端口','程式碼管理連接埠','コード管理ポート','Code admin port'],['MCP service port','MCP 服务端口','MCP 服務連接埠','MCP サービスポート','MCP service port'],['IDE port','IDE 端口','IDE 連接埠','IDE ポート','IDE port'],['Collaboration bind host','协作绑定主机','協作繫結主機','コラボレーションのバインドホスト','Collaboration bind host'],['Collaboration port','协作端口','協作連接埠','コラボレーションポート','Collaboration port'],
108913
- ['Context token limit','上下文 Token 限制','上下文 Token 限制','コンテキスト Token 上限','Context token limit'],['Maximum agent rounds','Agent 最大轮数','Agent 最大輪數','Agent 最大ラウンド数','Maximum agent rounds'],['Run timeout (seconds)','运行超时(秒)','執行逾時(秒)','実行タイムアウト(秒)','Run timeout (seconds)'],['Shell timeout (seconds)','Shell 超时(秒)','Shell 逾時(秒)','Shell タイムアウト(秒)','Shell timeout (seconds)'],['Shell timeout mode','Shell 超时模式','Shell 逾時模式','Shell タイムアウトモード','Shell timeout mode'],['Shell async handoff (seconds)','Shell 异步移交(秒)','Shell 非同步移交(秒)','Shell 非同期引き継ぎ(秒)','Shell async handoff (seconds)'],
110544
+ ['Context token limit','上下文 Token 限制','上下文 Token 限制','コンテキスト Token 上限','Context token limit'],['Maximum agent rounds','Agent 最大轮数','Agent 最大輪數','Agent 最大ラウンド数','Maximum agent rounds'],['Default goal turns','目标默认轮数','目標預設輪數','ゴールの既定ターン数','Default goal turns'],['Run timeout (seconds)','运行超时(秒)','執行逾時(秒)','実行タイムアウト(秒)','Run timeout (seconds)'],['Shell timeout (seconds)','Shell 超时(秒)','Shell 逾時(秒)','Shell タイムアウト(秒)','Shell timeout (seconds)'],['Shell timeout mode','Shell 超时模式','Shell 逾時模式','Shell タイムアウトモード','Shell timeout mode'],['Shell async handoff (seconds)','Shell 异步移交(秒)','Shell 非同步移交(秒)','Shell 非同期引き継ぎ(秒)','Shell async handoff (seconds)'],
108914
110545
  ['Liquid kernel mode','液态内核模式','液態核心模式','Liquid Kernel モード','Liquid kernel mode'],['Evolution schedule','演进周期','演進週期','進化スケジュール','Evolution schedule'],['Liquid kernel restart policy','液态内核重启策略','液態核心重新啟動策略','Liquid Kernel 再起動ポリシー','Liquid kernel restart policy'],
108915
110546
  ['Skills root','Skills 根目录','Skills 根目錄','Skills ルート','Skills root'],['WebUI config JSON','WebUI 配置 JSON','WebUI 設定 JSON','WebUI 設定 JSON','WebUI config JSON'],['External WebUI directory','外部 WebUI 目录','外部 WebUI 目錄','外部 WebUI ディレクトリ','External WebUI directory'],['LLM config file or URL','LLM 配置文件或 URL','LLM 設定檔或 URL','LLM 設定ファイルまたは URL','LLM config file or URL'],
108916
110547
  ['Skills Studio','Skills Studio','Skills Studio','Skills Studio','Skills Studio'],['RAG admin','RAG 管理服务','RAG 管理服務','RAG 管理','RAG admin'],['Code library admin','代码库管理服务','程式碼庫管理服務','コードライブラリ管理','Code library admin'],['Programming IDE','编程 IDE','程式設計 IDE','プログラミング IDE','Programming IDE'],['IDE password login','IDE 密码登录','IDE 密碼登入','IDE パスワードログイン','IDE password login'],['MCP service','MCP 服务','MCP 服務','MCP サービス','MCP service'],['LAN collaboration','LAN 协作','LAN 協作','LAN コラボレーション','LAN collaboration'],
@@ -122226,6 +123857,7 @@ RAG_ADMIN_INDEX_HTML = """<!doctype html>
122226
123857
  <meta charset="utf-8">
122227
123858
  <meta name="viewport" content="width=device-width, initial-scale=1">
122228
123859
  <title>Clouds Coder RAG Admin</title>
123860
+ <!--cc-favicon:rag-admin-->
122229
123861
  <link rel="stylesheet" href="/assets/style.css">
122230
123862
  <script defer src="/assets/rag-admin.js"></script>
122231
123863
  </head>
@@ -122285,7 +123917,7 @@ RAG_ADMIN_INDEX_HTML = """<!doctype html>
122285
123917
  <header class="rag-hero">
122286
123918
  <div>
122287
123919
  <p class="eyebrow">Clouds Coder</p>
122288
- <h1>TF-Graph_IDF RAG Admin</h1>
123920
+ <h1><!--cc-logo:rag-admin:header:40-->TF-Graph_IDF RAG Admin</h1>
122289
123921
  <p class="subtitle">Global knowledge library, graph view, batch import, backup, and retrieval control.</p>
122290
123922
  </div>
122291
123923
  <div class="hero-actions">
@@ -122476,6 +124108,7 @@ body{min-height:100vh}
122476
124108
  .rag-hero{display:flex;justify-content:space-between;gap:18px;align-items:flex-start;margin-bottom:18px;padding:24px;border:1px solid rgba(23,49,34,.08);border-radius:28px;background:linear-gradient(135deg,rgba(255,255,255,.92),rgba(236,244,229,.88));box-shadow:var(--shadow)}
122477
124109
  .eyebrow{margin:0 0 6px;font-size:12px;letter-spacing:.18em;text-transform:uppercase;color:var(--accent)}
122478
124110
  .rag-hero h1{margin:0;font-size:34px;line-height:1.05}
124111
+ .rag-hero h1{display:flex;align-items:center;gap:14px}
122479
124112
  .subtitle{margin:10px 0 0;max-width:760px;color:var(--muted)}
122480
124113
  .hero-actions{display:flex;gap:10px;flex-wrap:wrap}
122481
124114
  .auth-overlay{position:fixed;inset:0;z-index:100;display:flex;align-items:center;justify-content:center;padding:18px;background:rgba(13,31,21,.72);backdrop-filter:blur(8px)}
@@ -124797,6 +126430,8 @@ window.addEventListener('DOMContentLoaded',async()=>{
124797
126430
 
124798
126431
  CODE_ADMIN_INDEX_HTML = (
124799
126432
  RAG_ADMIN_INDEX_HTML
126433
+ .replace("<!--cc-favicon:rag-admin-->", "<!--cc-favicon:code-admin-->")
126434
+ .replace("<!--cc-logo:rag-admin:", "<!--cc-logo:code-admin:")
124800
126435
  .replace("Clouds Coder RAG Admin", "Clouds Coder Code Library Admin")
124801
126436
  .replace("/assets/rag-admin.js", "/assets/code-admin.js")
124802
126437
  .replace("TF-Graph_IDF RAG Admin", "Code Graph Library Admin")
@@ -124807,6 +126442,9 @@ CODE_ADMIN_INDEX_HTML = (
124807
126442
  "Independent code library, repository graph view, batch import, backup, and developer retrieval control.",
124808
126443
  )
124809
126444
  )
126445
+ RAG_ADMIN_INDEX_HTML = embed_service_logos(RAG_ADMIN_INDEX_HTML)
126446
+ CODE_ADMIN_INDEX_HTML = embed_service_logos(CODE_ADMIN_INDEX_HTML)
126447
+
124810
126448
  CODE_ADMIN_CSS = (
124811
126449
  RAG_ADMIN_CSS
124812
126450
  + """
@@ -124850,6 +126488,7 @@ IDE_INDEX_HTML = """<!doctype html>
124850
126488
  <meta charset="utf-8">
124851
126489
  <meta name="viewport" content="width=device-width, initial-scale=1">
124852
126490
  <title>Clouds Coder IDE</title>
126491
+ <!--cc-favicon:ide-->
124853
126492
  <link rel="stylesheet" href="/assets/js_lib/codicons/dist/codicon.css">
124854
126493
  <link rel="stylesheet" href="/assets/js_lib/xterm/css/xterm.css">
124855
126494
  <link rel="stylesheet" href="/assets/ide.css">
@@ -124857,7 +126496,7 @@ IDE_INDEX_HTML = """<!doctype html>
124857
126496
  <body class="icons-fallback">
124858
126497
  <div id="authGate" class="auth-gate">
124859
126498
  <section class="auth-dialog" aria-labelledby="authTitle">
124860
- <div class="auth-mark"><span class="codicon codicon-code"></span></div>
126499
+ <div class="auth-mark"><!--cc-logo:ide:auth:44--></div>
124861
126500
  <h1 id="authTitle">Clouds Coder</h1>
124862
126501
  <p id="authSubtitle">Sign in to Program</p>
124863
126502
  <div id="collabTransportWarning" class="collab-transport-warning is-hidden" role="status"></div>
@@ -124882,7 +126521,7 @@ IDE_INDEX_HTML = """<!doctype html>
124882
126521
  <div id="ideShell" class="ide-shell is-hidden">
124883
126522
  <header class="title-bar">
124884
126523
  <button id="mainMenuBtn" class="icon-button" title="Application menu" aria-label="Application menu"><span class="codicon codicon-menu"></span></button>
124885
- <div class="product-mark"><span class="codicon codicon-code"></span></div>
126524
+ <div class="product-mark"><!--cc-logo:ide:title:20--></div>
124886
126525
  <nav id="menuBar" class="menu-bar" aria-label="Main menu">
124887
126526
  <button data-menu="file">File</button><button data-menu="edit">Edit</button><button data-menu="selection">Selection</button><button data-menu="view">View</button><button data-menu="go">Go</button><button data-menu="run">Run</button><button data-menu="terminal">Terminal</button><button data-menu="help">Help</button>
124888
126527
  </nav>
@@ -124985,7 +126624,7 @@ IDE_INDEX_HTML = """<!doctype html>
124985
126624
  <div id="agentContext" class="agent-context"></div>
124986
126625
  <section id="agentTodoPanel" class="agent-todo is-hidden"><button id="agentTodoToggle" class="agent-todo-header" type="button" aria-expanded="true"><span class="codicon codicon-chevron-down"></span><strong>Progress</strong><span id="agentTodoCount" class="agent-todo-count"></span></button><div id="agentTodoBody" class="agent-todo-body"></div></section>
124987
126626
  <div id="agentMessages" class="agent-messages"></div>
124988
- <div class="agent-composer" id="agentComposer"><section id="agentAskUser" class="agent-ask-user is-hidden" aria-live="polite"><div class="agent-ask-user-head"><span class="codicon codicon-question"></span><strong>Input required</strong><span id="agentAskUserRole"></span></div><div id="agentAskUserQuestion" class="agent-ask-user-question"></div><div id="agentAskUserOptions" class="agent-ask-user-options"></div><div id="agentAskUserHint" class="agent-ask-user-hint"></div></section><div id="agentAttachments" class="agent-attachments is-hidden"></div><div id="agentDropHint" class="agent-drop-hint is-hidden">Drop files to attach</div><textarea id="agentPrompt" rows="4" placeholder="Ask Clouds Coder"></textarea><input id="agentAttachmentInput" type="file" multiple hidden><div class="agent-actions"><button id="attachContextBtn" class="icon-button" title="Attach files"><span class="codicon codicon-attach"></span></button><button id="promptEnhanceBtn" class="icon-button agent-enhance-button" title="Enhance prompt before sending: Off · Medium" aria-label="Enhance prompt before sending. Long press to choose strength." aria-pressed="false"><span class="codicon codicon-lightbulb"></span><small id="promptEnhanceBudget">M</small></button><button id="agentModelBtn" class="icon-button agent-model-button" title="Choose model"><span class="codicon codicon-hubot"></span><small id="agentContextPercent"></small></button><span id="agentStatus"></span><button id="stopAgentBtn" class="icon-button agent-stop-button is-hidden" title="Stop Agent" aria-label="Stop Agent"><span class="codicon codicon-debug-stop"></span></button><button id="sendAgentBtn" class="icon-button primary" title="Send"><span class="codicon codicon-send"></span></button></div></div>
126627
+ <div class="agent-composer" id="agentComposer"><section id="agentGoalBar" class="agent-goal is-hidden" aria-live="polite"></section><section id="agentAskUser" class="agent-ask-user is-hidden" aria-live="polite"><div class="agent-ask-user-head"><span class="codicon codicon-question"></span><strong>Input required</strong><span id="agentAskUserRole"></span></div><div id="agentAskUserQuestion" class="agent-ask-user-question"></div><div id="agentAskUserOptions" class="agent-ask-user-options"></div><div id="agentAskUserHint" class="agent-ask-user-hint"></div></section><div id="agentAttachments" class="agent-attachments is-hidden"></div><div id="agentDropHint" class="agent-drop-hint is-hidden">Drop files to attach</div><textarea id="agentPrompt" rows="4" placeholder="Ask Clouds Coder"></textarea><input id="agentAttachmentInput" type="file" multiple hidden><div class="agent-actions"><button id="attachContextBtn" class="icon-button" title="Attach files"><span class="codicon codicon-attach"></span></button><button id="promptEnhanceBtn" class="icon-button agent-enhance-button" title="Enhance prompt before sending: Off · Medium" aria-label="Enhance prompt before sending. Long press to choose strength." aria-pressed="false"><span class="codicon codicon-lightbulb"></span><small id="promptEnhanceBudget">M</small></button><button id="agentModelBtn" class="icon-button agent-model-button" title="Choose model"><span class="codicon codicon-hubot"></span><small id="agentContextPercent"></small></button><span id="agentStatus"></span><button id="stopAgentBtn" class="icon-button agent-stop-button is-hidden" title="Stop Agent" aria-label="Stop Agent"><span class="codicon codicon-debug-stop"></span></button><button id="sendAgentBtn" class="icon-button primary" title="Send"><span class="codicon codicon-send"></span></button></div></div>
124989
126628
  </aside>
124990
126629
  </div>
124991
126630
  <footer class="status-bar"><div class="status-left"><button id="remoteStatus" title="Local window"><span class="codicon codicon-remote"></span></button><button id="gitStatus"><span class="codicon codicon-git-branch"></span><span id="statusBranch">-</span></button><button id="syncStatus"><span class="codicon codicon-sync"></span></button><button id="errorStatus"><span class="codicon codicon-error"></span><span id="errorCount">0</span><span class="codicon codicon-warning"></span><span id="warningCount">0</span></button></div><div id="statusMessage" class="status-message">Ready</div><div class="status-right"><button id="fileSizeStatus" title="File size">0 B</button><button id="languageStatus">Plain Text</button><button id="encodingStatus">UTF-8</button><button id="eolStatus">LF</button><button id="indentStatus">Spaces: 2</button><button id="accountStatus"><span class="codicon codicon-account"></span><span id="accountName"></span></button><button id="notificationsBtn" title="Notifications"><span class="codicon codicon-bell"></span></button></div></footer>
@@ -124999,6 +126638,7 @@ IDE_INDEX_HTML = """<!doctype html>
124999
126638
  </body>
125000
126639
  </html>
125001
126640
  """
126641
+ IDE_INDEX_HTML = embed_service_logos(IDE_INDEX_HTML)
125002
126642
 
125003
126643
  IDE_CSS = """
125004
126644
  .icons-fallback .codicon::before{display:inline-block;min-width:1em;font-family:"Segoe UI Symbol","Apple Symbols",Arial,sans-serif!important;font-style:normal;font-weight:400;line-height:1;text-align:center;content:"□"!important}
@@ -125014,7 +126654,8 @@ button{color:inherit}.is-hidden{display:none!important}
125014
126654
  .icon-button{display:inline-grid;place-items:center;width:28px;height:28px;padding:0;border:0;background:transparent;color:var(--ink);border-radius:4px;cursor:pointer}.icon-button:hover{background:var(--hover);color:var(--bright)}.icon-button.primary{background:var(--accent);color:white}.icon-button:disabled{opacity:.4;cursor:default}
125015
126655
  .button{display:inline-flex;align-items:center;justify-content:center;gap:7px;min-height:28px;padding:4px 12px;border:1px solid transparent;border-radius:2px;background:#3a3d41;color:var(--bright);cursor:pointer}.button:hover{background:#45494e}.button.primary{background:var(--accent);color:#fff}.button.primary:hover{background:#026ec1}.button:disabled{opacity:.45;cursor:not-allowed}
125016
126656
  input,select,textarea{border:1px solid transparent;border-radius:2px;background:var(--input);color:var(--bright);outline:none}input:focus,select:focus,textarea:focus{border-color:var(--focus)}input::placeholder,textarea::placeholder{color:#a0a0a0}select{height:25px;padding:0 6px}
125017
- .auth-gate{position:fixed;inset:0;z-index:1000;display:grid;place-items:center;background:#181818}.auth-dialog{width:min(360px,calc(100vw - 32px));padding:36px 34px 32px;border:1px solid var(--line-light);background:#202020;box-shadow:0 18px 58px rgba(0,0,0,.42)}.auth-mark{display:grid;place-items:center;width:44px;height:44px;margin:0 auto 16px;background:#007acc;color:white}.auth-mark .codicon{font-size:28px}.auth-dialog h1{margin:0;text-align:center;color:var(--bright);font-size:22px;font-weight:500}.auth-dialog p{margin:7px 0 24px;text-align:center;color:var(--muted)}.auth-dialog form{display:grid;gap:7px}.auth-dialog label{margin-top:5px;font-size:12px}.auth-dialog input{height:32px;padding:5px 8px}.auth-dialog .button{margin-top:12px;height:32px}.auth-message{min-height:18px;margin-top:14px;color:var(--danger);font-size:12px;line-height:1.45}
126657
+ .auth-gate{position:fixed;inset:0;z-index:1000;display:grid;place-items:center;background:#181818}.auth-dialog{width:min(360px,calc(100vw - 32px));padding:36px 34px 32px;border:1px solid var(--line-light);background:#202020;box-shadow:0 18px 58px rgba(0,0,0,.42)}.auth-mark{display:grid;place-items:center;width:44px;height:44px;margin:0 auto 16px}
126658
+ .auth-mark svg,.product-mark svg{display:block}.auth-mark .codicon{font-size:28px}.auth-dialog h1{margin:0;text-align:center;color:var(--bright);font-size:22px;font-weight:500}.auth-dialog p{margin:7px 0 24px;text-align:center;color:var(--muted)}.auth-dialog form{display:grid;gap:7px}.auth-dialog label{margin-top:5px;font-size:12px}.auth-dialog input{height:32px;padding:5px 8px}.auth-dialog .button{margin-top:12px;height:32px}.auth-message{min-height:18px;margin-top:14px;color:var(--danger);font-size:12px;line-height:1.45}
125018
126659
  .ide-shell{height:100vh;display:grid;grid-template-rows:var(--title-height) minmax(0,1fr) var(--status-height);overflow:hidden}.title-bar{display:grid;grid-template-columns:30px 26px auto minmax(220px,560px) 1fr;align-items:center;gap:2px;padding:0 7px;background:var(--title);border-bottom:1px solid #151515;user-select:none}.product-mark{display:grid;place-items:center;color:#23a8f2}.product-mark .codicon{font-size:20px}.menu-bar{display:flex;align-items:center;gap:0;min-width:0}.menu-bar button{height:27px;padding:0 7px;border:0;border-radius:4px;background:transparent;color:var(--ink);cursor:pointer}.menu-bar button:hover{background:var(--hover)}.command-center{justify-self:center;width:min(100%,460px);height:25px;display:flex;align-items:center;justify-content:center;gap:7px;border:1px solid #3c3c3c;border-radius:5px;background:#242424;color:#d4d4d4;cursor:pointer;box-shadow:inset 0 0 0 1px rgba(255,255,255,.02)}.command-center:hover{background:#2a2a2a;border-color:#555}.layout-controls{justify-self:end;display:flex;align-items:center;gap:1px}
125019
126660
  .workbench-grid{min-height:0;display:grid;grid-template-columns:var(--activity-width) var(--sidebar-width) minmax(260px,1fr) var(--secondary-width);background:var(--editor)}.ide-shell.primary-hidden .workbench-grid{grid-template-columns:var(--activity-width) 0 minmax(260px,1fr) var(--secondary-width)}.ide-shell.secondary-hidden .workbench-grid{grid-template-columns:var(--activity-width) var(--sidebar-width) minmax(260px,1fr) 0}.ide-shell.primary-hidden.secondary-hidden .workbench-grid{grid-template-columns:var(--activity-width) 0 minmax(260px,1fr) 0}
125020
126661
  .activity-bar{min-width:0;display:flex;flex-direction:column;justify-content:space-between;background:var(--activity);border-right:1px solid var(--line);user-select:none}.activity-top,.activity-bottom{display:flex;flex-direction:column;align-items:stretch}.activity-button{position:relative;display:grid;place-items:center;width:47px;height:48px;padding:0;border:0;border-left:2px solid transparent;background:transparent;color:#858585;cursor:pointer}.activity-button .codicon{font-size:24px}.activity-button:hover{color:#d7d7d7}.activity-button.is-active{border-left-color:#fff;color:#fff}.activity-badge{position:absolute;right:5px;bottom:4px;min-width:16px;height:16px;padding:0 4px;border-radius:8px;background:#007acc;color:#fff;font:10px/16px sans-serif;text-align:center}.activity-badge:empty{display:none}
@@ -125675,7 +127316,7 @@ function renderAgentMarkdown(text){const source=String(text||'');if(!window.mark
125675
127316
  const AGENT_MESSAGES_DOM_LIMIT=360,AGENT_RENDERED_KEY_LIMIT=720,AGENT_MARKDOWN_COLLAPSE_CHARS=12000;
125676
127317
  function rememberAgentRendered(key){if(!key)return false;if(S.agentRendered.has(key))return false;S.agentRendered.add(key);while(S.agentRendered.size>AGENT_RENDERED_KEY_LIMIT){const oldest=S.agentRendered.values().next().value;S.agentRendered.delete(oldest)}return true}
125677
127318
  function agentMessagesNearBottom(host=E('agentMessages')){return !!host&&(host.scrollHeight-host.scrollTop-host.clientHeight<96)}
125678
- function trimAgentMessages(host=E('agentMessages')){if(!host)return;const rows=[...host.children].filter(row=>!row.classList.contains('agent-history-truncated')&&row.id!=='agentLiveResponse');if(rows.length<=AGENT_MESSAGES_DOM_LIMIT)return;const follow=agentMessagesNearBottom(host),oldHeight=host.scrollHeight,removeCount=rows.length-AGENT_MESSAGES_DOM_LIMIT;for(let i=0;i<removeCount;i++)rows[i]?.remove();let marker=host.querySelector('.agent-history-truncated');if(!marker){marker=document.createElement('div');marker.className='agent-history-truncated';marker.textContent='Earlier activity omitted from this view.';host.prepend(marker)}const delta=host.scrollHeight-oldHeight;if(follow)host.scrollTop=host.scrollHeight;else host.scrollTop=Math.max(0,host.scrollTop+delta);for(const[key,value]of S.agentToolCards)if(!value?.isConnected)S.agentToolCards.delete(key);for(const[key,value]of S.agentPlanCards)if(!value?.isConnected)S.agentPlanCards.delete(key)}
127319
+ function trimAgentMessages(host=E('agentMessages')){if(!host)return;const rows=[...host.children].filter(row=>!row.classList.contains('agent-history-truncated')&&row.id!=='agentLiveResponse');if(rows.length<=AGENT_MESSAGES_DOM_LIMIT)return;const follow=agentMessagesNearBottom(host),oldHeight=host.scrollHeight,removeCount=rows.length-AGENT_MESSAGES_DOM_LIMIT;/* The user's own messages go last, so the history keeps them after long tool runs. */const others=rows.filter(row=>row.dataset.userInput!=='1'),users=rows.filter(row=>row.dataset.userInput==='1');for(let i=0;i<Math.min(removeCount,others.length);i++)others[i].remove();for(let i=0;i<removeCount-others.length;i++)users[i]?.remove();let marker=host.querySelector('.agent-history-truncated');if(!marker){marker=document.createElement('div');marker.className='agent-history-truncated';marker.textContent='Earlier activity omitted from this view.';host.prepend(marker)}const delta=host.scrollHeight-oldHeight;if(follow)host.scrollTop=host.scrollHeight;else host.scrollTop=Math.max(0,host.scrollTop+delta);for(const[key,value]of S.agentToolCards)if(!value?.isConnected)S.agentToolCards.delete(key);for(const[key,value]of S.agentPlanCards)if(!value?.isConnected)S.agentPlanCards.delete(key)}
125679
127320
  function appendAgentNode(row){const host=E('agentMessages');if(!host||!row)return row;host.appendChild(row);if(!S.agentBatching)trimAgentMessages(host);return row}
125680
127321
  function finishAgentMessagesRender(follow=false){const host=E('agentMessages');if(!host)return;if(follow)host.scrollTop=host.scrollHeight;trimAgentMessages(host);if(follow)host.scrollTop=host.scrollHeight}
125681
127322
  function agentMessage(text,type='system',meta=''){const row=document.createElement('div');row.className=`agent-message ${type}`;if(meta){const key=agentRoleKey(meta),label=document.createElement('span');label.className=`agent-meta${key?` agent-role-${key}`:''}`;label.textContent=agentRoleLabel(meta);row.appendChild(label)}const value=stripAgentRolePrefix(text,meta);if(type==='assistant'){const body=document.createElement('div');body.className='agent-markdown';const collapsed=value.length>AGENT_MARKDOWN_COLLAPSE_CHARS,initial=collapsed?value.slice(0,AGENT_MARKDOWN_COLLAPSE_CHARS):value;body.innerHTML=renderAgentMarkdown(initial);body.dataset.source=value;row.appendChild(body);if(collapsed){const expand=document.createElement('button');expand.className='button agent-expand-long';expand.textContent='Show full response';expand.onclick=()=>{body.innerHTML=renderAgentMarkdown(value);expand.remove()};row.appendChild(expand)}}else row.appendChild(document.createTextNode(value));return appendAgentNode(row)}
@@ -125686,6 +127327,9 @@ function updateAgentContext(){const file=activeFile();E('agentContext').textCont
125686
127327
  function applyIdeSessionTitleEvent(data={},evt={}){const payload=data&&typeof data==='object'?data:{},sid=String(payload.session_id||evt.session_id||S.activeSession||'').trim();if(!sid)return false;const title=String(payload.session_title||'').trim(),rev=Number(payload.title_revision||0);let target=S.sessions.find(row=>String(row?.id||'')===sid);if(!target&&String(S.activeSession||'')===sid)target=S.activeSessionRow;if(!target)return false;const workspaceId=String(payload.workspace_id||target.workspace_id||'').trim();let changed=false;if(title&&rev>=Number(target.title_revision||0)&&(target.title!==title||target.title_origin!==payload.title_origin)){target.title=title;target.title_origin=payload.title_origin||target.title_origin;target.title_revision=rev;changed=true}if(String(S.activeSession||'')===sid)S.activeSessionRow={...(S.activeSessionRow||{}),...target};if(workspaceId){for(const row of S.sessions){if(String(row?.workspace_id||'').trim()!==workspaceId)continue;if(payload.workspace_name&&row.workspace_name!==payload.workspace_name){row.workspace_name=String(payload.workspace_name);changed=true}if(payload.workspace_created_at!=null&&Number(row.workspace_created_at||0)!==Number(payload.workspace_created_at||0)){row.workspace_created_at=Number(payload.workspace_created_at||0);changed=true}if(payload.workspace_label&&row.workspace_label!==payload.workspace_label){row.workspace_label=String(payload.workspace_label);changed=true}}}if(changed){clearTimeout(S.sessionTitleRenderTimer);S.sessionTitleRenderTimer=setTimeout(()=>{S.sessionTitleRenderTimer=0;renderSessions();updateAgentContext()},0)}return changed}
125687
127328
  function agentEventKey(row){
125688
127329
  if(!row)return'';
127330
+ // A user message and its retained copy (kept after compaction) carry
127331
+ // different ids but the same timestamp; render them once.
127332
+ if(row.role==='user'&&row.user_input&&Number(row.ts||0)>0)return`feed-user:${Math.round(Number(row.ts)*1000)}`;
125689
127333
  const id=String(row.id||'').trim(),seq=Number(row.seq||0);
125690
127334
  if(id)return`feed:${id}`;
125691
127335
  if(seq>0)return`feed-seq:${seq}`;
@@ -125769,7 +127413,7 @@ function renderAgentState(state){
125769
127413
  const detail=queued&&!running?`${state.scheduler_queued} queued`:[state.active_role,state.phase,state.active_tool].filter(Boolean).join(' / ');
125770
127414
  let submissionLabel='';if(running){S.agentSubmissionSeenRunning=true;S.agentSubmissionStatus='running';submissionLabel=detail||'Running'}else if(starting){S.agentSubmissionStatus='starting';S.agentSubmissionPendingUntil=Math.max(Number(S.agentSubmissionPendingUntil||0),Date.now()+15000);submissionLabel='Starting...'}else if(queued){S.agentSubmissionStatus='queued';S.agentSubmissionPendingUntil=Math.max(Number(S.agentSubmissionPendingUntil||0),Date.now()+30000);submissionLabel=detail||'Queued'}else if(S.agentSubmissionSeenRunning){S.agentSubmissionStatus='';S.agentSubmissionPendingUntil=0;S.agentSubmissionSeenRunning=false}else if(S.agentSubmissionStatus){submissionLabel=Date.now()<Number(S.agentSubmissionPendingUntil||0)?({submitting:'Submitting...',accepted:'Accepted · starting...',starting:'Starting...',queued:'Queued',failed:'Submit failed'}[S.agentSubmissionStatus]||'Checking...'):'Checking...'}
125771
127415
  if(S.agentSubmissionStatus==='failed'&&Date.now()>=Number(S.agentSubmissionPendingUntil||0)){S.agentSubmissionStatus='';submissionLabel=''}const agentStatusLabel=S.agentInterrupting?'Stopping...':(submissionLabel||(awaiting?'Awaiting input':'Idle'));E('agentStatus').textContent=agentStatusLabel;E('sendAgentBtn').disabled=S.agentSubmitting;E('stopAgentBtn').classList.toggle('is-hidden',!busy);E('stopAgentBtn').disabled=S.agentInterrupting;
125772
- renderAgentProgress(state);renderAgentContextHud(state);renderAgentAskUser(state);
127416
+ renderAgentProgress(state);renderAgentContextHud(state);renderAgentAskUser(state);renderAgentGoalBar(state);
125773
127417
  const feed=Array.isArray(state._delta_feed)?state._delta_feed:(Array.isArray(state.feed)?state.feed:[]),operations=Array.isArray(state._delta_operations)?state._delta_operations:(Array.isArray(state.operations)?state.operations:[]),timelineSignature=`${Number(state.snapshot_revision||0)}:${Number(state.feed_cursor||0)}:${Number(state.operation_cursor||0)}:${feed.length}:${operations.length}`,timelineChanged=timelineSignature!==S.agentTimelineSignature;
125774
127418
  S.agentBatching=true;
125775
127419
  try{
@@ -125784,9 +127428,9 @@ function renderAgentState(state){
125784
127428
  if(type==='tool_calls'){const tools=Array.isArray(row.data?.tools)?row.data.tools:[],progress=String(row.data?.public_progress||(!text.toLowerCase().startsWith('[tool calls]')?text:'')).trim();if(progress&&!isSyntheticPublicProgress(progress))agentApproach(progress,role);renderAgentPlanCard(tools.length?tools:[text||'Tool calls scheduled'],role);continue}
125785
127429
  if(type==='approach'){agentApproach(text,role);continue}
125786
127430
  if(type==='web_search'){agentToolCard({kind:'tool',name:'web_search',title:'Web search',state:'Completed',stateTone:'success',output:text,role});continue}
125787
- if(type==='runtime_hint'){renderAgentRuntimeHint(row);continue}
127431
+ if(type==='goal'){renderAgentGoalCard(row);continue}if(type==='slash_command'){renderAgentSlashCard(row);continue}if(type==='runtime_hint'){renderAgentRuntimeHint(row);continue}
125788
127432
  if(renderAgentControl(text,role))continue;
125789
- const tone=row.role==='assistant'?'assistant':row.role==='user'?'user':type==='error'?'error':'system';agentMessage(text,tone,role);continue;
127433
+ const tone=row.role==='assistant'?'assistant':row.role==='user'?'user':type==='error'?'error':'system',node=agentMessage(text,tone,role);if(row.user_input&&node)node.dataset.userInput='1';continue;
125790
127434
  }
125791
127435
  renderAgentOperationOnce(item.op);
125792
127436
  }
@@ -125840,7 +127484,7 @@ function promptExecutionGroup(rows){const values=(rows||[]).filter(row=>row&&row
125840
127484
  function promptSkillGroup(rows){const values=(rows||[]).filter(row=>row&&row.id);return values.length?`<div class="prompt-detail-group skills"><strong>Selected skills</strong>${values.map((row,index)=>`<div class="prompt-skill"><span class="prompt-step-index">${index+1}</span><span class="prompt-skill-content"><b>${escapeHtml(row.name||row.id)}</b><span>${escapeHtml(row.id)}</span>${row.rationale?`<small>${escapeHtml(row.rationale)}</small>`:''}</span></div>`).join('')}</div>`:''}
125841
127485
  function promptWorkspaceGroup(context){if(!context)return'';const summary=`${Number(context.entry_count||0).toLocaleString()} directory entries inspected${context.truncated?' (bounded snapshot)':''}${context.skipped_directories?` · ${context.skipped_directories} generated/heavy directories skipped`:''}`;return promptDetailGroup('Workspace awareness',[summary])}
125842
127486
  function renderPromptEnhancement(result){const draft=S.promptEnhanceDraft;if(!draft)return;E('promptEnhanceIntent').textContent=result.intent_summary||'The request was converted into an actionable Agent instruction.';E('promptEnhanceDetails').innerHTML=promptWorkspaceGroup(result.workspace_context)+promptSkillGroup(result.selected_skills)+promptExecutionGroup(result.execution_steps)+promptDetailGroup('Deliverables',result.deliverables)+promptDetailGroup('Constraints',result.constraints)+promptDetailGroup('Assumptions',result.assumptions)+promptDetailGroup('Acceptance criteria',result.acceptance_criteria)+promptClarificationGroup(result.clarifications);const editor=E('promptEnhanceEditor');editor.value=result.enhanced_prompt||draft.original;editor.readOnly=false;E('promptUseEnhanced').textContent='Save & Use';const model=[result.provider,result.model].filter(Boolean).join(' / '),budget=PROMPT_ENHANCE_BUDGETS.find(row=>row.id===(result.budget||draft.budget))?.label||'Medium',fallback=result.source==='fallback',hybrid=result.source==='hybrid';E('promptEnhanceModel').textContent=fallback?`Local template · ${budget}`:(model?`Generated by ${model}`:'Generated for this Agent session')+` · ${budget}`;let baseNote;if(fallback&&result.fallback_reason==='model_error')baseNote=`The model request failed, so this prompt was generated from the local ${budget} template.`;else if(fallback)baseNote=`The model returned unusable structured output, so this prompt was generated from the local ${budget} template.`;else if(hybrid)baseNote='The model response was partially structured; local defaults filled only missing analysis fields.';else baseNote='The intent analysis explains the rewrite. Only the editable Final Agent Prompt is sent when you choose Save & Use.';const elapsed=Number(result.duration_ms)>=0?` Completed in ${promptEnhanceElapsedLabel(result.duration_ms)}.`:'';const timeout=result.timeout_policy==='unlimited'?' No fixed server timeout was applied.':'';E('promptEnhanceNote').textContent=baseNote+elapsed+timeout+(result.warning?` ${result.warning}`:'');E('promptEnhanceOverlay').classList.remove('is-hidden');requestAnimationFrame(()=>editor.focus())}
125843
- async function submitAgentDraft(draft,message){const input=E('agentPrompt'),submittedPaths=new Set(draft.attachments||[]),cleared=input.value.trim()===draft.original.trim();let optimistic=null;if(!message||S.agentSubmitting)return;S.agentSubmitting=true;S.agentSubmissionStatus='submitting';S.agentSubmissionPendingUntil=Date.now()+30000;if(!S.agentOptimisticMessageKey||S.agentOptimisticMessageKey!==`${draft.session_id}:${message}`){S.agentOptimisticMessageKey=`${draft.session_id}:${message}`;optimistic=agentMessage(message,'user');optimistic.dataset.agentOptimistic=message;}S.agentSubmissionSeenRunning=!!S.agentState?.running;E('sendAgentBtn').disabled=true;if(cleared)input.value='';E('agentStatus').textContent=S.agentState?.running?'Queuing input...':'Submitting...';try{const out=await api(`/api/ide/sessions/${qs(draft.session_id)}/agent-task`,{method:'POST',body:JSON.stringify({root_id:draft.root_id,active_path:draft.active_path,message,attachments:draft.attachments||[]})});if(draft.session_id!==S.activeSession||draft.session_seq!==S.sessionSwitchSeq)return;S.agentAttachments=S.agentAttachments.filter(item=>!submittedPaths.has(item.path));renderAgentAttachments();if(draft.enhance_requested&&!S.promptEnhancePersistent){S.promptEnhanceEnabled=false;renderPromptEnhanceToggle();scheduleStateSave()}S.agentSubmitting=false;E('sendAgentBtn').disabled=false;input.focus();if(out.running||out.live_input){S.agentSubmissionStatus='running';S.agentSubmissionSeenRunning=true;E('agentStatus').textContent='Running'}else if(out.scheduler_started||out.scheduler_starting||out.deferred_start){S.agentSubmissionStatus='starting';E('agentStatus').textContent='Starting...'}else if(out.queued){S.agentSubmissionStatus='queued';E('agentStatus').textContent=Number(out.queue_position||0)>0?`Queued #${Number(out.queue_position)}`:'Queued'}else{S.agentSubmissionStatus='accepted';E('agentStatus').textContent='Accepted · starting...'}S.agentSubmissionPendingUntil=Date.now()+30000;S.agentPollRequested=true;scheduleAgentPoll(40)}catch(error){optimistic?.remove();S.agentOptimisticMessageKey='';S.agentSubmitting=false;S.agentSubmissionStatus='failed';S.agentSubmissionPendingUntil=Date.now()+10000;E('agentStatus').textContent='Submit failed';E('sendAgentBtn').disabled=false;if(cleared&&!input.value.trim())input.value=draft.original;input.focus();agentMessage(error.message,'error');throw error}}
127487
+ async function submitAgentDraft(draft,message){const input=E('agentPrompt'),submittedPaths=new Set(draft.attachments||[]),cleared=input.value.trim()===draft.original.trim();let optimistic=null;if(!message||S.agentSubmitting)return;S.agentSubmitting=true;S.agentSubmissionStatus='submitting';S.agentSubmissionPendingUntil=Date.now()+30000;if(!S.agentOptimisticMessageKey||S.agentOptimisticMessageKey!==`${draft.session_id}:${message}`){S.agentOptimisticMessageKey=`${draft.session_id}:${message}`;optimistic=agentMessage(message,'user');optimistic.dataset.agentOptimistic=message;}S.agentSubmissionSeenRunning=!!S.agentState?.running;E('sendAgentBtn').disabled=true;if(cleared)input.value='';E('agentStatus').textContent=S.agentState?.running?'Queuing input...':'Submitting...';try{const out=await api(`/api/ide/sessions/${qs(draft.session_id)}/agent-task`,{method:'POST',body:JSON.stringify({root_id:draft.root_id,active_path:draft.active_path,message,attachments:draft.attachments||[]})});if(draft.session_id!==S.activeSession||draft.session_seq!==S.sessionSwitchSeq)return;if(out&&(out.goal_command||out.slash_command)){for(const node of E('agentMessages')?.querySelectorAll('[data-agent-optimistic]')||[])if(node.dataset.agentOptimistic===message)node.remove();S.agentOptimisticMessageKey=''}S.agentAttachments=S.agentAttachments.filter(item=>!submittedPaths.has(item.path));renderAgentAttachments();if(draft.enhance_requested&&!S.promptEnhancePersistent){S.promptEnhanceEnabled=false;renderPromptEnhanceToggle();scheduleStateSave()}S.agentSubmitting=false;E('sendAgentBtn').disabled=false;input.focus();if(out.running||out.live_input){S.agentSubmissionStatus='running';S.agentSubmissionSeenRunning=true;E('agentStatus').textContent='Running'}else if(out.scheduler_started||out.scheduler_starting||out.deferred_start){S.agentSubmissionStatus='starting';E('agentStatus').textContent='Starting...'}else if(out.queued){S.agentSubmissionStatus='queued';E('agentStatus').textContent=Number(out.queue_position||0)>0?`Queued #${Number(out.queue_position)}`:'Queued'}else{S.agentSubmissionStatus='accepted';E('agentStatus').textContent='Accepted · starting...'}S.agentSubmissionPendingUntil=Date.now()+30000;S.agentPollRequested=true;scheduleAgentPoll(40)}catch(error){optimistic?.remove();S.agentOptimisticMessageKey='';S.agentSubmitting=false;S.agentSubmissionStatus='failed';S.agentSubmissionPendingUntil=Date.now()+10000;E('agentStatus').textContent='Submit failed';E('sendAgentBtn').disabled=false;if(cleared&&!input.value.trim())input.value=draft.original;input.focus();agentMessage(error.message,'error');throw error}}
125844
127488
  async function requestPromptEnhancement(draft,{regenerate=false}={}){if(S.promptEnhancing)return;const previous=regenerate?(E('promptEnhanceEditor').value.trim()||draft.result?.enhanced_prompt||''):'';const generation=regenerate?Number(draft.regeneration||0)+1:0,controller=typeof AbortController==='function'?new AbortController():null,pending={controller},budget=draft.budget||S.promptEnhanceBudget;S.promptEnhanceDraft=draft;S.promptEnhanceAbort=pending;E('promptEnhanceOverlay').classList.remove('is-hidden');if(!regenerate){E('promptEnhanceModel').textContent='';E('promptEnhanceIntent').textContent='';E('promptEnhanceDetails').innerHTML='';E('promptEnhanceEditor').value='';E('promptEnhanceNote').textContent=''}const budgetLabel=PROMPT_ENHANCE_BUDGETS.find(row=>row.id===budget)?.label||'Medium';setPromptEnhanceBusy(true,regenerate?`Regenerating ${budgetLabel} prompt...`:`Preparing ${budgetLabel} prompt with workspace${draft.skills_aware?' and skills':''} awareness...`);try{const result=await api(`/api/ide/v2/sessions/${qs(draft.session_id)}/prompt-enhance`,{method:'POST',body:JSON.stringify({root_id:draft.root_id,active_path:draft.active_path,message:draft.original,attachments:draft.attachments||[],previous_prompt:previous,regeneration:generation,budget,skills_awareness:!!draft.skills_aware}),signal:controller?.signal});if(S.promptEnhanceAbort!==pending||draft.session_id!==S.activeSession||draft.session_seq!==S.sessionSwitchSeq)return;S.promptEnhanceDraft=Object.assign({},draft,{result,regeneration:generation,budget});renderPromptEnhancement(result)}catch(error){if(error?.name==='AbortError')return;if(draft.session_id===S.activeSession&&draft.session_seq===S.sessionSwitchSeq){if(regenerate&&draft.result){S.promptEnhanceDraft=draft;E('promptEnhanceNote').textContent=`Regeneration failed: ${error.message}`}else{S.promptEnhanceDraft=Object.assign({},draft,{budget});E('promptEnhanceModel').textContent=`${budgetLabel} enhancement failed`;E('promptEnhanceIntent').textContent='No enhanced prompt was accepted. The original request is unchanged.';E('promptEnhanceDetails').innerHTML='';E('promptEnhanceEditor').value='';E('promptEnhanceNote').textContent=`Model error: ${error.message}. Choose Regenerate or Use Original & Start.`}E('promptEnhanceOverlay').classList.remove('is-hidden');toast(error.message,'error',8000)}}finally{if(S.promptEnhanceAbort===pending){S.promptEnhanceAbort=null;if(draft.session_id===S.activeSession&&draft.session_seq===S.sessionSwitchSeq)setPromptEnhanceBusy(false)}}}
125845
127489
  async function usePromptReview(original=false){const draft=S.promptEnhanceDraft;if(!draft)return;const message=original?draft.original:E('promptEnhanceEditor').value.trim();if(!message)return toast('Enhanced prompt is empty.','warning');S.promptEnhanceAbort=null;setPromptEnhanceBusy(false);E('promptEnhanceOverlay').classList.add('is-hidden');S.promptEnhanceDraft=null;await submitAgentDraft(draft,message)}
125846
127490
  async function regeneratePromptReview(){const draft=S.promptEnhanceDraft;if(!draft)return;await requestPromptEnhancement(draft,{regenerate:true})}
@@ -126001,6 +127645,37 @@ showAgentModelMenu=async function showAgentModelMenuWithSettingsAndActions(ancho
126001
127645
  window.addEventListener('pagehide',stopCollaborationPresenceHeartbeat);
126002
127646
  window.addEventListener('DOMContentLoaded',async()=>{initIconFallback();try{if(await authenticate())await startWorkbench()}catch(error){showError(error)}});
126003
127647
  """
127648
+ IDE_JS += r"""
127649
+ /* goal mode in the IDE agent panel */
127650
+ const AGENT_GOAL_STATUS={active:'Active',paused:'Paused',complete:'Achieved',impossible:'Not possible',budget_limited:'Budget used up',cleared:'Cleared'};
127651
+ const AGENT_GOAL_PHASE={set:'Goal set',continue:'Goal not met yet',complete:'Goal achieved',impossible:'Goal judged impossible',budget_limited:'Goal budget used up',paused:'Goal paused',pause:'Goal paused',resume:'Goal resumed',clear:'Goal cleared',waiting:'Goal waiting for you',deferred:'Goal continues after your message',status:'Goal status',error:'Goal command not applied',preferences:'Goal settings'};
127652
+ function agentGoalDuration(sec){const s=Math.max(0,Math.round(Number(sec)||0));if(s<60)return `${s}s`;const m=Math.floor(s/60);return m<60?`${m}m`:`${Math.floor(m/60)}h ${String(m%60).padStart(2,'0')}m`}
127653
+ function agentGoalMeta(goal){const g=goal||{},parts=[],done=Number(g.turns)||0,max=Number(g.max_turns)||0;if(max>0)parts.push(`turn ${g.status==='active'&&done<max?done+1:done}/${max}`);let used=Number(g.time_used_seconds)||0;if(g.status==='active'&&Number(g.active_since)>0){const live=(Number(g.time_banked_seconds)||0)+Date.now()/1000-Number(g.active_since);if(live>=0)used=live}parts.push(agentGoalDuration(used));if(Number(g.tokens_used)>0)parts.push(`${Number(g.tokens_used).toLocaleString()} tokens`);return parts.join(' · ')}
127654
+ function renderAgentSlashCard(row){const data=row&&typeof row.data==='object'?row.data:{},mode=['on','off','auto'].includes(String(data.mode||''))?String(data.mode):'auto';const notes={on:'The agent proposes a plan before it works.',off:'The agent works without a plan proposal.',auto:'The agent decides per task.'};const lines=[notes[mode]];if(data.action==='task')lines.push('The task was sent.');return agentToolCard({kind:'control',name:'plan',title:'Plan mode',state:`Plan: ${mode[0].toUpperCase()+mode.slice(1)}`,stateTone:mode==='on'?'running':'success',output:lines.join('\n'),role:'Plan',expanded:false})}
127655
+ function renderAgentGoalCard(row){const data=row&&typeof row.data==='object'?row.data:{},goal=data.goal&&typeof data.goal==='object'?data.goal:{},phase=String(data.phase||'status'),status=String(goal.status||''),lines=[];if(goal.objective)lines.push(`Condition: ${goal.objective}`);if(data.reason)lines.push(`Evaluator: ${data.reason}`);if(data.next_step&&phase!=='complete')lines.push(`Next step: ${data.next_step}`);if(phase==='continue')lines.push(`Next: turn ${(Number(data.turn)||0)+1}`);if(goal.status_reason&&goal.status_reason!==data.reason)lines.push(goal.status_reason);if(status)lines.push(agentGoalMeta(goal));if(data.summary&&(phase==='error'||phase==='waiting'||phase==='deferred'||phase==='preferences'))lines.unshift(String(data.summary));if(phase==='set'&&data.origin==='proposal')lines.unshift('Proposed by the agent and confirmed by you.');const tone=phase==='complete'?'success':(phase==='continue'||phase==='set'||phase==='resume'||phase==='status')?'running':'warning';const card=agentToolCard({kind:'control',name:'goal',title:AGENT_GOAL_PHASE[phase]||String(data.summary||'Goal'),state:phase==='preferences'?`Proposals ${data.mode==='on'?'on':'off'}`:(AGENT_GOAL_STATUS[status]||'Goal'),stateTone:tone,output:lines.join('\n'),role:'Goal',expanded:phase==='complete'||phase==='error'||phase==='set'});card.dataset.goalPhase=phase;return card}
127656
+ function renderAgentGoalBar(state){const bar=E('agentGoalBar');if(!bar)return;S.agentGoal=state&&state.goal||{};const g=state&&state.goal&&typeof state.goal==='object'?state.goal:{},status=String(g.status||'');if(status!=='active'&&status!=='paused'){bar.classList.add('is-hidden');bar.innerHTML='';return}const last=Array.isArray(g.verdicts)&&g.verdicts.length?g.verdicts[g.verdicts.length-1]:(g.last_verdict||{});const label=g.evaluating?'Checking the condition':(AGENT_GOAL_STATUS[status]||status);const acts=(status==='active'?[['pause','Pause']]:[['resume','Resume']]).concat([['clear','Clear']]);const html=`<div class="agent-goal-head"><span class="agent-goal-mark" aria-hidden="true"></span><strong>Goal</strong><span class="agent-goal-state">${escapeHtml(label)}</span><span class="agent-goal-meta">${escapeHtml(agentGoalMeta(g))}</span>${acts.map(([a,l])=>`<button type="button" class="agent-goal-btn" data-agent-goal="${a}">${escapeHtml(l)}</button>`).join('')}</div><div class="agent-goal-objective" title="${escapeHtml(String(g.objective||''))}">${escapeHtml(String(g.objective||''))}</div>${last&&last.reason?`<div class="agent-goal-reason">${escapeHtml(String(last.reason))}${last.next_step?` — next: ${escapeHtml(String(last.next_step))}`:''}</div>`:''}`;if(bar.innerHTML!==html)bar.innerHTML=html;bar.dataset.status=status;bar.classList.remove('is-hidden')}
127657
+ async function agentGoalAction(action){if(!S.activeSession)return;try{await api(`/api/ide/sessions/${qs(S.activeSession)}/agent-task`,{method:'POST',body:JSON.stringify({root_id:S.activeRoot||'session',message:`/goal ${action}`})})}catch(err){toast(String(err&&err.message||err),'error')}scheduleAgentPoll(60)}
127658
+ document.addEventListener('click',ev=>{const btn=ev.target&&ev.target.closest?ev.target.closest('[data-agent-goal]'):null;if(!btn)return;ev.preventDefault();agentGoalAction(String(btn.dataset.agentGoal||''))});
127659
+ setInterval(()=>{if(S.agentGoal&&S.agentGoal.status==='active'&&!S.agentGoal.evaluating)renderAgentGoalBar({goal:S.agentGoal})},15000);
127660
+ """
127661
+
127662
+ IDE_CSS += r"""
127663
+ .agent-goal{margin:0 0 8px;padding:7px 9px;border:1px solid #1f4b6e;border-left:2px solid #3794ff;background:#1b2530;color:#ddd;font-size:11px}
127664
+ .agent-goal[data-status="paused"]{border-color:#66501f;border-left-color:#d7ba7d;background:#252319}
127665
+ .agent-goal-head{display:flex;align-items:center;gap:6px;min-width:0}
127666
+ .agent-goal-mark{flex:0 0 auto;width:7px;height:7px;border-radius:50%;background:#3794ff;animation:agentGoalPulse 1.8s ease-in-out infinite}
127667
+ .agent-goal[data-status="paused"] .agent-goal-mark{background:#d7ba7d;animation:none}
127668
+ @keyframes agentGoalPulse{50%{opacity:.35}}
127669
+ .agent-goal-head strong{font-weight:600}
127670
+ .agent-goal-state{color:#75beff}
127671
+ .agent-goal[data-status="paused"] .agent-goal-state{color:#d7ba7d}
127672
+ .agent-goal-meta{flex:1 1 auto;min-width:0;color:#999;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-variant-numeric:tabular-nums}
127673
+ .agent-goal-btn{flex:0 0 auto;height:21px;padding:0 7px;border:1px solid #555;background:#2d2d2d;color:#ddd;font:inherit;font-size:10px;cursor:pointer}
127674
+ .agent-goal-btn:hover{border-color:#3794ff;background:#26323d}
127675
+ .agent-goal-objective{margin-top:4px;font-size:12px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
127676
+ .agent-goal-reason{margin-top:3px;color:#aaa;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}
127677
+ @media (prefers-reduced-motion:reduce){.agent-goal-mark{animation:none}}
127678
+ """
126004
127679
 
126005
127680
  # ============================================================================
126006
127681
  # Architecture / 架构 / アーキテクチャ
@@ -127926,12 +129601,14 @@ class SkillsStudioStore:
127926
129601
  }
127927
129602
 
127928
129603
 
127929
- STUDIO_INDEX_HTML = r'''<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Skills Studio 2.0</title><link rel="stylesheet" href="/assets/studio.css"></head><body><div class="studio"><header><div><span class="eyebrow">CLOUDS CODER</span><h1>Skills Studio <em>2.0</em></h1><p>Design private, testable Skill packages. Nothing reaches global agents before approval.</p></div><button id="newProject">New project</button></header><main><aside><div class="side-title">Projects</div><div id="projects"></div></aside><section class="workspace"><div id="empty" class="empty"><h2>Start a private Skill draft</h2><p>Create a project to design requirements, files, workflow and evaluations.</p><button id="emptyNew">Create project</button></div><div id="editor" class="hidden"><div class="project-head"><div><h2 id="projectTitle"></h2><div id="projectMeta" class="meta"></div></div><div class="actions"><button data-action="validate">Validate</button><button data-action="evaluate">Evaluate</button><button data-action="submit" class="primary">Request review</button></div></div><nav class="tabs"><button class="active" data-tab="brief">Brief</button><button data-tab="design">Design</button><button data-tab="files">Files</button><button data-tab="workflow">Workflow</button><button data-tab="evaluation">Evaluation</button></nav><div id="tabContent"></div></div></section><aside class="copilot"><div class="side-title">Copilot</div><p class="muted">Choose stepwise interview or one-click generation. Candidate patches stay private until you accept them.</p><textarea id="copilotInput" placeholder="Describe the skill goal, examples, constraints and references…"></textarea><div class="mode"><button data-mode="stepwise" class="selected">Stepwise</button><button data-mode="one_click">One-click</button></div><button id="copilotRun" class="primary wide">Generate private candidate</button><pre id="copilotStatus" class="status"></pre></aside></main></div><script src="/assets/js_lib/monaco/min/vs/loader.js"></script><script src="/assets/studio.js"></script></body></html>'''
127930
- STUDIO_CSS = r'''*{box-sizing:border-box}body{margin:0;background:#f4f7fb;color:#182538;font:14px/1.5 Inter,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}.studio{min-height:100vh}header{height:90px;background:#0d1b2a;color:#fff;padding:16px 28px;display:flex;align-items:center;justify-content:space-between}h1{margin:2px 0;font-size:25px}h1 em{font-style:normal;color:#64d6ff}.eyebrow{font-size:10px;letter-spacing:.18em;color:#8ba8c4}header p{margin:2px 0;color:#a9bdcf}button{border:1px solid #ccd8e5;background:#fff;color:#29415d;border-radius:8px;padding:8px 13px;cursor:pointer;font-weight:600}button:hover{border-color:#6aa8db}button.primary{background:#1668c7;border-color:#1668c7;color:#fff}button.wide{width:100%;margin-top:10px}.studio main{height:calc(100vh - 90px);display:grid;grid-template-columns:230px minmax(420px,1fr) 310px}.studio aside{background:#fff;border-right:1px solid #dce5ee;padding:16px;overflow:auto}.studio .copilot{border-left:1px solid #dce5ee;border-right:0;background:#fbfdff}.side-title{font-weight:800;color:#526a83;margin-bottom:12px}.project-item{padding:10px;border:1px solid transparent;border-radius:9px;margin-bottom:6px;cursor:pointer}.project-item:hover,.project-item.active{background:#eef6ff;border-color:#b7d7f5}.project-item small,.meta,.muted{color:#70859a;font-size:12px}.workspace{padding:24px;overflow:auto}.empty{max-width:520px;margin:12vh auto;text-align:center}.hidden{display:none!important}.project-head{display:flex;justify-content:space-between;gap:18px;align-items:start;border-bottom:1px solid #dce5ee;padding-bottom:15px}.project-head h2{margin:0}.actions{display:flex;gap:7px}.tabs{display:flex;gap:2px;margin:14px 0;border-bottom:1px solid #dce5ee}.tabs button{border:0;border-bottom:2px solid transparent;border-radius:0;background:transparent}.tabs button.active{color:#1668c7;border-bottom-color:#1668c7}.panel{background:#fff;border:1px solid #dce5ee;border-radius:12px;padding:18px;margin-bottom:12px}.file-row{display:flex;justify-content:space-between;width:100%;padding:9px;border:0;border-bottom:1px solid #edf1f5;border-radius:0;text-align:left}.file-row code{color:#1668c7}.file-workbench{display:grid;grid-template-columns:minmax(180px,28%) 1fr;gap:12px;min-height:460px}.file-tools{height:38px;display:flex;justify-content:space-between;align-items:center;color:#60768c}.monaco-host,.file-fallback{height:410px;width:100%;border:1px solid #d5e0ea}.file-fallback{display:none;min-height:410px;border-radius:0}textarea{width:100%;min-height:160px;border:1px solid #cbd8e5;border-radius:9px;padding:10px;font:13px/1.5 ui-monospace,monospace;resize:vertical}.mode{display:flex;gap:6px;margin-top:10px}.mode button{flex:1}.mode button.selected{background:#e7f2ff;border-color:#79b4ea;color:#075da9}.status{min-height:140px;white-space:pre-wrap;background:#0e1c2a;color:#bee4ff;border-radius:9px;padding:10px;font-size:11px}@media(max-width:1000px){.studio main{grid-template-columns:190px minmax(300px,1fr)}.copilot{position:fixed;right:0;top:90px;bottom:0;width:300px;box-shadow:-10px 0 30px #9eacbb;display:none}.copilot.open{display:block}}@media(max-width:700px){header{padding:12px 16px;height:auto}.studio main{height:auto;min-height:calc(100vh - 76px);grid-template-columns:1fr}.studio main>aside:first-child{display:none}.workspace{padding:14px}.actions{flex-wrap:wrap}.project-head{display:block}.actions{margin-top:10px}.file-workbench{grid-template-columns:1fr}.monaco-host,.file-fallback{height:330px;min-height:330px}}'''
129604
+ STUDIO_INDEX_HTML = r'''<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Skills Studio 2.0</title><!--cc-favicon:skills-studio--><link rel="stylesheet" href="/assets/studio.css"></head><body><div class="studio"><header><div><span class="eyebrow">CLOUDS CODER</span><h1><!--cc-logo:skills-studio:header:34-->Skills Studio <em>2.0</em></h1><p>Design private, testable Skill packages. Nothing reaches global agents before approval.</p></div><button id="newProject">New project</button></header><main><aside><div class="side-title">Projects</div><div id="projects"></div></aside><section class="workspace"><div id="empty" class="empty"><h2>Start a private Skill draft</h2><p>Create a project to design requirements, files, workflow and evaluations.</p><button id="emptyNew">Create project</button></div><div id="editor" class="hidden"><div class="project-head"><div><h2 id="projectTitle"></h2><div id="projectMeta" class="meta"></div></div><div class="actions"><button data-action="validate">Validate</button><button data-action="evaluate">Evaluate</button><button data-action="submit" class="primary">Request review</button></div></div><nav class="tabs"><button class="active" data-tab="brief">Brief</button><button data-tab="design">Design</button><button data-tab="files">Files</button><button data-tab="workflow">Workflow</button><button data-tab="evaluation">Evaluation</button></nav><div id="tabContent"></div></div></section><aside class="copilot"><div class="side-title">Copilot</div><p class="muted">Choose stepwise interview or one-click generation. Candidate patches stay private until you accept them.</p><textarea id="copilotInput" placeholder="Describe the skill goal, examples, constraints and references…"></textarea><div class="mode"><button data-mode="stepwise" class="selected">Stepwise</button><button data-mode="one_click">One-click</button></div><button id="copilotRun" class="primary wide">Generate private candidate</button><pre id="copilotStatus" class="status"></pre></aside></main></div><script src="/assets/js_lib/monaco/min/vs/loader.js"></script><script src="/assets/studio.js"></script></body></html>'''
129605
+ STUDIO_INDEX_HTML = embed_service_logos(STUDIO_INDEX_HTML)
129606
+ STUDIO_CSS = r'''*{box-sizing:border-box}body{margin:0;background:#f4f7fb;color:#182538;font:14px/1.5 Inter,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}.studio{min-height:100vh}header{height:90px;background:#0d1b2a;color:#fff;padding:16px 28px;display:flex;align-items:center;justify-content:space-between}h1{margin:2px 0;font-size:25px}h1 em{font-style:normal;color:#64d6ff}.eyebrow{font-size:10px;letter-spacing:.18em;color:#8ba8c4}header p{margin:2px 0;color:#a9bdcf}button{border:1px solid #ccd8e5;background:#fff;color:#29415d;border-radius:8px;padding:8px 13px;cursor:pointer;font-weight:600}button:hover{border-color:#6aa8db}button.primary{background:#1668c7;border-color:#1668c7;color:#fff}button.wide{width:100%;margin-top:10px}.studio main{height:calc(100vh - 90px);display:grid;grid-template-columns:230px minmax(420px,1fr) 310px}.studio aside{background:#fff;border-right:1px solid #dce5ee;padding:16px;overflow:auto}.studio .copilot{border-left:1px solid #dce5ee;border-right:0;background:#fbfdff}.side-title{font-weight:800;color:#526a83;margin-bottom:12px}.project-item{padding:10px;border:1px solid transparent;border-radius:9px;margin-bottom:6px;cursor:pointer}.project-item:hover,.project-item.active{background:#eef6ff;border-color:#b7d7f5}.project-item small,.meta,.muted{color:#70859a;font-size:12px}.workspace{padding:24px;overflow:auto}.empty{max-width:520px;margin:12vh auto;text-align:center}.hidden{display:none!important}.project-head{display:flex;justify-content:space-between;gap:18px;align-items:start;border-bottom:1px solid #dce5ee;padding-bottom:15px}.project-head h2{margin:0}.actions{display:flex;gap:7px}.tabs{display:flex;gap:2px;margin:14px 0;border-bottom:1px solid #dce5ee}.tabs button{border:0;border-bottom:2px solid transparent;border-radius:0;background:transparent}.tabs button.active{color:#1668c7;border-bottom-color:#1668c7}.panel{background:#fff;border:1px solid #dce5ee;border-radius:12px;padding:18px;margin-bottom:12px}.file-row{display:flex;justify-content:space-between;width:100%;padding:9px;border:0;border-bottom:1px solid #edf1f5;border-radius:0;text-align:left}.file-row code{color:#1668c7}.file-workbench{display:grid;grid-template-columns:minmax(180px,28%) 1fr;gap:12px;min-height:460px}.file-tools{height:38px;display:flex;justify-content:space-between;align-items:center;color:#60768c}.monaco-host,.file-fallback{height:410px;width:100%;border:1px solid #d5e0ea}.file-fallback{display:none;min-height:410px;border-radius:0}textarea{width:100%;min-height:160px;border:1px solid #cbd8e5;border-radius:9px;padding:10px;font:13px/1.5 ui-monospace,monospace;resize:vertical}.mode{display:flex;gap:6px;margin-top:10px}.mode button{flex:1}.mode button.selected{background:#e7f2ff;border-color:#79b4ea;color:#075da9}.status{min-height:140px;white-space:pre-wrap;background:#0e1c2a;color:#bee4ff;border-radius:9px;padding:10px;font-size:11px}@media(max-width:1000px){.studio main{grid-template-columns:190px minmax(300px,1fr)}.copilot{position:fixed;right:0;top:90px;bottom:0;width:300px;box-shadow:-10px 0 30px #9eacbb;display:none}.copilot.open{display:block}}@media(max-width:700px){header{padding:12px 16px;height:auto}.studio main{height:auto;min-height:calc(100vh - 76px);grid-template-columns:1fr}.studio main>aside:first-child{display:none}.workspace{padding:14px}.actions{flex-wrap:wrap}.project-head{display:block}.actions{margin-top:10px}.file-workbench{grid-template-columns:1fr}.monaco-host,.file-fallback{height:330px;min-height:330px}}h1 .cc-service-logo{vertical-align:-7px;margin-right:12px;border-radius:9px}'''
127931
129607
  STUDIO_JS = r'''const S={csrf:'',device:'',session:'',projects:[],project:null,mode:'stepwise',tab:'brief',job:null,monaco:null,editor:null,model:null};const $=id=>document.getElementById(id);const esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));async function api(path,opt={}){const h=new Headers(opt.headers||{});if(opt.body&&!h.has('Content-Type'))h.set('Content-Type','application/json');if(opt.method&&opt.method!=='GET')h.set('X-CSRF-Token',S.csrf);const r=await fetch(path,{credentials:'same-origin',cache:'no-store',...opt,headers:h});const b=await r.json();if(!r.ok)throw Error(b.error||`HTTP ${r.status}`);return b}async function boot(){const b=await api('/api/skillslab/v2/bootstrap');S.csrf=b.csrf_token;S.projects=b.projects||[];renderProjects();if(S.projects[0])openProject(S.projects[0].id)}function renderProjects(){const h=$('projects');h.innerHTML=S.projects.map(p=>`<div class="project-item ${S.project?.id===p.id?'active':''}" data-id="${esc(p.id)}"><strong>${esc(p.title)}</strong><br><small>${esc(p.status)} · v${p.revision}</small></div>`).join('')||'<p class="muted">No private drafts yet.</p>';h.querySelectorAll('[data-id]').forEach(x=>x.onclick=()=>openProject(x.dataset.id))}async function openProject(id){S.project=await api('/api/skillslab/v2/projects/'+encodeURIComponent(id));$('empty').classList.add('hidden');$('editor').classList.remove('hidden');$('projectTitle').textContent=S.project.title;$('projectMeta').textContent=`${S.project.status} · revision ${S.project.revision}`;renderProjects();renderTab()}function renderTab(){const c=$('tabContent');if(!S.project)return;const v=S.project.validation||{};if(S.tab==='files'){c.innerHTML=`<div class="panel"><div class="file-workbench"><div id="studioFileList">${(S.project.files||[]).map(f=>`<button class="file-row" data-file="${esc(f.path)}"><code>${esc(f.path)}</code><span>${f.size} bytes</span></button>`).join('')}</div><div><div class="file-tools"><span id="activeFile">Select a file</span><button id="saveFile" disabled>Save</button></div><div id="monacoHost" class="monaco-host"></div><textarea id="fileFallback" class="file-fallback"></textarea></div></div></div>`;c.querySelectorAll('[data-file]').forEach(x=>x.onclick=()=>openStudioFile(x.dataset.file));}else if(S.tab==='evaluation')c.innerHTML=`<div class="panel"><h3>Deterministic validation</h3><pre>${esc(JSON.stringify(v,null,2))}</pre></div>`;else c.innerHTML=`<div class="panel"><h3>${S.tab==='brief'?'Requirements brief':S.tab==='design'?'Design decisions':'Workflow view'}</h3><p>${esc(S.project.summary?.description||'Describe the target, triggers, inputs/outputs, tools, trust boundary and quality bar in Copilot.')}</p><p class="muted">Private draft only · global agents are unaffected.</p></div>`}async function initStudioEditor(value,path){const host=$('monacoHost'),fallback=$('fileFallback');if(window.require&&window.monaco){if(!S.editor){window.MonacoEnvironment={getWorker:()=>new Worker('/assets/studio-monaco-worker.js')};window.require.config({paths:{vs:'/assets/js_lib/monaco/min/vs'}});await new Promise((resolve,reject)=>window.require(['vs/editor/editor.main'],resolve,reject));S.monaco=window.monaco;S.editor=S.monaco.editor.create(host,{automaticLayout:true,minimap:{enabled:false},fontSize:13,wordWrap:'on'});}if(S.model)S.model.dispose();S.model=S.monaco.editor.createModel(value,path.endsWith('.md')?'markdown':path.endsWith('.yaml')||path.endsWith('.yml')?'yaml':'plaintext');S.editor.setModel(S.model);fallback.classList.add('hidden')}else{fallback.value=value;fallback.classList.remove('hidden')}}async function openStudioFile(path){const f=await api(`/api/skillslab/v2/projects/${S.project.id}/files/${encodeURIComponent(path)}`);S.activeFile=path;$('activeFile').textContent=path;$('saveFile').disabled=!!f.is_binary;if(!f.is_binary){await initStudioEditor(f.content,path);$('saveFile').onclick=async()=>{const content=S.editor&&S.model?S.model.getValue():$('fileFallback').value;await api(`/api/skillslab/v2/projects/${S.project.id}/files`,{method:'POST',body:JSON.stringify({path,content,expected_revision:S.project.revision})});await openProject(S.project.id)}}}async function newProject(){const title=prompt('Skill title');if(!title)return;const p=await api('/api/skillslab/v2/projects',{method:'POST',body:JSON.stringify({title})});S.projects.unshift(p);renderProjects();openProject(p.id)}document.querySelectorAll('[data-tab]').forEach(b=>b.onclick=()=>{S.tab=b.dataset.tab;document.querySelectorAll('[data-tab]').forEach(x=>x.classList.toggle('active',x===b));renderTab()});document.querySelectorAll('[data-mode]').forEach(b=>b.onclick=()=>{S.mode=b.dataset.mode;document.querySelectorAll('[data-mode]').forEach(x=>x.classList.toggle('selected',x===b))});$('newProject').onclick=$('emptyNew').onclick=()=>newProject().catch(e=>alert(e.message));document.querySelectorAll('[data-action]').forEach(b=>b.onclick=async()=>{try{if(b.dataset.action==='validate'){$('copilotStatus').textContent=JSON.stringify(await api(`/api/skillslab/v2/projects/${S.project.id}/validate`),null,2)}else if(b.dataset.action==='evaluate'){$('copilotStatus').textContent=JSON.stringify(await api(`/api/skillslab/v2/projects/${S.project.id}/evaluations`,{method:'POST',body:JSON.stringify({expected_revision:S.project.revision})}),null,2)}else{const out=await api(`/api/skillslab/v2/projects/${S.project.id}/submissions`,{method:'POST',body:JSON.stringify({expected_revision:S.project.revision})});$('copilotStatus').textContent=JSON.stringify(out,null,2)}openProject(S.project.id)}catch(e){alert(e.message)}});$('copilotRun').onclick=async()=>{try{const out=await api(`/api/skillslab/v2/projects/${S.project.id}/copilot/jobs`,{method:'POST',body:JSON.stringify({mode:S.mode,goal:$('copilotInput').value,expected_revision:S.project.revision})});$('copilotStatus').textContent=JSON.stringify(out,null,2);setTimeout(async()=>{$('copilotStatus').textContent=JSON.stringify(await api(`/api/skillslab/v2/copilot/jobs/${out.id}`),null,2)},250)}catch(e){alert(e.message)}};boot().catch(e=>{$('copilotStatus').textContent=e.message});'''
127932
129608
 
127933
- ADMIN_SKILLS_REVIEW_HTML = r'''<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Skills Review</title><link rel="stylesheet" href="/assets/skills-review.css"></head><body><header><div><span>ADMIN GOVERNANCE</span><h1>Skills Review</h1></div><div><input id="token" type="password" placeholder="Admin token"><button id="load">Load submissions</button></div></header><main><aside><select id="status"><option value="">All states</option><option>submitted</option><option>changes_requested</option><option>rejected</option><option>published</option><option>unpublished</option></select><div id="list"></div></aside><section id="detail"><div class="empty">Select a frozen submission.</div></section></main><script src="/assets/skills-review.js"></script></body></html>'''
127934
- ADMIN_SKILLS_REVIEW_CSS = r'''*{box-sizing:border-box}body{margin:0;background:#f5f7fa;color:#1d2b3a;font:14px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}header{height:78px;padding:13px 24px;background:#15273a;color:#fff;display:flex;justify-content:space-between;align-items:center}header span{font-size:10px;letter-spacing:.16em;color:#8db4d5}h1{margin:0;font-size:24px}input,select,button,textarea{font:inherit;border:1px solid #c5d2df;border-radius:7px;padding:8px}button{cursor:pointer;background:#fff}main{display:grid;grid-template-columns:300px 1fr;height:calc(100vh - 78px)}aside{background:#fff;border-right:1px solid #dbe3eb;padding:14px;overflow:auto}aside select{width:100%;margin-bottom:10px}.row{padding:11px;border:1px solid #dbe3eb;border-radius:9px;margin-bottom:8px;cursor:pointer}.row:hover{border-color:#5b9dd2}.row small{display:block;color:#6d8297}.detail{padding:24px;overflow:auto}.card{background:#fff;border:1px solid #dbe3eb;border-radius:10px;padding:16px;margin-bottom:12px}.files{display:grid;gap:5px}.file{display:flex;justify-content:space-between;padding:7px;background:#f3f7fb}pre{white-space:pre-wrap;max-height:50vh;overflow:auto;background:#102235;color:#d8edff;padding:14px;border-radius:8px}.actions{display:flex;gap:7px}.approve{background:#167044;color:#fff;border-color:#167044}.danger{color:#a12626}.empty{padding:15vh;text-align:center;color:#708397}@media(max-width:700px){main{grid-template-columns:1fr;height:auto}aside{border-right:0}header{height:auto;gap:10px;align-items:start;flex-direction:column}}'''
129609
+ ADMIN_SKILLS_REVIEW_HTML = r'''<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Skills Review</title><!--cc-favicon:admin--><link rel="stylesheet" href="/assets/skills-review.css"></head><body><header><div><span>ADMIN GOVERNANCE</span><h1><!--cc-logo:admin:header:30-->Skills Review</h1></div><div><input id="token" type="password" placeholder="Admin token"><button id="load">Load submissions</button></div></header><main><aside><select id="status"><option value="">All states</option><option>submitted</option><option>changes_requested</option><option>rejected</option><option>published</option><option>unpublished</option></select><div id="list"></div></aside><section id="detail"><div class="empty">Select a frozen submission.</div></section></main><script src="/assets/skills-review.js"></script></body></html>'''
129610
+ ADMIN_SKILLS_REVIEW_HTML = embed_service_logos(ADMIN_SKILLS_REVIEW_HTML)
129611
+ ADMIN_SKILLS_REVIEW_CSS = r'''*{box-sizing:border-box}body{margin:0;background:#f5f7fa;color:#1d2b3a;font:14px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}header{height:78px;padding:13px 24px;background:#15273a;color:#fff;display:flex;justify-content:space-between;align-items:center}header span{font-size:10px;letter-spacing:.16em;color:#8db4d5}h1{margin:0;font-size:24px}input,select,button,textarea{font:inherit;border:1px solid #c5d2df;border-radius:7px;padding:8px}button{cursor:pointer;background:#fff}main{display:grid;grid-template-columns:300px 1fr;height:calc(100vh - 78px)}aside{background:#fff;border-right:1px solid #dbe3eb;padding:14px;overflow:auto}aside select{width:100%;margin-bottom:10px}.row{padding:11px;border:1px solid #dbe3eb;border-radius:9px;margin-bottom:8px;cursor:pointer}.row:hover{border-color:#5b9dd2}.row small{display:block;color:#6d8297}.detail{padding:24px;overflow:auto}.card{background:#fff;border:1px solid #dbe3eb;border-radius:10px;padding:16px;margin-bottom:12px}.files{display:grid;gap:5px}.file{display:flex;justify-content:space-between;padding:7px;background:#f3f7fb}pre{white-space:pre-wrap;max-height:50vh;overflow:auto;background:#102235;color:#d8edff;padding:14px;border-radius:8px}.actions{display:flex;gap:7px}.approve{background:#167044;color:#fff;border-color:#167044}.danger{color:#a12626}.empty{padding:15vh;text-align:center;color:#708397}@media(max-width:700px){main{grid-template-columns:1fr;height:auto}aside{border-right:0}header{height:auto;gap:10px;align-items:start;flex-direction:column}}h1 .cc-service-logo{vertical-align:-6px;margin-right:10px;border-radius:8px}'''
127935
129612
  ADMIN_SKILLS_REVIEW_JS = r'''const A={token:sessionStorage.getItem('cc_admin_token')||'',rows:[]};const $=id=>document.getElementById(id),esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));$('token').value=A.token;async function api(path,opt={}){A.token=$('token').value.trim();sessionStorage.setItem('cc_admin_token',A.token);const h=new Headers(opt.headers||{});h.set('Authorization','Bearer '+A.token);if(opt.body)h.set('Content-Type','application/json');const r=await fetch(path,{...opt,headers:h,cache:'no-store'}),b=await r.json();if(!r.ok)throw Error(b.error||`HTTP ${r.status}`);return b}async function load(){const b=await api('/api/admin/skills/submissions?status='+encodeURIComponent($('status').value));A.rows=b.submissions||[];$('list').innerHTML=A.rows.map(x=>`<div class="row" data-id="${esc(x.id)}"><strong>${esc(x.summary?.name||x.project_id.slice(0,8))}</strong><small>${esc(x.status)} · revision ${x.revision}</small><small>${x.files.length} files</small></div>`).join('')||'<div class="empty">No submissions</div>';document.querySelectorAll('[data-id]').forEach(x=>x.onclick=()=>detail(x.dataset.id))}async function detail(id){const b=await api('/api/admin/skills/submissions/'+encodeURIComponent(id)),s=b.snapshot||{},row=A.rows.find(x=>x.id===id)||b;$('detail').innerHTML=`<div class="detail"><div class="card"><h2>${esc(s.project?.title||s.project?.slug||id)}</h2><p>Frozen revision ${b.revision} · ${esc(b.status)}</p><div class="actions"><button class="approve" data-act="approve">Approve & publish</button><button data-act="changes_requested">Request changes</button><button class="danger" data-act="reject">Reject</button>${b.status==='published'?'<button class="danger" data-act="unpublish">Unpublish</button>':''}</div></div><div class="card"><h3>Frozen file tree</h3><div class="files">${(s.files||[]).map(f=>`<div class="file"><code>${esc(f.path)}</code><span>${f.size} B · ${esc((f.digest||'').slice(0,12))}</span></div>`).join('')}</div></div><div class="card"><h3>Snapshot metadata</h3><pre>${esc(JSON.stringify({project:s.project,frozen_at:s.frozen_at},null,2))}</pre></div></div>`;document.querySelectorAll('[data-act]').forEach(x=>x.onclick=async()=>{const note=prompt('Review note')||'';await api(`/api/admin/skills/submissions/${id}/${x.dataset.act}`,{method:'POST',body:JSON.stringify({note})});await load();$('detail').innerHTML='<div class="empty">Review action completed.</div>'})}$('load').onclick=()=>load().catch(e=>alert(e.message));$('status').onchange=()=>load().catch(e=>alert(e.message));if(A.token)load().catch(()=>{});'''
127936
129613
 
127937
129614
  # Runtime composition root: wires models, skills, session managers, storage,
@@ -128973,9 +130650,11 @@ class AppContext:
128973
130650
  session_llm_concurrency: int | None = None,
128974
130651
  max_run_tokens: int = 0,
128975
130652
  max_task_tokens: int = 0,
130653
+ goal_default_turns: int = GOAL_DEFAULT_MAX_TURNS,
128976
130654
  ):
128977
130655
  self.max_run_tokens = max(0, int(max_run_tokens or 0))
128978
130656
  self.max_task_tokens = max(0, int(max_task_tokens or 0))
130657
+ self.goal_default_turns = max(1, min(GOAL_MAX_TURNS_LIMIT, int(goal_default_turns or GOAL_DEFAULT_MAX_TURNS)))
128979
130658
  self.workspace = Path(workspace).resolve()
128980
130659
  self.workspace_migration = _migrate_legacy_runtime_roots(self.workspace)
128981
130660
  self.base_url = base_url
@@ -133558,6 +135237,12 @@ document.addEventListener('DOMContentLoaded', function(){{
133558
135237
  context_lines.extend(f"- {path}" for path in attachments)
133559
135238
  context_lines.append("")
133560
135239
  context_lines.append(message)
135240
+ goal_reply = self._handle_slash_command(
135241
+ user_id, sess, message, wrap=lambda objective: "\n".join(context_lines[:-1] + [objective])
135242
+ )
135243
+ if goal_reply is not None:
135244
+ goal_reply["session_id"] = sid
135245
+ return goal_reply
133561
135246
  out = self.submit_user_message(user_id, sid, "\n".join(context_lines))
133562
135247
  result = dict(out if isinstance(out, dict) else {"ok": True, "result": out})
133563
135248
  result["session_id"] = sid
@@ -135013,6 +136698,8 @@ document.addEventListener('DOMContentLoaded', function(){{
135013
136698
  if row["id"] in seen_feed_ids:
135014
136699
  continue
135015
136700
  seen_feed_ids.add(row["id"])
136701
+ if role == "user" and bool(raw.get("user_input")):
136702
+ row["user_input"] = True
135016
136703
  data = raw.get("data", {}) if isinstance(raw.get("data"), dict) else {}
135017
136704
  if data:
135018
136705
  public_data = ide_public_operation_data(data)
@@ -135050,10 +136737,12 @@ document.addEventListener('DOMContentLoaded', function(){{
135050
136737
  )
135051
136738
  raw_feed_count = len(feed)
135052
136739
  raw_operation_count = len(operations)
135053
- feed, feed_truncated = _bounded_ui_rows(
136740
+ feed, feed_truncated = _bounded_ui_feed_rows(
135054
136741
  feed,
135055
136742
  max_rows=180,
135056
136743
  byte_budget=IDE_AGENT_FEED_BYTES,
136744
+ pin_limit=UI_PINNED_USER_ROWS_IDE,
136745
+ pin_budget=UI_PINNED_USER_ROWS_IDE_BYTES,
135057
136746
  text_limit=3600,
135058
136747
  data_text_limit=1200,
135059
136748
  collection_limit=20,
@@ -135084,6 +136773,11 @@ document.addEventListener('DOMContentLoaded', function(){{
135084
136773
  "role": trim(str(raw_question.get("role", "") or "agent"), 40),
135085
136774
  "ts": float(raw_question.get("ts", 0.0) or 0.0),
135086
136775
  }
136776
+ if isinstance(raw_question.get("goal_proposal"), dict):
136777
+ pending_question["goal_proposal"] = {
136778
+ "objective": trim(str(raw_question["goal_proposal"].get("objective", "") or ""), GOAL_OBJECTIVE_MAX_CHARS),
136779
+ "max_turns": int(raw_question["goal_proposal"].get("max_turns", 0) or 0),
136780
+ }
135087
136781
  if bool(snap.get("running", False)):
135088
136782
  try:
135089
136783
  active_tool = str(snap.get("agent_active_tool", "") or "").strip()
@@ -135111,6 +136805,7 @@ document.addEventListener('DOMContentLoaded', function(){{
135111
136805
  "title_revision": int(getattr(sess, "auto_title_revision", 0) or 0),
135112
136806
  "running": bool(snap.get("running", False)),
135113
136807
  "scheduler_starting": bool(snap.get("scheduler_starting", False)),
136808
+ "goal": dict(snap.get("goal") or {}),
135114
136809
  "phase": str(snap.get("agent_phase", "idle") or "idle"),
135115
136810
  "active_role": str(snap.get("agent_active_role", "") or ""),
135116
136811
  "active_tool": str(snap.get("agent_active_tool", "") or ""),
@@ -137997,7 +139692,58 @@ document.addEventListener('DOMContentLoaded', function(){{
137997
139692
  "queued_user": int(queued_for_user),
137998
139693
  }
137999
139694
 
138000
- def submit_user_message(self, user_id: str, session_id: str, content: str) -> dict:
139695
+ def _handle_goal_command(self, user_id: str, sess, text: str, *, wrap=None) -> dict | None:
139696
+ """Apply '/goal …' typed in the web agent or the IDE; None for other text.
139697
+
139698
+ Setting a goal submits the condition as the user's message, so the
139699
+ first turn starts through the normal (scheduler-aware) path; ``wrap``
139700
+ lets the IDE add its workspace context to that message.
139701
+ """
139702
+ try:
139703
+ command = SessionState.parse_goal_command(text)
139704
+ except ValueError as exc:
139705
+ sess._goal_emit("error", str(exc))
139706
+ return {"ok": False, "goal_command": True, "error": str(exc), "summary": str(exc)}
139707
+ if command is None:
139708
+ return None
139709
+ reply = sess.goal_command(command)
139710
+ start_text = str(reply.pop("start_text", "") or "")
139711
+ if start_text:
139712
+ run = self.submit_user_message(
139713
+ user_id, sess.id, wrap(start_text) if callable(wrap) else start_text, goal_commands=False
139714
+ )
139715
+ if isinstance(run, dict):
139716
+ for key in ("queued", "running", "queue_id", "deferred_start", "live_input"):
139717
+ if key in run:
139718
+ reply[key] = run[key]
139719
+ elif reply.pop("resume_run", False):
139720
+ reply["running"] = bool(sess.goal_resume_run())
139721
+ return reply
139722
+
139723
+ def _handle_plan_command(self, user_id: str, sess, text: str, *, wrap=None) -> dict | None:
139724
+ """Apply '/plan …' typed in the web agent or the IDE; None for other text."""
139725
+ command = SessionState.parse_plan_command(text)
139726
+ if command is None:
139727
+ return None
139728
+ reply = sess.plan_command(command)
139729
+ task = str(command.get("task", "") or "")
139730
+ if task:
139731
+ run = self.submit_user_message(user_id, sess.id, wrap(task) if callable(wrap) else task, goal_commands=False)
139732
+ if isinstance(run, dict):
139733
+ for key in ("queued", "running", "queue_id", "deferred_start", "live_input", "queue_position"):
139734
+ if key in run:
139735
+ reply[key] = run[key]
139736
+ reply["task_submitted"] = True
139737
+ return reply
139738
+
139739
+ def _handle_slash_command(self, user_id: str, sess, text: str, *, wrap=None) -> dict | None:
139740
+ """Session commands shared by the web agent and the IDE: /goal and /plan."""
139741
+ reply = self._handle_goal_command(user_id, sess, text, wrap=wrap)
139742
+ if reply is None:
139743
+ reply = self._handle_plan_command(user_id, sess, text, wrap=wrap)
139744
+ return reply
139745
+
139746
+ def submit_user_message(self, user_id: str, session_id: str, content: str, *, goal_commands: bool = True) -> dict:
138001
139747
  mgr = self.manager_for_user(user_id)
138002
139748
  sess = mgr.get(session_id)
138003
139749
  if not sess:
@@ -138005,6 +139751,10 @@ document.addEventListener('DOMContentLoaded', function(){{
138005
139751
  text = str(content or "").strip()
138006
139752
  if not text:
138007
139753
  raise ValueError("content required")
139754
+ if goal_commands:
139755
+ slash_reply = self._handle_slash_command(user_id, sess, text)
139756
+ if slash_reply is not None:
139757
+ return slash_reply
138008
139758
  try:
138009
139759
  self.telemetry.record(
138010
139760
  "message",
@@ -138337,6 +140087,7 @@ document.addEventListener('DOMContentLoaded', function(){{
138337
140087
  mgr.read_context_policy = normalize_read_context_policy(
138338
140088
  getattr(self, "read_context_policy", DEFAULT_READ_CONTEXT_POLICY)
138339
140089
  )
140090
+ mgr.goal_default_turns = int(getattr(self, "goal_default_turns", GOAL_DEFAULT_MAX_TURNS) or GOAL_DEFAULT_MAX_TURNS)
138340
140091
  mgr.tool_memory_policy = normalize_tool_memory_policy(
138341
140092
  getattr(self, "tool_memory_policy", getattr(self, "read_context_policy", DEFAULT_TOOL_MEMORY_POLICY))
138342
140093
  )
@@ -138702,6 +140453,7 @@ document.addEventListener('DOMContentLoaded', function(){{
138702
140453
  mgr.read_context_policy = normalize_read_context_policy(
138703
140454
  getattr(self, "read_context_policy", DEFAULT_READ_CONTEXT_POLICY)
138704
140455
  )
140456
+ mgr.goal_default_turns = int(getattr(self, "goal_default_turns", GOAL_DEFAULT_MAX_TURNS) or GOAL_DEFAULT_MAX_TURNS)
138705
140457
  mgr.tool_memory_policy = normalize_tool_memory_policy(
138706
140458
  getattr(self, "tool_memory_policy", DEFAULT_TOOL_MEMORY_POLICY)
138707
140459
  )
@@ -142911,6 +144663,34 @@ class Handler(BaseHTTPRequestHandler):
142911
144663
  pref = "auto"
142912
144664
  sess.plan_mode_user_preference = pref
142913
144665
  return self._send_json({"plan_mode": pref})
144666
+ m = re.match(r"^/api/sessions/([^/]+)/config/goal$", path)
144667
+ if m:
144668
+ sess = mgr.get(m.group(1))
144669
+ if not sess:
144670
+ return self._send_json({"error": "session not found"}, status=404)
144671
+ try:
144672
+ body = self._read_json()
144673
+ except Exception:
144674
+ body = {}
144675
+ if not isinstance(body, dict):
144676
+ body = {}
144677
+ updates: dict = {}
144678
+ for key in ("max_turns", "token_budget", "time_budget_seconds"):
144679
+ if key in body:
144680
+ try:
144681
+ updates[key] = max(0, int(float(body.get(key) or 0)))
144682
+ except (TypeError, ValueError):
144683
+ return self._send_json({"error": f"{key} must be a number"}, status=400)
144684
+ if "allow_model_proposals" in body:
144685
+ flag = body.get("allow_model_proposals")
144686
+ updates["allow_model_proposals"] = (
144687
+ flag if isinstance(flag, bool) else str(flag or "").strip().lower() in {"1", "true", "on", "yes"}
144688
+ )
144689
+ if int(updates.get("max_turns", 0) or 0) > GOAL_MAX_TURNS_LIMIT:
144690
+ return self._send_json({"error": f"max_turns must be between 0 and {GOAL_MAX_TURNS_LIMIT}"}, status=400)
144691
+ if updates:
144692
+ sess.goal_set_preferences(updates)
144693
+ return self._send_json({"ok": True, "preferences": sess.goal_public_preferences()})
142914
144694
  m = re.match(r"^/api/sessions/([^/]+)/config/task-level$", path)
142915
144695
  if m:
142916
144696
  sess = mgr.get(m.group(1))
@@ -146308,7 +148088,8 @@ class CollaborationHandler(IdeHandler):
146308
148088
  path = unquote(parsed.path)
146309
148089
  query = parse_qs(parsed.query or "")
146310
148090
  if path == "/":
146311
- return self._send_text(self.app.web_ui_ide_index_html(), "text/html; charset=utf-8")
148091
+ page = rebrand_service_logos(self.app.web_ui_ide_index_html(), "collaboration")
148092
+ return self._send_text(page, "text/html; charset=utf-8")
146312
148093
  if path == "/api/ide/v2/auth/status":
146313
148094
  return self._send_json({
146314
148095
  "ok": True,
@@ -146598,12 +148379,14 @@ class McpServiceHandler(BaseHTTPRequestHandler):
146598
148379
  body = "".join(rows) or '<tr><td colspan="5">no MCP servers configured</td></tr>'
146599
148380
  return (
146600
148381
  "<!doctype html><html><head><meta charset='utf-8'><title>MCP Service</title>"
148382
+ f"{service_favicon_link('mcp-service')}"
146601
148383
  "<style>body{font:14px system-ui;margin:24px;background:#0b0e14;color:#cdd6f4}"
146602
148384
  "table{border-collapse:collapse;width:100%}td,th{border:1px solid #313244;padding:6px 10px;text-align:left}"
146603
148385
  "th{background:#181825}code{color:#89b4fa}input,button{font:inherit;padding:6px 9px;margin:4px 4px 4px 0}"
146604
148386
  "button{cursor:pointer}article{border:1px solid #313244;padding:10px;margin:10px 0}pre{white-space:pre-wrap;overflow-wrap:anywhere}"
146605
- ".ok{color:#a6e3a1}.warn{color:#f9e2af}.err{color:#f38ba8}</style></head><body>"
146606
- f"<h2>Clouds_Coder MCP Service</h2>"
148387
+ ".ok{color:#a6e3a1}.warn{color:#f9e2af}.err{color:#f38ba8}"
148388
+ "h2 .cc-service-logo{vertical-align:-7px;margin-right:10px;border-radius:8px}</style></head><body>"
148389
+ f"<h2>{service_logo_svg('mcp-service', 30, 'header')}Clouds_Coder MCP Service</h2>"
146607
148390
  f"<p>ready <b>{h.get('ready',0)}/{h.get('total',0)}</b> · tools <b>{h.get('tool_count',0)}</b> · "
146608
148391
  f"monitor {'on' if h.get('monitor') else 'off'}</p>"
146609
148392
  "<table><tr><th>server</th><th>state</th><th>alive</th><th>tools</th><th>error</th></tr>"
@@ -146941,6 +148724,12 @@ def main():
146941
148724
  type=int,
146942
148725
  help=f"Per-run max agent rounds [{MIN_AGENT_ROUNDS}-{MAX_AGENT_ROUNDS_CAP}]",
146943
148726
  )
148727
+ parser.add_argument(
148728
+ "--goal_turns",
148729
+ default=GOAL_DEFAULT_MAX_TURNS,
148730
+ type=int,
148731
+ help=f"Default turn budget of a /goal set without --turns; one turn is one whole run [1-{GOAL_MAX_TURNS_LIMIT}]",
148732
+ )
146944
148733
  parser.add_argument(
146945
148734
  "--timeout",
146946
148735
  "--run_timeout",
@@ -148183,6 +149972,7 @@ def main():
148183
149972
  liquid_kernel_startup_policy=resolved_liquid_kernel_startup_policy,
148184
149973
  ide_password_login_enabled=bool(getattr(args, "ide_password_login_enabled", False)),
148185
149974
  max_run_tokens=max(0, int(args.max_run_tokens)), max_task_tokens=max(0, int(args.max_task_tokens)),
149975
+ goal_default_turns=int(getattr(args, "goal_turns", GOAL_DEFAULT_MAX_TURNS) or GOAL_DEFAULT_MAX_TURNS),
148186
149976
  )
148187
149977
  app.configure_startup_language(resolved_language, resolved_language_source)
148188
149978
  startup_evolution = app.restore_liquid_kernel_startup(