lewtun HF Staff OpenAI Codex commited on
Commit
94c9d71
·
2 Parent(s): 868f7ca550a209

Deploy 2026-06-18

Browse files

Co-authored-by: OpenAI Codex <codex@openai.com>

Files changed (39) hide show
  1. .github/dependabot.yml +11 -0
  2. .github/workflows/ci.yml +6 -6
  3. .github/workflows/claude-review.yml +2 -2
  4. .github/workflows/claude.yml +2 -2
  5. AGENTS.md +1 -1
  6. agent/context_manager/manager.py +21 -3
  7. agent/core/agent_loop.py +149 -73
  8. agent/core/model_ids.py +6 -6
  9. agent/core/model_switcher.py +8 -8
  10. agent/core/session.py +7 -1
  11. agent/main.py +5 -1
  12. agent/prompts/system_prompt_v3.yaml +42 -3
  13. agent/tools/jobs_tool.py +37 -5
  14. backend/dependencies.py +1 -1
  15. backend/routes/agent.py +33 -40
  16. backend/session_manager.py +18 -2
  17. configs/cli_agent_config.json +1 -1
  18. configs/frontend_agent_config.json +1 -1
  19. frontend/src/components/Chat/ChatInput.tsx +28 -27
  20. frontend/src/components/SessionSidebar/SessionSidebar.tsx +3 -3
  21. frontend/src/components/WelcomeScreen/WelcomeScreen.tsx +1 -1
  22. frontend/src/utils/model.ts +3 -3
  23. tests/unit/test_agent_model_gating.py +27 -37
  24. tests/unit/test_auto_approval_policy.py +1 -1
  25. tests/unit/test_build_kpis.py +3 -3
  26. tests/unit/test_cli_local_models.py +3 -3
  27. tests/unit/test_cli_rendering.py +9 -1
  28. tests/unit/test_config.py +7 -7
  29. tests/unit/test_effort_probe.py +1 -1
  30. tests/unit/test_llm_error_classification.py +1 -1
  31. tests/unit/test_llm_params.py +2 -2
  32. tests/unit/test_messaging.py +10 -10
  33. tests/unit/test_personal_trace_repo.py +1 -1
  34. tests/unit/test_prompt_caching.py +2 -2
  35. tests/unit/test_sandbox_auto_start.py +292 -1
  36. tests/unit/test_session_manager_persistence.py +30 -3
  37. tests/unit/test_session_resume.py +1 -1
  38. tests/unit/test_sft_tagger.py +1 -1
  39. tests/unit/test_thinking_history.py +159 -0
.github/dependabot.yml ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: 2
2
+ updates:
3
+ - package-ecosystem: "github-actions"
4
+ directory: "/"
5
+ schedule:
6
+ interval: "weekly"
7
+ cooldown:
8
+ default-days: 7
9
+ groups:
10
+ actions:
11
+ patterns: ["*"]
.github/workflows/ci.yml CHANGED
@@ -17,16 +17,16 @@ jobs:
17
  name: Ruff
18
  runs-on: ubuntu-latest
19
  steps:
20
- - uses: actions/checkout@v4
21
 
22
  - name: Install uv
23
- uses: astral-sh/setup-uv@v5
24
  with:
25
  enable-cache: true
26
  cache-dependency-glob: uv.lock
27
 
28
  - name: Set up Python
29
- uses: actions/setup-python@v5
30
  with:
31
  python-version: "3.12"
32
 
@@ -43,16 +43,16 @@ jobs:
43
  name: Tests
44
  runs-on: ubuntu-latest
45
  steps:
46
- - uses: actions/checkout@v4
47
 
48
  - name: Install uv
49
- uses: astral-sh/setup-uv@v5
50
  with:
51
  enable-cache: true
52
  cache-dependency-glob: uv.lock
53
 
54
  - name: Set up Python
55
- uses: actions/setup-python@v5
56
  with:
57
  python-version: "3.12"
58
 
 
17
  name: Ruff
18
  runs-on: ubuntu-latest
19
  steps:
20
+ - uses: actions/checkout@v6
21
 
22
  - name: Install uv
23
+ uses: astral-sh/setup-uv@v7
24
  with:
25
  enable-cache: true
26
  cache-dependency-glob: uv.lock
27
 
28
  - name: Set up Python
29
+ uses: actions/setup-python@v6
30
  with:
31
  python-version: "3.12"
32
 
 
43
  name: Tests
44
  runs-on: ubuntu-latest
45
  steps:
46
+ - uses: actions/checkout@v6
47
 
48
  - name: Install uv
49
+ uses: astral-sh/setup-uv@v7
50
  with:
51
  enable-cache: true
52
  cache-dependency-glob: uv.lock
53
 
54
  - name: Set up Python
55
+ uses: actions/setup-python@v6
56
  with:
57
  python-version: "3.12"
58
 
.github/workflows/claude-review.yml CHANGED
@@ -19,7 +19,7 @@ jobs:
19
  if: github.event.pull_request.draft == false
20
  runs-on: ubuntu-latest
21
  steps:
22
- - uses: actions/checkout@v4
23
  with:
24
  fetch-depth: 0
25
  # On pull_request_target, keep checkout on the trusted base-repo ref.
@@ -64,7 +64,7 @@ jobs:
64
  - name: Prepare Claude Code bin directory
65
  run: mkdir -p "$HOME/.local/bin"
66
 
67
- - uses: anthropics/claude-code-action@v1
68
  with:
69
  anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
70
  # Bypass the OIDC -> Claude GitHub App token exchange. That exchange
 
19
  if: github.event.pull_request.draft == false
20
  runs-on: ubuntu-latest
21
  steps:
22
+ - uses: actions/checkout@v6
23
  with:
24
  fetch-depth: 0
25
  # On pull_request_target, keep checkout on the trusted base-repo ref.
 
64
  - name: Prepare Claude Code bin directory
65
  run: mkdir -p "$HOME/.local/bin"
66
 
67
+ - uses: anthropics/claude-code-action@v1.0.137
68
  with:
69
  anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
70
  # Bypass the OIDC -> Claude GitHub App token exchange. That exchange
.github/workflows/claude.yml CHANGED
@@ -25,11 +25,11 @@ jobs:
25
  (github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude')))
26
  runs-on: ubuntu-latest
27
  steps:
28
- - uses: actions/checkout@v4
29
  with:
30
  fetch-depth: 0
31
 
32
- - uses: anthropics/claude-code-action@v1
33
  with:
34
  anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
35
  track_progress: true
 
25
  (github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude')))
26
  runs-on: ubuntu-latest
27
  steps:
28
+ - uses: actions/checkout@v6
29
  with:
30
  fetch-depth: 0
31
 
32
+ - uses: anthropics/claude-code-action@v1.0.137
33
  with:
34
  anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
35
  track_progress: true
AGENTS.md CHANGED
@@ -13,7 +13,7 @@ Notes:
13
  - Vite proxies `/api` and `/auth` to `http://localhost:7860`.
14
  - If `127.0.0.1:7860` is already owned by another local process, binding the backend to `::1` lets the Vite proxy resolve `localhost` cleanly.
15
  - Prefer `npm ci` over `npm install` for setup, since `npm install` may rewrite `frontend/package-lock.json` metadata depending on npm version.
16
- - Non-local LLM calls use `https://router.huggingface.co/v1` with the active Hugging Face user's token. Web sessions default to Kimi K2.6 for free users and Claude Opus 4.8 for Pro users; the CLI default is Claude Opus 4.8. For local development, set `HF_TOKEN` and optionally `ML_INTERN_DEFAULT_MODEL_ID`.
17
  - When asked to start the local server, export the GitHub CLI token first with `export GITHUB_TOKEN="$(gh auth token)"`.
18
  - When debugging a web app issue tied to a session ID, inspect the session data in `smolagents/ml-intern-sessions` for additional context.
19
 
 
13
  - Vite proxies `/api` and `/auth` to `http://localhost:7860`.
14
  - If `127.0.0.1:7860` is already owned by another local process, binding the backend to `::1` lets the Vite proxy resolve `localhost` cleanly.
15
  - Prefer `npm ci` over `npm install` for setup, since `npm install` may rewrite `frontend/package-lock.json` metadata depending on npm version.
16
+ - Non-local LLM calls use `https://router.huggingface.co/v1` with the active Hugging Face user's token. Web sessions and the CLI default to GLM 5.2. For local development, set `HF_TOKEN` and optionally `ML_INTERN_DEFAULT_MODEL_ID`.
17
  - When asked to start the local server, export the GitHub CLI token first with `export GITHUB_TOKEN="$(gh auth token)"`.
18
  - When debugging a web app issue tied to a session ID, inspect the session data in `smolagents/ml-intern-sessions` for additional context.
19
 
agent/context_manager/manager.py CHANGED
@@ -201,17 +201,23 @@ class ContextManager:
201
  tool_specs: list[dict[str, Any]] | None = None,
202
  prompt_file_suffix: str = "system_prompt_v3.yaml",
203
  hf_token: str | None = None,
 
204
  local_mode: bool = False,
 
205
  ):
206
  self.prompt_file_suffix = prompt_file_suffix
207
  self.tool_specs = tool_specs or []
208
  self.hf_token = hf_token
 
209
  self.local_mode = local_mode
 
210
  self.system_prompt = self._load_system_prompt(
211
  self.tool_specs,
212
  prompt_file_suffix=self.prompt_file_suffix,
213
  hf_token=hf_token,
 
214
  local_mode=local_mode,
 
215
  )
216
  # The model's real input-token ceiling (from litellm.get_model_info).
217
  # Compaction triggers at _COMPACT_THRESHOLD_RATIO below it — see
@@ -231,22 +237,30 @@ class ContextManager:
231
  *,
232
  tool_specs: list[dict[str, Any]] | None = None,
233
  hf_token: str | None = None,
 
234
  local_mode: bool | None = None,
 
235
  ) -> Message:
236
  """Re-render the system prompt and return it as a system message."""
237
  if tool_specs is not None:
238
  self.tool_specs = tool_specs
239
  if hf_token is not None:
240
  self.hf_token = hf_token
 
 
241
  if local_mode is not None:
242
  self.local_mode = local_mode
 
 
243
  self.system_prompt = self._load_system_prompt(
244
  self.tool_specs,
245
  prompt_file_suffix=getattr(
246
  self, "prompt_file_suffix", "system_prompt_v3.yaml"
247
  ),
248
  hf_token=getattr(self, "hf_token", None),
 
249
  local_mode=getattr(self, "local_mode", False),
 
250
  )
251
  return Message(role="system", content=self.system_prompt)
252
 
@@ -255,7 +269,9 @@ class ContextManager:
255
  tool_specs: list[dict[str, Any]],
256
  prompt_file_suffix: str = "system_prompt.yaml",
257
  hf_token: str | None = None,
 
258
  local_mode: bool = False,
 
259
  ):
260
  """Load and render the system prompt from YAML file with Jinja2"""
261
  prompt_file = Path(__file__).parent.parent / "prompts" / f"{prompt_file_suffix}"
@@ -271,13 +287,15 @@ class ContextManager:
271
  current_time = now.strftime("%H:%M:%S.%f")[:-3]
272
  current_timezone = f"{now.strftime('%Z')} (UTC{now.strftime('%z')[:3]}:{now.strftime('%z')[3:]})"
273
 
274
- # Get HF user info from OAuth token
275
- hf_user_info = _get_hf_username(hf_token)
 
276
 
277
  template = Template(template_str)
278
  static_prompt = template.render(
279
  tools=tool_specs,
280
  num_tools=len(tool_specs),
 
281
  )
282
 
283
  # CLI-specific context for local mode
@@ -301,7 +319,7 @@ class ContextManager:
301
  f"{static_prompt}\n\n"
302
  f"[Session context: Date={current_date}, Time={current_time}, "
303
  f"Timezone={current_timezone}, User={hf_user_info}, "
304
- f"Tools={len(tool_specs)}]"
305
  )
306
 
307
  def add_message(self, message: Message, token_count: int = None) -> None:
 
201
  tool_specs: list[dict[str, Any]] | None = None,
202
  prompt_file_suffix: str = "system_prompt_v3.yaml",
203
  hf_token: str | None = None,
204
+ hf_username: str | None = None,
205
  local_mode: bool = False,
206
+ autonomous_mode: bool = False,
207
  ):
208
  self.prompt_file_suffix = prompt_file_suffix
209
  self.tool_specs = tool_specs or []
210
  self.hf_token = hf_token
211
+ self.hf_username = hf_username
212
  self.local_mode = local_mode
213
+ self.autonomous_mode = autonomous_mode
214
  self.system_prompt = self._load_system_prompt(
215
  self.tool_specs,
216
  prompt_file_suffix=self.prompt_file_suffix,
217
  hf_token=hf_token,
218
+ hf_username=hf_username,
219
  local_mode=local_mode,
220
+ autonomous_mode=autonomous_mode,
221
  )
222
  # The model's real input-token ceiling (from litellm.get_model_info).
223
  # Compaction triggers at _COMPACT_THRESHOLD_RATIO below it — see
 
237
  *,
238
  tool_specs: list[dict[str, Any]] | None = None,
239
  hf_token: str | None = None,
240
+ hf_username: str | None = None,
241
  local_mode: bool | None = None,
242
+ autonomous_mode: bool | None = None,
243
  ) -> Message:
244
  """Re-render the system prompt and return it as a system message."""
245
  if tool_specs is not None:
246
  self.tool_specs = tool_specs
247
  if hf_token is not None:
248
  self.hf_token = hf_token
249
+ if hf_username is not None:
250
+ self.hf_username = hf_username
251
  if local_mode is not None:
252
  self.local_mode = local_mode
253
+ if autonomous_mode is not None:
254
+ self.autonomous_mode = autonomous_mode
255
  self.system_prompt = self._load_system_prompt(
256
  self.tool_specs,
257
  prompt_file_suffix=getattr(
258
  self, "prompt_file_suffix", "system_prompt_v3.yaml"
259
  ),
260
  hf_token=getattr(self, "hf_token", None),
261
+ hf_username=getattr(self, "hf_username", None),
262
  local_mode=getattr(self, "local_mode", False),
263
+ autonomous_mode=getattr(self, "autonomous_mode", False),
264
  )
265
  return Message(role="system", content=self.system_prompt)
266
 
 
269
  tool_specs: list[dict[str, Any]],
270
  prompt_file_suffix: str = "system_prompt.yaml",
271
  hf_token: str | None = None,
272
+ hf_username: str | None = None,
273
  local_mode: bool = False,
274
+ autonomous_mode: bool = False,
275
  ):
276
  """Load and render the system prompt from YAML file with Jinja2"""
277
  prompt_file = Path(__file__).parent.parent / "prompts" / f"{prompt_file_suffix}"
 
287
  current_time = now.strftime("%H:%M:%S.%f")[:-3]
288
  current_timezone = f"{now.strftime('%Z')} (UTC{now.strftime('%z')[:3]}:{now.strftime('%z')[3:]})"
289
 
290
+ # Prefer the username already resolved by the caller; fall back to a
291
+ # token lookup for contexts that construct ContextManager directly.
292
+ hf_user_info = hf_username or _get_hf_username(hf_token)
293
 
294
  template = Template(template_str)
295
  static_prompt = template.render(
296
  tools=tool_specs,
297
  num_tools=len(tool_specs),
298
+ autonomous_mode=autonomous_mode,
299
  )
300
 
301
  # CLI-specific context for local mode
 
319
  f"{static_prompt}\n\n"
320
  f"[Session context: Date={current_date}, Time={current_time}, "
321
  f"Timezone={current_timezone}, User={hf_user_info}, "
322
+ f"Tools={len(tool_specs)}, Autonomous={str(autonomous_mode).lower()}]"
323
  )
324
 
325
  def add_message(self, message: Message, token_count: int = None) -> None:
agent/core/agent_loop.py CHANGED
@@ -676,7 +676,7 @@ def _friendly_error_message(
676
  ):
677
  return (
678
  "Model not found. Use '/model' to list suggestions, or paste an "
679
- "HF model id like 'MiniMaxAI/MiniMax-M2.7'. Availability is shown "
680
  "when you switch."
681
  )
682
 
@@ -793,6 +793,33 @@ class LLMResult:
793
  usage: dict = field(default_factory=dict)
794
 
795
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
796
  def _is_invalid_thinking_signature_error(exc: Exception) -> bool:
797
  """Return True when a provider rejected replayed thinking metadata."""
798
  text = str(exc)
@@ -911,11 +938,22 @@ async def _call_llm_streaming(
911
  session: Session, messages, tools, llm_params
912
  ) -> LLMResult:
913
  """Call the LLM with streaming, emitting assistant_chunk events."""
914
- response = None
915
  _healed_effort = False # one-shot safety net per call
916
  _healed_thinking_signature = False
917
  t_start = time.monotonic()
918
  for _llm_attempt in range(_MAX_LLM_RETRIES):
 
 
 
 
 
 
 
 
 
 
 
 
919
  try:
920
  request_llm_params = with_prompt_cache_params(
921
  llm_params,
@@ -933,10 +971,93 @@ async def _call_llm_streaming(
933
  timeout=600,
934
  **request_llm_params,
935
  )
936
- break
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
937
  except ContextWindowExceededError:
938
  raise
939
  except Exception as e:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
940
  if _is_context_overflow_error(e):
941
  raise ContextWindowExceededError(str(e)) from e
942
  if not _healed_effort and _is_effort_config_error(e):
@@ -980,78 +1101,16 @@ async def _call_llm_streaming(
980
  },
981
  )
982
  )
983
- await asyncio.sleep(_delay)
 
 
 
 
 
 
984
  continue
985
  raise
986
 
987
- full_content = ""
988
- tool_calls_acc: dict[int, dict] = {}
989
- token_count = 0
990
- finish_reason = None
991
- final_usage_chunk = None
992
-
993
- async for chunk in response:
994
- if session.is_cancelled:
995
- tool_calls_acc.clear()
996
- break
997
-
998
- choice = chunk.choices[0] if chunk.choices else None
999
- if not choice:
1000
- if hasattr(chunk, "usage") and chunk.usage:
1001
- token_count = chunk.usage.total_tokens
1002
- final_usage_chunk = chunk
1003
- continue
1004
-
1005
- delta = choice.delta
1006
- if choice.finish_reason:
1007
- finish_reason = choice.finish_reason
1008
-
1009
- if delta.content:
1010
- full_content += delta.content
1011
- await session.send_event(
1012
- Event(event_type="assistant_chunk", data={"content": delta.content})
1013
- )
1014
-
1015
- if delta.tool_calls:
1016
- for tc_delta in delta.tool_calls:
1017
- idx = tc_delta.index
1018
- if idx not in tool_calls_acc:
1019
- tool_calls_acc[idx] = {
1020
- "id": "",
1021
- "type": "function",
1022
- "function": {"name": "", "arguments": ""},
1023
- }
1024
- if tc_delta.id:
1025
- tool_calls_acc[idx]["id"] = tc_delta.id
1026
- if tc_delta.function:
1027
- if tc_delta.function.name:
1028
- tool_calls_acc[idx]["function"]["name"] += (
1029
- tc_delta.function.name
1030
- )
1031
- if tc_delta.function.arguments:
1032
- tool_calls_acc[idx]["function"]["arguments"] += (
1033
- tc_delta.function.arguments
1034
- )
1035
-
1036
- if hasattr(chunk, "usage") and chunk.usage:
1037
- token_count = chunk.usage.total_tokens
1038
- final_usage_chunk = chunk
1039
-
1040
- usage = await telemetry.record_llm_call(
1041
- session,
1042
- model=llm_params.get("model", session.config.model_name),
1043
- response=final_usage_chunk,
1044
- latency_ms=int((time.monotonic() - t_start) * 1000),
1045
- finish_reason=finish_reason,
1046
- )
1047
- return LLMResult(
1048
- content=full_content or None,
1049
- tool_calls_acc=tool_calls_acc,
1050
- token_count=token_count,
1051
- finish_reason=finish_reason,
1052
- usage=usage,
1053
- )
1054
-
1055
 
1056
  async def _call_llm_non_streaming(
1057
  session: Session, messages, tools, llm_params
@@ -1062,6 +1121,13 @@ async def _call_llm_non_streaming(
1062
  _healed_thinking_signature = False
1063
  t_start = time.monotonic()
1064
  for _llm_attempt in range(_MAX_LLM_RETRIES):
 
 
 
 
 
 
 
1065
  try:
1066
  request_llm_params = with_prompt_cache_params(
1067
  llm_params,
@@ -1125,7 +1191,13 @@ async def _call_llm_non_streaming(
1125
  },
1126
  )
1127
  )
1128
- await asyncio.sleep(_delay)
 
 
 
 
 
 
1129
  continue
1130
  raise
1131
 
@@ -2557,7 +2629,9 @@ async def submission_loop(
2557
  session_holder: list | None = None,
2558
  hf_token: str | None = None,
2559
  user_id: str | None = None,
 
2560
  local_mode: bool = False,
 
2561
  stream: bool = True,
2562
  notification_gateway: NotificationGateway | None = None,
2563
  notification_destinations: list[str] | None = None,
@@ -2576,8 +2650,10 @@ async def submission_loop(
2576
  tool_router=tool_router,
2577
  hf_token=hf_token,
2578
  user_id=user_id,
 
2579
  user_plan=user_plan,
2580
  local_mode=local_mode,
 
2581
  stream=stream,
2582
  notification_gateway=notification_gateway,
2583
  notification_destinations=notification_destinations,
 
676
  ):
677
  return (
678
  "Model not found. Use '/model' to list suggestions, or paste an "
679
+ "HF model id like 'MiniMaxAI/MiniMax-M3:novita'. Availability is shown "
680
  "when you switch."
681
  )
682
 
 
793
  usage: dict = field(default_factory=dict)
794
 
795
 
796
+ def _session_cancelled(session: Any) -> bool:
797
+ return bool(getattr(session, "is_cancelled", False))
798
+
799
+
800
+ async def _sleep_for_retry_or_cancel(session: Session, delay: float) -> bool:
801
+ """Sleep for a retry delay, waking early if the session is interrupted."""
802
+ if _session_cancelled(session):
803
+ return True
804
+
805
+ cancel_event = getattr(session, "_cancelled", None)
806
+ if cancel_event is None or not hasattr(cancel_event, "wait"):
807
+ await asyncio.sleep(delay)
808
+ return _session_cancelled(session)
809
+
810
+ sleep_task = asyncio.create_task(asyncio.sleep(delay))
811
+ cancel_task = asyncio.create_task(cancel_event.wait())
812
+ done, pending = await asyncio.wait(
813
+ {sleep_task, cancel_task},
814
+ return_when=asyncio.FIRST_COMPLETED,
815
+ )
816
+ for task in pending:
817
+ task.cancel()
818
+ if pending:
819
+ await asyncio.gather(*pending, return_exceptions=True)
820
+ return cancel_task in done or _session_cancelled(session)
821
+
822
+
823
  def _is_invalid_thinking_signature_error(exc: Exception) -> bool:
824
  """Return True when a provider rejected replayed thinking metadata."""
825
  text = str(exc)
 
938
  session: Session, messages, tools, llm_params
939
  ) -> LLMResult:
940
  """Call the LLM with streaming, emitting assistant_chunk events."""
 
941
  _healed_effort = False # one-shot safety net per call
942
  _healed_thinking_signature = False
943
  t_start = time.monotonic()
944
  for _llm_attempt in range(_MAX_LLM_RETRIES):
945
+ if _session_cancelled(session):
946
+ return LLMResult(
947
+ content=None,
948
+ tool_calls_acc={},
949
+ token_count=0,
950
+ finish_reason=None,
951
+ )
952
+ full_content = ""
953
+ tool_calls_acc: dict[int, dict] = {}
954
+ token_count = 0
955
+ finish_reason = None
956
+ final_usage_chunk = None
957
  try:
958
  request_llm_params = with_prompt_cache_params(
959
  llm_params,
 
971
  timeout=600,
972
  **request_llm_params,
973
  )
974
+
975
+ async for chunk in response:
976
+ if session.is_cancelled:
977
+ tool_calls_acc.clear()
978
+ break
979
+
980
+ choice = chunk.choices[0] if chunk.choices else None
981
+ if not choice:
982
+ if hasattr(chunk, "usage") and chunk.usage:
983
+ token_count = chunk.usage.total_tokens
984
+ final_usage_chunk = chunk
985
+ continue
986
+
987
+ delta = choice.delta
988
+ if choice.finish_reason:
989
+ finish_reason = choice.finish_reason
990
+
991
+ if delta.content:
992
+ full_content += delta.content
993
+ await session.send_event(
994
+ Event(
995
+ event_type="assistant_chunk",
996
+ data={"content": delta.content},
997
+ )
998
+ )
999
+
1000
+ if delta.tool_calls:
1001
+ for tc_delta in delta.tool_calls:
1002
+ idx = tc_delta.index
1003
+ if idx not in tool_calls_acc:
1004
+ tool_calls_acc[idx] = {
1005
+ "id": "",
1006
+ "type": "function",
1007
+ "function": {"name": "", "arguments": ""},
1008
+ }
1009
+ if tc_delta.id:
1010
+ tool_calls_acc[idx]["id"] = tc_delta.id
1011
+ if tc_delta.function:
1012
+ if tc_delta.function.name:
1013
+ tool_calls_acc[idx]["function"]["name"] += (
1014
+ tc_delta.function.name
1015
+ )
1016
+ if tc_delta.function.arguments:
1017
+ tool_calls_acc[idx]["function"]["arguments"] += (
1018
+ tc_delta.function.arguments
1019
+ )
1020
+
1021
+ if hasattr(chunk, "usage") and chunk.usage:
1022
+ token_count = chunk.usage.total_tokens
1023
+ final_usage_chunk = chunk
1024
+
1025
+ usage = await telemetry.record_llm_call(
1026
+ session,
1027
+ model=llm_params.get("model", session.config.model_name),
1028
+ response=final_usage_chunk,
1029
+ latency_ms=int((time.monotonic() - t_start) * 1000),
1030
+ finish_reason=finish_reason,
1031
+ )
1032
+ return LLMResult(
1033
+ content=full_content or None,
1034
+ tool_calls_acc=tool_calls_acc,
1035
+ token_count=token_count,
1036
+ finish_reason=finish_reason,
1037
+ usage=usage,
1038
+ )
1039
  except ContextWindowExceededError:
1040
  raise
1041
  except Exception as e:
1042
+ stream_received_output = bool(full_content or tool_calls_acc)
1043
+ if full_content:
1044
+ await session.send_event(
1045
+ Event(event_type="assistant_stream_end", data={})
1046
+ )
1047
+ if stream_received_output:
1048
+ logger.warning(
1049
+ "Streaming LLM error after partial response; not retrying "
1050
+ "to avoid duplicating assistant output/tool calls: %s",
1051
+ e,
1052
+ )
1053
+ await telemetry.record_llm_call(
1054
+ session,
1055
+ model=llm_params.get("model", session.config.model_name),
1056
+ response=final_usage_chunk,
1057
+ latency_ms=int((time.monotonic() - t_start) * 1000),
1058
+ finish_reason=finish_reason or "error",
1059
+ )
1060
+ raise
1061
  if _is_context_overflow_error(e):
1062
  raise ContextWindowExceededError(str(e)) from e
1063
  if not _healed_effort and _is_effort_config_error(e):
 
1101
  },
1102
  )
1103
  )
1104
+ if await _sleep_for_retry_or_cancel(session, _delay):
1105
+ return LLMResult(
1106
+ content=None,
1107
+ tool_calls_acc={},
1108
+ token_count=0,
1109
+ finish_reason=None,
1110
+ )
1111
  continue
1112
  raise
1113
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1114
 
1115
  async def _call_llm_non_streaming(
1116
  session: Session, messages, tools, llm_params
 
1121
  _healed_thinking_signature = False
1122
  t_start = time.monotonic()
1123
  for _llm_attempt in range(_MAX_LLM_RETRIES):
1124
+ if _session_cancelled(session):
1125
+ return LLMResult(
1126
+ content=None,
1127
+ tool_calls_acc={},
1128
+ token_count=0,
1129
+ finish_reason=None,
1130
+ )
1131
  try:
1132
  request_llm_params = with_prompt_cache_params(
1133
  llm_params,
 
1191
  },
1192
  )
1193
  )
1194
+ if await _sleep_for_retry_or_cancel(session, _delay):
1195
+ return LLMResult(
1196
+ content=None,
1197
+ tool_calls_acc={},
1198
+ token_count=0,
1199
+ finish_reason=None,
1200
+ )
1201
  continue
1202
  raise
1203
 
 
2629
  session_holder: list | None = None,
2630
  hf_token: str | None = None,
2631
  user_id: str | None = None,
2632
+ hf_username: str | None = None,
2633
  local_mode: bool = False,
2634
+ autonomous_mode: bool = False,
2635
  stream: bool = True,
2636
  notification_gateway: NotificationGateway | None = None,
2637
  notification_destinations: list[str] | None = None,
 
2650
  tool_router=tool_router,
2651
  hf_token=hf_token,
2652
  user_id=user_id,
2653
+ hf_username=hf_username,
2654
  user_plan=user_plan,
2655
  local_mode=local_mode,
2656
+ autonomous_mode=autonomous_mode,
2657
  stream=stream,
2658
  notification_gateway=notification_gateway,
2659
  notification_destinations=notification_destinations,
agent/core/model_ids.py CHANGED
@@ -5,17 +5,17 @@ HF_ROUTER_BASE_URL = "https://router.huggingface.co/v1"
5
  # Keep these as verbatim HF Router ids; version punctuation differs by model.
6
  CLAUDE_OPUS_48_MODEL_ID = "anthropic/claude-opus-4.8:fal-ai"
7
  GPT_55_MODEL_ID = "openai/gpt-5.5:fal-ai"
8
- KIMI_K26_MODEL_ID = "moonshotai/Kimi-K2.6:novita"
9
- MINIMAX_M27_MODEL_ID = "MiniMaxAI/MiniMax-M2.7:novita"
10
- GLM_51_MODEL_ID = "zai-org/GLM-5.1:novita"
11
  DEEPSEEK_V4_PRO_MODEL_ID = "deepseek-ai/DeepSeek-V4-Pro:novita"
12
 
13
  HOSTED_MODEL_IDS = {
14
  CLAUDE_OPUS_48_MODEL_ID,
15
  GPT_55_MODEL_ID,
16
- KIMI_K26_MODEL_ID,
17
- MINIMAX_M27_MODEL_ID,
18
- GLM_51_MODEL_ID,
19
  DEEPSEEK_V4_PRO_MODEL_ID,
20
  }
21
 
 
5
  # Keep these as verbatim HF Router ids; version punctuation differs by model.
6
  CLAUDE_OPUS_48_MODEL_ID = "anthropic/claude-opus-4.8:fal-ai"
7
  GPT_55_MODEL_ID = "openai/gpt-5.5:fal-ai"
8
+ KIMI_K27_CODE_MODEL_ID = "moonshotai/Kimi-K2.7-Code:novita"
9
+ MINIMAX_M3_MODEL_ID = "MiniMaxAI/MiniMax-M3:novita"
10
+ GLM_52_MODEL_ID = "zai-org/GLM-5.2:novita"
11
  DEEPSEEK_V4_PRO_MODEL_ID = "deepseek-ai/DeepSeek-V4-Pro:novita"
12
 
13
  HOSTED_MODEL_IDS = {
14
  CLAUDE_OPUS_48_MODEL_ID,
15
  GPT_55_MODEL_ID,
16
+ KIMI_K27_CODE_MODEL_ID,
17
+ MINIMAX_M3_MODEL_ID,
18
+ GLM_52_MODEL_ID,
19
  DEEPSEEK_V4_PRO_MODEL_ID,
20
  }
21
 
agent/core/model_switcher.py CHANGED
@@ -29,24 +29,24 @@ from agent.core.local_models import (
29
  from agent.core.model_ids import (
30
  CLAUDE_OPUS_48_MODEL_ID,
31
  DEEPSEEK_V4_PRO_MODEL_ID,
32
- GLM_51_MODEL_ID,
33
  GPT_55_MODEL_ID,
34
- KIMI_K26_MODEL_ID,
35
- MINIMAX_M27_MODEL_ID,
36
  strip_huggingface_model_prefix,
37
  )
38
 
39
 
40
  # Suggested models shown by `/model` (not a gate). Users can paste any HF
41
- # Router model id (e.g. "MiniMaxAI/MiniMax-M2.7"). Append ":fastest",
42
  # ":cheapest", ":preferred", or ":<provider>" to override the default routing
43
  # policy (auto = fastest with failover).
44
  SUGGESTED_MODELS = [
45
  {"id": CLAUDE_OPUS_48_MODEL_ID, "label": "Claude Opus 4.8"},
46
  {"id": GPT_55_MODEL_ID, "label": "GPT-5.5"},
47
- {"id": MINIMAX_M27_MODEL_ID, "label": "MiniMax M2.7"},
48
- {"id": KIMI_K26_MODEL_ID, "label": "Kimi K2.6"},
49
- {"id": GLM_51_MODEL_ID, "label": "GLM 5.1"},
50
  {"id": DEEPSEEK_V4_PRO_MODEL_ID, "label": "DeepSeek V4 Pro"},
51
  ]
52
 
@@ -161,7 +161,7 @@ def print_model_listing(config, console) -> None:
161
  marker = " [dim]<-- current[/dim]" if m["id"] == current else ""
162
  console.print(f" {m['id']} [dim]({m['label']})[/dim]{marker}")
163
  console.print(
164
- "\n[dim]Paste any HF model id (e.g. 'MiniMaxAI/MiniMax-M2.7').\n"
165
  "Add ':fastest', ':cheapest', ':preferred', or ':<provider>' to override routing.\n"
166
  "Use 'ollama/<model>', 'vllm/<model>', 'lm_studio/<model>', or "
167
  "'llamacpp/<model>' for local OpenAI-compatible endpoints.[/dim]"
 
29
  from agent.core.model_ids import (
30
  CLAUDE_OPUS_48_MODEL_ID,
31
  DEEPSEEK_V4_PRO_MODEL_ID,
32
+ GLM_52_MODEL_ID,
33
  GPT_55_MODEL_ID,
34
+ KIMI_K27_CODE_MODEL_ID,
35
+ MINIMAX_M3_MODEL_ID,
36
  strip_huggingface_model_prefix,
37
  )
38
 
39
 
40
  # Suggested models shown by `/model` (not a gate). Users can paste any HF
41
+ # Router model id (e.g. "MiniMaxAI/MiniMax-M3:novita"). Append ":fastest",
42
  # ":cheapest", ":preferred", or ":<provider>" to override the default routing
43
  # policy (auto = fastest with failover).
44
  SUGGESTED_MODELS = [
45
  {"id": CLAUDE_OPUS_48_MODEL_ID, "label": "Claude Opus 4.8"},
46
  {"id": GPT_55_MODEL_ID, "label": "GPT-5.5"},
47
+ {"id": MINIMAX_M3_MODEL_ID, "label": "MiniMax M3"},
48
+ {"id": KIMI_K27_CODE_MODEL_ID, "label": "Kimi K2.7 Code"},
49
+ {"id": GLM_52_MODEL_ID, "label": "GLM 5.2"},
50
  {"id": DEEPSEEK_V4_PRO_MODEL_ID, "label": "DeepSeek V4 Pro"},
51
  ]
52
 
 
161
  marker = " [dim]<-- current[/dim]" if m["id"] == current else ""
162
  console.print(f" {m['id']} [dim]({m['label']})[/dim]{marker}")
163
  console.print(
164
+ "\n[dim]Paste any HF model id (e.g. 'MiniMaxAI/MiniMax-M3:novita').\n"
165
  "Add ':fastest', ':cheapest', ':preferred', or ':<provider>' to override routing.\n"
166
  "Use 'ollama/<model>', 'vllm/<model>', 'lm_studio/<model>', or "
167
  "'llamacpp/<model>' for local OpenAI-compatible endpoints.[/dim]"
agent/core/session.py CHANGED
@@ -52,7 +52,7 @@ def _get_max_tokens_safe(model_name: str) -> int:
52
 
53
  Primary source: ``litellm.get_model_info(model)['max_input_tokens']``.
54
  Strips any HF routing suffix / huggingface/ prefix so tagged ids
55
- ('moonshotai/Kimi-K2.6:cheapest') look up the bare model. Falls back to a
56
  conservative 200k default for models not in the catalog.
57
  """
58
  from litellm import get_model_info
@@ -108,6 +108,7 @@ class Session:
108
  context_manager: ContextManager | None = None,
109
  hf_token: str | None = None,
110
  local_mode: bool = False,
 
111
  stream: bool = True,
112
  notification_gateway: NotificationGateway | None = None,
113
  notification_destinations: list[str] | None = None,
@@ -123,6 +124,7 @@ class Session:
123
  self.hf_username: Optional[str] = hf_username
124
  self.user_plan: str | None = user_plan
125
  self.local_mode = local_mode
 
126
  self.persistence_store = persistence_store
127
  self.tool_router = tool_router
128
  self.stream = stream
@@ -135,7 +137,9 @@ class Session:
135
  untouched_messages=5,
136
  tool_specs=tool_specs,
137
  hf_token=hf_token,
 
138
  local_mode=local_mode,
 
139
  )
140
  self.event_queue = event_queue
141
  self.session_id = session_id or str(uuid.uuid4())
@@ -500,7 +504,9 @@ class Session:
500
  return refresh(
501
  tool_specs=tool_specs,
502
  hf_token=self.hf_token,
 
503
  local_mode=self.local_mode,
 
504
  )
505
  except Exception as e:
506
  logger.warning("Failed to refresh system prompt for new chat: %s", e)
 
52
 
53
  Primary source: ``litellm.get_model_info(model)['max_input_tokens']``.
54
  Strips any HF routing suffix / huggingface/ prefix so tagged ids
55
+ ('moonshotai/Kimi-K2.7-Code:novita') look up the bare model. Falls back to a
56
  conservative 200k default for models not in the catalog.
57
  """
58
  from litellm import get_model_info
 
108
  context_manager: ContextManager | None = None,
109
  hf_token: str | None = None,
110
  local_mode: bool = False,
111
+ autonomous_mode: bool = False,
112
  stream: bool = True,
113
  notification_gateway: NotificationGateway | None = None,
114
  notification_destinations: list[str] | None = None,
 
124
  self.hf_username: Optional[str] = hf_username
125
  self.user_plan: str | None = user_plan
126
  self.local_mode = local_mode
127
+ self.autonomous_mode = autonomous_mode
128
  self.persistence_store = persistence_store
129
  self.tool_router = tool_router
130
  self.stream = stream
 
137
  untouched_messages=5,
138
  tool_specs=tool_specs,
139
  hf_token=hf_token,
140
+ hf_username=hf_username,
141
  local_mode=local_mode,
142
+ autonomous_mode=autonomous_mode,
143
  )
144
  self.event_queue = event_queue
145
  self.session_id = session_id or str(uuid.uuid4())
 
504
  return refresh(
505
  tool_specs=tool_specs,
506
  hf_token=self.hf_token,
507
+ hf_username=self.hf_username,
508
  local_mode=self.local_mode,
509
+ autonomous_mode=self.autonomous_mode,
510
  )
511
  except Exception as e:
512
  logger.warning("Failed to refresh system prompt for new chat: %s", e)
agent/main.py CHANGED
@@ -86,7 +86,7 @@ def _validate_cli_model_override(model: str) -> str:
86
  if not model_switcher.is_valid_model_id(model):
87
  raise ValueError(
88
  "Invalid model id. Use an HF Router id like "
89
- "'anthropic/claude-opus-4.8:fal-ai' or a supported local prefix."
90
  )
91
  return model.removeprefix("huggingface/")
92
 
@@ -1241,8 +1241,10 @@ async def main(model: str | None = None, sandbox_tools: bool = False):
1241
  session_holder=session_holder,
1242
  hf_token=hf_token,
1243
  user_id=hf_user,
 
1244
  user_plan=hf_user_plan,
1245
  local_mode=local_mode,
 
1246
  stream=True,
1247
  notification_gateway=notification_gateway,
1248
  notification_destinations=config.messaging.default_auto_destinations(),
@@ -1485,8 +1487,10 @@ async def headless_main(
1485
  session_holder=session_holder,
1486
  hf_token=hf_token,
1487
  user_id=hf_user,
 
1488
  user_plan=hf_user_plan,
1489
  local_mode=local_mode,
 
1490
  stream=stream,
1491
  notification_gateway=notification_gateway,
1492
  notification_destinations=config.messaging.default_auto_destinations(),
 
86
  if not model_switcher.is_valid_model_id(model):
87
  raise ValueError(
88
  "Invalid model id. Use an HF Router id like "
89
+ "'zai-org/GLM-5.2:novita' or a supported local prefix."
90
  )
91
  return model.removeprefix("huggingface/")
92
 
 
1241
  session_holder=session_holder,
1242
  hf_token=hf_token,
1243
  user_id=hf_user,
1244
+ hf_username=hf_user,
1245
  user_plan=hf_user_plan,
1246
  local_mode=local_mode,
1247
+ autonomous_mode=False,
1248
  stream=True,
1249
  notification_gateway=notification_gateway,
1250
  notification_destinations=config.messaging.default_auto_destinations(),
 
1487
  session_holder=session_holder,
1488
  hf_token=hf_token,
1489
  user_id=hf_user,
1490
+ hf_username=hf_user,
1491
  user_plan=hf_user_plan,
1492
  local_mode=local_mode,
1493
+ autonomous_mode=True,
1494
  stream=stream,
1495
  notification_gateway=notification_gateway,
1496
  notification_destinations=config.messaging.default_auto_destinations(),
agent/prompts/system_prompt_v3.yaml CHANGED
@@ -3,6 +3,21 @@ system_prompt: |
3
 
4
  Your goal is to complete what the user requested with zero errors. You are fully autonomous — research, validate, implement, and deliver results without asking for unnecessary confirmation.
5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  # Your knowledge of HF libraries is outdated
7
 
8
  You do not know current APIs for TRL, Transformers, PEFT, Trackio, or other HF libraries. Your internal knowledge WILL produce wrong imports, wrong argument names, and wrong trainer configurations.
@@ -42,7 +57,9 @@ system_prompt: |
42
 
43
  SILENT DATASET SUBSTITUTION: When a requested dataset fails to load, you will silently switch to a different one without telling the user. Fix: if the requested dataset isn't available, tell the user and ask what to do.
44
 
45
- PREFER HUB KERNELS OVER COMPILING ATTENTION: Do NOT pip install 'flash-attn' to enable flash_attention_2 building from source can take many minutes to hours and often fails on the job's CUDA/PyTorch combo. Instead, use the HF `kernels` library (`pip install kernels`, already pulled in by recent TRL) and load a prebuilt attention kernel from the Hub via `attn_implementation`. Examples: `AutoModelForCausalLM.from_pretrained(..., attn_implementation="kernels-community/flash-attn2")`, or `kernels-community/vllm-flash-attn3`, or `kernels-community/paged-attention`. With TRL/SFT scripts you can pass `--attn_implementation kernels-community/flash-attn2` on the CLI. Search additional kernels at https://huggingface.co/models?other=kernel. Only `pip install` extra packages (and document why) when no Hub kernel covers the need.
 
 
46
 
47
  SCOPE-CHANGING FIXES: Avoid at all costs! When you hit an error (especially OOM), you will try "creative" workarounds that change what the user asked for and/or change the training task itself — switching full SFT to LoRA on OOM, reducing max_length (silently truncates training data and changes what the model learns), disabling monitoring instead of fixing it. Do not do this. Fix errors with the minimal change that preserves the user's original request and are grounded in research and examples. If the original approach genuinely cannot work, explain why and ask the user for input before changing methods, sequence length, training approach or any other part of the task.
48
 
@@ -66,7 +83,7 @@ system_prompt: |
66
  report_to="trackio"
67
  run_name="<descriptive-run-name>" # e.g. "sft_qwen3-4b_lr2e-5_bs128"
68
  project="<descriptive-project-name>" # keeps related runs grouped so you can compare them
69
- trackio_space_id="<username>/ml-intern-<8-char-id>" # creates a public dashboard Space
70
  `project` and `trackio_space_id` can also be set via TRACKIO_PROJECT / TRACKIO_SPACE_ID env vars.
71
 
72
  Alerts are how iterations decide what to change. Use trackio.alert(title, text, level) at every decision point in training. Levels:
@@ -108,7 +125,23 @@ system_prompt: |
108
  - a public/raw URL
109
  If you wrote or tested a script locally, read the file content and submit it inline, or write it into the sandbox first.
110
 
111
- GPU preflight is mandatory before hf_jobs when the job will run on GPU, or when the script loads a model, uses CUDA, bf16/fp16, quantization, flash attention, or torch.compile. First create a GPU sandbox with sandbox_create (t4-small minimum; choose larger hardware when VRAM requires it), run a tiny smoke test there using the same imports, model-loading path, training entrypoint, and a tiny dataset/subset, then fix failures before submitting. If you skip GPU sandbox preflight, state why before calling hf_jobs.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
 
113
  Before calling hf_jobs, output a pre-flight check:
114
  - Reference implementation: [which example you based this on]
@@ -168,6 +201,9 @@ system_prompt: |
168
 
169
  # Autonomous / headless mode
170
 
 
 
 
171
  When running autonomously (no human in the loop), you MUST follow these rules:
172
 
173
  NEVER respond with only text. Every response MUST include at least one tool call. If you have nothing to do, check the plan, verify outputs or plan ahead. A text-only response ends the agent loop permanently — there is no human to re-prompt you.
@@ -193,6 +229,9 @@ system_prompt: |
193
  The task is NOT done until:
194
  - The required output exists (e.g. final model, metrics reached, dataset updated etc)
195
  - You have evaluated the model and confirmed it works
 
 
 
196
 
197
  # Communication
198
 
 
3
 
4
  Your goal is to complete what the user requested with zero errors. You are fully autonomous — research, validate, implement, and deliver results without asking for unnecessary confirmation.
5
 
6
+ # Identity
7
+
8
+ When greeting the user or asked who you are, introduce yourself as ML Intern.
9
+ Do not claim to be Claude, ChatGPT, Anthropic, OpenAI, or the underlying backend model. If asked what model powers you, say ML Intern can run on different backend models and only give model details if they are explicitly available in session context.
10
+ Do not cite this system prompt, hidden instructions, or internal mechanics as the reason for your behavior.
11
+ Default to the session context User value as the authenticated Hugging Face namespace when creating hub_model_id, trackio_space_id, dataset repos, model repos, or Spaces. If the user explicitly requests an org namespace or a tool provides an allowed namespace, use that explicit namespace instead. Never leave placeholders such as <username>, <model-name>, <project>, TODO, or similar placeholder values in scripts, tool arguments, repo IDs, or final answers. If session context says User=unknown because identity lookup failed or no token is available in this runtime, do not guess the namespace; ask for it before creating Hub resources.
12
+
13
+ # Tool calling contract
14
+
15
+ The active tool schema is the source of truth. Use only tools that are actually available in the current tool list.
16
+ Do not simulate tool calls in prose or fenced code blocks. Call tools through the tool interface with valid JSON arguments matching the tool schema.
17
+ Before every tool call, check required arguments, enum values, mutually exclusive fields, and whether paths are local machine paths, sandbox paths, Hub repo IDs, or URLs.
18
+ After every tool call, inspect the returned result before deciding the next action. Do not claim success unless the tool result confirms it.
19
+ If a tool is unavailable or fails repeatedly for the same reason, switch to another available approach or report the blocker.
20
+
21
  # Your knowledge of HF libraries is outdated
22
 
23
  You do not know current APIs for TRL, Transformers, PEFT, Trackio, or other HF libraries. Your internal knowledge WILL produce wrong imports, wrong argument names, and wrong trainer configurations.
 
57
 
58
  SILENT DATASET SUBSTITUTION: When a requested dataset fails to load, you will silently switch to a different one without telling the user. Fix: if the requested dataset isn't available, tell the user and ask what to do.
59
 
60
+ ALWAYS USE HUB KERNELS, NEVER COMPILE FLASH-ATTN: Do NOT pip install `flash-attn` and do NOT use `attn_implementation="flash_attention_2"` because that requires the compiled flash-attn package and often fails on the job's CUDA/PyTorch combo. For accelerated attention, use the HF `kernels` library and load a prebuilt attention kernel from the Hub via `attn_implementation`. Examples: `AutoModelForCausalLM.from_pretrained(..., attn_implementation="kernels-community/flash-attn2")`, or `kernels-community/vllm-flash-attn3`, or `kernels-community/paged-attention`. With TRL/SFT scripts you can pass `--attn_implementation kernels-community/flash-attn2` on the CLI. Flash-attention Hub kernels require Ampere-or-newer GPUs unless their docs say otherwise: never choose T4 sandboxes or T4 HF Jobs for scripts that use a flash-attention kernel, because T4 is pre-Ampere. Use A10G, A100, H100, or another compatible newer GPU, or choose a non-flash Hub kernel if T4 is required. Search additional kernels at https://huggingface.co/models?other=kernel.
61
+
62
+ CORE ML DEPENDENCY FRESHNESS: Do not rely on preinstalled packages in sandboxes or HF Jobs. Before model-loading, training, or inference work, explicitly install or upgrade the latest compatible core stack in the sandbox: `torch`, `transformers`, `trl`, `accelerate`, `datasets`, `trackio`, and `kernels~=0.12.0` when using Hub kernels. Include the same packages in `hf_jobs.dependencies`. Use unpinned latest stable versions by default for the rest of the core stack; constrain `kernels` to `kernels~=0.12.0`. Pin other versions only when current docs/examples require a specific compatibility set or a smoke test shows latest is incompatible. Print the installed versions before model loading. If `kernels` and `transformers` are incompatible, fix the package set using current docs/examples or choose another compatible Hub kernel, then rerun the smoke test. Do NOT fall back to default attention or compiled flash-attn as a shortcut.
63
 
64
  SCOPE-CHANGING FIXES: Avoid at all costs! When you hit an error (especially OOM), you will try "creative" workarounds that change what the user asked for and/or change the training task itself — switching full SFT to LoRA on OOM, reducing max_length (silently truncates training data and changes what the model learns), disabling monitoring instead of fixing it. Do not do this. Fix errors with the minimal change that preserves the user's original request and are grounded in research and examples. If the original approach genuinely cannot work, explain why and ask the user for input before changing methods, sequence length, training approach or any other part of the task.
65
 
 
83
  report_to="trackio"
84
  run_name="<descriptive-run-name>" # e.g. "sft_qwen3-4b_lr2e-5_bs128"
85
  project="<descriptive-project-name>" # keeps related runs grouped so you can compare them
86
+ trackio_space_id="<username>/ml-intern-<8-char-id>" # pattern only: replace <username> with the resolved namespace, e.g. alice/ml-intern-a1b2c3d4
87
  `project` and `trackio_space_id` can also be set via TRACKIO_PROJECT / TRACKIO_SPACE_ID env vars.
88
 
89
  Alerts are how iterations decide what to change. Use trackio.alert(title, text, level) at every decision point in training. Levels:
 
125
  - a public/raw URL
126
  If you wrote or tested a script locally, read the file content and submit it inline, or write it into the sandbox first.
127
 
128
+ For non-trivial hf_jobs scripts, use an exact-source workflow:
129
+ 1. Write the script in the session sandbox.
130
+ 2. Run syntax/import validation.
131
+ 3. Run a tiny smoke test with the same entrypoint, dependencies, dataset columns, model-loading path, and relevant precision/attention settings. For training scripts, make sure one training step succeeds, plus one evaluation step when the final workflow includes evaluation or an eval split is available.
132
+ 4. Submit the exact tested script source or the exact tested sandbox file. Do not reconstruct a similar script from memory.
133
+
134
+ Every training script must fail fast before expensive work:
135
+ - print package versions for torch, transformers, trl, accelerate, datasets, trackio, and kernels when used
136
+ - assert required dataset columns exist
137
+ - assert hub_model_id and trackio_space_id contain no placeholders
138
+ - assert push_to_hub=True and hub_model_id are set
139
+ - include every imported third-party package in hf_jobs.dependencies
140
+ - include the core ML stack in hf_jobs.dependencies: torch, transformers, trl, accelerate, datasets, trackio, and kernels~=0.12.0 when using Hub kernels; also include any actually used extras such as peft, bitsandbytes, sentencepiece, or protobuf
141
+
142
+ Never leave placeholder values such as <username>, <model-name>, <project>, TODO, or similar unfinished values in hf_jobs scripts or hf_jobs arguments.
143
+
144
+ GPU preflight is mandatory before hf_jobs when the job will run on GPU, or when the script loads a model, uses CUDA, bf16/fp16, quantization, flash attention, or torch.compile. First create a GPU sandbox with sandbox_create (t4-small minimum for non-flash workloads; for flash-attention kernels use Ampere-or-newer hardware, never T4), run a tiny smoke test there using the same imports, model-loading path, training entrypoint, and a tiny dataset/subset, then fix failures before submitting. If you skip GPU sandbox preflight, state why before calling hf_jobs.
145
 
146
  Before calling hf_jobs, output a pre-flight check:
147
  - Reference implementation: [which example you based this on]
 
201
 
202
  # Autonomous / headless mode
203
 
204
+ {% if autonomous_mode %}
205
+ Autonomous mode is active for this session because the runtime marked it as autonomous, headless, benchmarked, or fixed-time-budget. Apply this section even if the user prompt does not contain those words.
206
+
207
  When running autonomously (no human in the loop), you MUST follow these rules:
208
 
209
  NEVER respond with only text. Every response MUST include at least one tool call. If you have nothing to do, check the plan, verify outputs or plan ahead. A text-only response ends the agent loop permanently — there is no human to re-prompt you.
 
229
  The task is NOT done until:
230
  - The required output exists (e.g. final model, metrics reached, dataset updated etc)
231
  - You have evaluated the model and confirmed it works
232
+ {% else %}
233
+ Autonomous mode is not active for this session. In normal interactive chat, text-only answers are allowed for simple questions, and you should stop once the user's request is satisfied.
234
+ {% endif %}
235
 
236
  # Communication
237
 
agent/tools/jobs_tool.py CHANGED
@@ -1105,14 +1105,41 @@ HF_JOBS_TOOL_SPEC = {
1105
  "- You MUST have called github_find_examples + github_read_file to find a working reference implementation. "
1106
  "Scripts based on your internal knowledge WILL use outdated APIs and fail.\n"
1107
  "- You MUST have validated dataset format via hf_inspect_dataset or hub_repo_details.\n"
 
 
 
 
 
1108
  "- If the job runs on GPU, or the script loads a model, uses CUDA, bf16/fp16, quantization, flash attention, "
1109
  "or torch.compile, you MUST create a GPU sandbox with sandbox_create first, run a tiny smoke test there, "
1110
  "and fix failures before submitting. If skipped, state why before calling hf_jobs.\n"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1111
  "- Training config MUST include push_to_hub=True and hub_model_id. "
1112
  "Job storage is EPHEMERAL — all files are deleted when the job ends. Without push_to_hub, trained models are lost permanently.\n"
 
 
 
 
 
 
 
1113
  "- Include trackio monitoring and provide the dashboard URL to the user. "
1114
  "When the script uses report_to='trackio', also pass `trackio_space_id` "
1115
- "(e.g. '<username>/ml-intern-<8char>') and `trackio_project` as tool args — "
 
1116
  "they are injected as TRACKIO_SPACE_ID/TRACKIO_PROJECT env vars and let the UI embed the live dashboard.\n\n"
1117
  "BATCH/ABLATION JOBS: Submit ONE job first. Check logs to confirm it starts training successfully. "
1118
  "Only then submit the remaining jobs. Never submit all at once — if there's a bug, all jobs fail.\n\n"
@@ -1126,8 +1153,8 @@ HF_JOBS_TOOL_SPEC = {
1126
  "3. Upgrade to larger GPU (a10g→a100→h100)\n"
1127
  "Do NOT switch training methods (e.g. full SFT to LoRA) or reduce max_length — those change what the user gets and require explicit approval.\n\n"
1128
  "Examples:\n"
1129
- "Training: {'operation': 'run', 'script': '/app/train.py', 'dependencies': ['transformers', 'trl', 'torch', 'datasets', 'trackio'], 'hardware_flavor': 'a100-large', 'timeout': '8h'}\n"
1130
- "Monitor: {'operation': 'ps'}, {'operation': 'logs', 'job_id': 'xxx'}, {'operation': 'cancel', 'job_id': 'xxx'}"
1131
  "Docker: {'operation': 'run', 'command': ['duckdb', '-c', 'select 1 + 2'], 'image': 'duckdb/duckdb', 'hardware_flavor': 'cpu-basic', 'timeout': '1h'}\n"
1132
  ),
1133
  "parameters": {
@@ -1155,7 +1182,9 @@ HF_JOBS_TOOL_SPEC = {
1155
  "description": (
1156
  "Python code, sandbox file path (e.g. '/app/train.py', './train.py', or bare 'train.py'), or URL. "
1157
  "Triggers Python mode. For ML training: base this on a working example found via github_find_examples, not on internal knowledge. "
 
1158
  "For GPU/model-loading training scripts, smoke-test in a GPU sandbox before submission. "
 
1159
  "Mutually exclusive with 'command'."
1160
  ),
1161
  },
@@ -1164,7 +1193,10 @@ HF_JOBS_TOOL_SPEC = {
1164
  "items": {"type": "string"},
1165
  "description": (
1166
  "Pip packages to install. Include ALL required packages. "
1167
- "Common training set: ['transformers', 'trl', 'torch', 'datasets', 'trackio', 'accelerate']. "
 
 
 
1168
  "Only used with 'script'."
1169
  ),
1170
  },
@@ -1201,7 +1233,7 @@ HF_JOBS_TOOL_SPEC = {
1201
  "type": "string",
1202
  "description": (
1203
  "Optional. The HF Space hosting the trackio dashboard for this run "
1204
- "(e.g. '<username>/ml-intern-<8char>', under YOUR HF namespace). "
1205
  "Injected as TRACKIO_SPACE_ID env var and used by the UI to embed "
1206
  "the live dashboard. Set this whenever the script uses "
1207
  "report_to='trackio'. The Space is auto-created and seeded with the "
 
1105
  "- You MUST have called github_find_examples + github_read_file to find a working reference implementation. "
1106
  "Scripts based on your internal knowledge WILL use outdated APIs and fail.\n"
1107
  "- You MUST have validated dataset format via hf_inspect_dataset or hub_repo_details.\n"
1108
+ "- For non-trivial scripts, write the script in the session sandbox, run syntax/import validation, "
1109
+ "run a tiny smoke test, and for training scripts make sure one training step succeeds, plus one "
1110
+ "evaluation step when the final workflow includes evaluation or an eval split is available, then "
1111
+ "submit the exact tested script source or exact tested sandbox file. "
1112
+ "Do NOT reconstruct a similar script from memory.\n"
1113
  "- If the job runs on GPU, or the script loads a model, uses CUDA, bf16/fp16, quantization, flash attention, "
1114
  "or torch.compile, you MUST create a GPU sandbox with sandbox_create first, run a tiny smoke test there, "
1115
  "and fix failures before submitting. If skipped, state why before calling hf_jobs.\n"
1116
+ "- Do NOT install compiled flash-attn or use attn_implementation='flash_attention_2'. "
1117
+ "For accelerated attention, use the HF kernels package with a Hub kernel such as "
1118
+ "kernels-community/flash-attn2, and smoke-test the exact same attn_implementation. "
1119
+ "Flash-attention Hub kernels require Ampere-or-newer GPUs unless their docs say otherwise: "
1120
+ "never choose T4 sandboxes or T4 HF Jobs for scripts that use a flash-attention kernel, "
1121
+ "because T4 is pre-Ampere. Use A10G, A100, H100, or another compatible newer GPU.\n"
1122
+ "- Do NOT rely on preinstalled ML packages. Install/upgrade the latest compatible core stack "
1123
+ "in the sandbox and include the same packages in dependencies: torch, transformers, trl, "
1124
+ "accelerate, datasets, trackio, and kernels~=0.12.0 when using Hub kernels. "
1125
+ "Use unpinned latest stable versions by default for the rest of the core stack; constrain "
1126
+ "kernels to kernels~=0.12.0. Pin other versions only when current docs/examples require a specific "
1127
+ "compatibility set or a smoke test shows latest is incompatible. Print installed versions "
1128
+ "before model loading. If kernels and transformers are incompatible, fix the package set "
1129
+ "or choose another compatible Hub kernel, then rerun the smoke test.\n"
1130
  "- Training config MUST include push_to_hub=True and hub_model_id. "
1131
  "Job storage is EPHEMERAL — all files are deleted when the job ends. Without push_to_hub, trained models are lost permanently.\n"
1132
+ "- Training scripts MUST fail fast on missing dataset columns, placeholder repo IDs, placeholder Trackio IDs, "
1133
+ "missing hub_model_id, or missing push_to_hub=True.\n"
1134
+ "- Do NOT leave placeholders such as <username>, <model-name>, <project>, TODO, "
1135
+ "or similar unfinished values in scripts or job arguments.\n"
1136
+ "- dependencies MUST include every imported third-party package, including the core ML stack "
1137
+ "torch, transformers, trl, accelerate, datasets, trackio, kernels~=0.12.0 when using Hub kernels, "
1138
+ "and extras such as peft, bitsandbytes, sentencepiece, or protobuf when used.\n"
1139
  "- Include trackio monitoring and provide the dashboard URL to the user. "
1140
  "When the script uses report_to='trackio', also pass `trackio_space_id` "
1141
+ "(pattern only: '<username>/ml-intern-<8char>'; replace <username>, e.g. 'alice/ml-intern-a1b2c3d4') "
1142
+ "and `trackio_project` as tool args — "
1143
  "they are injected as TRACKIO_SPACE_ID/TRACKIO_PROJECT env vars and let the UI embed the live dashboard.\n\n"
1144
  "BATCH/ABLATION JOBS: Submit ONE job first. Check logs to confirm it starts training successfully. "
1145
  "Only then submit the remaining jobs. Never submit all at once — if there's a bug, all jobs fail.\n\n"
 
1153
  "3. Upgrade to larger GPU (a10g→a100→h100)\n"
1154
  "Do NOT switch training methods (e.g. full SFT to LoRA) or reduce max_length — those change what the user gets and require explicit approval.\n\n"
1155
  "Examples:\n"
1156
+ "Training: {'operation': 'run', 'script': '/app/train.py', 'dependencies': ['torch', 'transformers', 'trl', 'accelerate', 'datasets', 'trackio', 'kernels~=0.12.0'], 'hardware_flavor': 'a100-large', 'timeout': '8h'}\n"
1157
+ "Monitor: {'operation': 'ps'}, {'operation': 'logs', 'job_id': 'xxx'}, {'operation': 'cancel', 'job_id': 'xxx'}\n"
1158
  "Docker: {'operation': 'run', 'command': ['duckdb', '-c', 'select 1 + 2'], 'image': 'duckdb/duckdb', 'hardware_flavor': 'cpu-basic', 'timeout': '1h'}\n"
1159
  ),
1160
  "parameters": {
 
1182
  "description": (
1183
  "Python code, sandbox file path (e.g. '/app/train.py', './train.py', or bare 'train.py'), or URL. "
1184
  "Triggers Python mode. For ML training: base this on a working example found via github_find_examples, not on internal knowledge. "
1185
+ "For non-trivial scripts, submit the exact tested script source or exact tested sandbox file. "
1186
  "For GPU/model-loading training scripts, smoke-test in a GPU sandbox before submission. "
1187
+ "Do not leave placeholders such as <username>, <model-name>, <project>, or TODO. "
1188
  "Mutually exclusive with 'command'."
1189
  ),
1190
  },
 
1193
  "items": {"type": "string"},
1194
  "description": (
1195
  "Pip packages to install. Include ALL required packages. "
1196
+ "Common training set: ['torch', 'transformers', 'trl', 'accelerate', 'datasets', 'trackio', 'kernels~=0.12.0']. "
1197
+ "Use unpinned latest stable versions by default for the rest of the core stack; constrain kernels to kernels~=0.12.0. "
1198
+ "Pin other versions only when current docs/examples require a compatibility set or a smoke test shows latest is incompatible. "
1199
+ "Must include every imported third-party package and any used extras such as peft, bitsandbytes, sentencepiece, or protobuf. "
1200
  "Only used with 'script'."
1201
  ),
1202
  },
 
1233
  "type": "string",
1234
  "description": (
1235
  "Optional. The HF Space hosting the trackio dashboard for this run "
1236
+ "(pattern only: '<username>/ml-intern-<8char>'; replace <username>, e.g. 'alice/ml-intern-a1b2c3d4'). "
1237
  "Injected as TRACKIO_SPACE_ID env var and used by the UI to embed "
1238
  "the live dashboard. Set this whenever the script uses "
1239
  "report_to='trackio'. The Space is auto-created and seeded with the "
backend/dependencies.py CHANGED
@@ -31,7 +31,7 @@ DEV_USER: dict[str, Any] = {
31
  "user_id": "dev",
32
  "username": "dev",
33
  "authenticated": True,
34
- "plan": "pro", # Dev uses the Pro web default model.
35
  }
36
 
37
  INTERNAL_HF_TOKEN_KEY = "_hf_token"
 
31
  "user_id": "dev",
32
  "username": "dev",
33
  "authenticated": True,
34
+ "plan": "pro",
35
  }
36
 
37
  INTERNAL_HF_TOKEN_KEY = "_hf_token"
backend/routes/agent.py CHANGED
@@ -58,10 +58,10 @@ from agent.core.llm_params import _resolve_llm_params
58
  from agent.core.model_ids import (
59
  CLAUDE_OPUS_48_MODEL_ID,
60
  DEEPSEEK_V4_PRO_MODEL_ID,
61
- GLM_51_MODEL_ID,
62
  GPT_55_MODEL_ID,
63
- KIMI_K26_MODEL_ID,
64
- MINIMAX_M27_MODEL_ID,
65
  strip_huggingface_model_prefix,
66
  )
67
  from agent.core.prompt_caching import with_prompt_cache_params
@@ -72,9 +72,8 @@ logger = logging.getLogger(__name__)
72
  router = APIRouter(prefix="/api", tags=["agent"])
73
  _background_route_tasks: set[asyncio.Task] = set()
74
 
75
- DEFAULT_OPUS_MODEL_ID = CLAUDE_OPUS_48_MODEL_ID
76
  DEFAULT_GPT_MODEL_ID = GPT_55_MODEL_ID
77
- DEFAULT_FREE_MODEL_ID = KIMI_K26_MODEL_ID
78
  DATASET_UPLOAD_MULTIPART_SLACK_BYTES = 1024 * 1024
79
 
80
 
@@ -120,35 +119,29 @@ def _schedule_usage_refresh_and_upload(
120
  def _available_models() -> list[dict[str, Any]]:
121
  models = [
122
  {
123
- "id": DEFAULT_OPUS_MODEL_ID,
124
  "label": "Claude Opus 4.8",
125
- "provider": "huggingface",
126
- "recommended": True,
127
  },
128
  {
129
  "id": DEFAULT_GPT_MODEL_ID,
130
  "label": "GPT-5.5",
131
- "provider": "huggingface",
132
  },
133
  {
134
- "id": DEFAULT_FREE_MODEL_ID,
135
- "label": "Kimi K2.6",
136
- "provider": "huggingface",
137
  },
138
  {
139
- "id": MINIMAX_M27_MODEL_ID,
140
- "label": "MiniMax M2.7",
141
- "provider": "huggingface",
142
  },
143
  {
144
- "id": GLM_51_MODEL_ID,
145
- "label": "GLM 5.1",
146
- "provider": "huggingface",
147
  },
148
  {
149
  "id": DEEPSEEK_V4_PRO_MODEL_ID,
150
  "label": "DeepSeek V4 Pro",
151
- "provider": "huggingface",
152
  },
153
  ]
154
  return models
@@ -167,20 +160,16 @@ def _validate_model_id(model_id: str | None) -> None:
167
  raise HTTPException(status_code=400, detail=f"Unknown model: {model_id}")
168
 
169
 
170
- def _default_model_for_user(user: dict[str, Any]) -> str:
171
- return DEFAULT_OPUS_MODEL_ID if user.get("plan") == "pro" else DEFAULT_FREE_MODEL_ID
172
 
173
 
174
- async def _model_override_for_new_session(
175
- requested_model: str | None,
176
- user: dict[str, Any],
177
- ) -> str | None:
178
  """Return the model override to use when creating a new session.
179
 
180
- Explicit model requests are honored. Empty web requests default to Kimi for
181
- non-Pro users and Opus for Pro users.
182
  """
183
- return requested_model or _default_model_for_user(user)
184
 
185
 
186
  def _user_hf_token(user: dict[str, Any] | None) -> str | None:
@@ -292,18 +281,22 @@ async def health_check() -> HealthResponse:
292
 
293
 
294
  @router.get("/health/llm", response_model=LLMHealthResponse)
295
- async def llm_health_check(request: Request) -> LLMHealthResponse:
 
 
 
296
  """Check if the LLM provider is reachable and the API key is valid.
297
 
298
- Makes a minimal 1-token completion call when a token is available. For
299
- token-less HF Router requests, returns ``status="skipped"`` instead of
300
- making an unauthenticated probe. Catches common errors:
 
301
  - 401 → invalid API key
302
  - 402/insufficient_quota → out of credits
303
  - 429 → rate limited
304
  - timeout / network → provider unreachable
305
  """
306
- model = session_manager.config.model_name
307
  hf_token = resolve_hf_request_token(request)
308
  if _model_requires_hf_router_token(model) and not hf_token:
309
  return LLMHealthResponse(status="skipped", model=model)
@@ -442,7 +435,7 @@ async def create_session(
442
  behalf of the user.
443
 
444
  Optional body ``{"model"?: <id>}`` selects the session's LLM; unknown
445
- ids are rejected (400). Empty requests use the plan-aware web default.
446
 
447
  Returns 503 if the server or user has reached the session limit.
448
  """
@@ -460,8 +453,8 @@ async def create_session(
460
 
461
  _validate_model_id(model)
462
 
463
- # Empty requests use the plan-aware web default.
464
- model = await _model_override_for_new_session(model, user)
465
 
466
  try:
467
  session_id = await session_manager.create_session(
@@ -494,7 +487,7 @@ async def restore_session_summary(
494
  session's context as a user-role system note.
495
 
496
  Optional ``"model"`` in the body overrides the session's LLM; otherwise
497
- the new session uses the plan-aware web default.
498
  """
499
  messages = body.get("messages")
500
  if not isinstance(messages, list) or not messages:
@@ -505,7 +498,7 @@ async def restore_session_summary(
505
  model = body.get("model")
506
  _validate_model_id(model)
507
 
508
- model = await _model_override_for_new_session(model, user)
509
 
510
  try:
511
  session_id = await session_manager.create_session(
@@ -562,9 +555,9 @@ async def activate_session(
562
  request: Request,
563
  user: dict = Depends(get_current_user),
564
  ) -> SessionInfo:
565
- """Mark a session as actively revisited and reset its usage meter window."""
566
  await _check_session_access(session_id, user, request)
567
- info = await _reset_usage_window(session_id)
568
  if not info:
569
  raise HTTPException(status_code=404, detail="Session not found")
570
  return SessionInfo(**info)
 
58
  from agent.core.model_ids import (
59
  CLAUDE_OPUS_48_MODEL_ID,
60
  DEEPSEEK_V4_PRO_MODEL_ID,
61
+ GLM_52_MODEL_ID,
62
  GPT_55_MODEL_ID,
63
+ KIMI_K27_CODE_MODEL_ID,
64
+ MINIMAX_M3_MODEL_ID,
65
  strip_huggingface_model_prefix,
66
  )
67
  from agent.core.prompt_caching import with_prompt_cache_params
 
72
  router = APIRouter(prefix="/api", tags=["agent"])
73
  _background_route_tasks: set[asyncio.Task] = set()
74
 
 
75
  DEFAULT_GPT_MODEL_ID = GPT_55_MODEL_ID
76
+ DEFAULT_MODEL_ID = GLM_52_MODEL_ID
77
  DATASET_UPLOAD_MULTIPART_SLACK_BYTES = 1024 * 1024
78
 
79
 
 
119
  def _available_models() -> list[dict[str, Any]]:
120
  models = [
121
  {
122
+ "id": CLAUDE_OPUS_48_MODEL_ID,
123
  "label": "Claude Opus 4.8",
 
 
124
  },
125
  {
126
  "id": DEFAULT_GPT_MODEL_ID,
127
  "label": "GPT-5.5",
 
128
  },
129
  {
130
+ "id": KIMI_K27_CODE_MODEL_ID,
131
+ "label": "Kimi K2.7 Code",
 
132
  },
133
  {
134
+ "id": MINIMAX_M3_MODEL_ID,
135
+ "label": "MiniMax M3",
 
136
  },
137
  {
138
+ "id": DEFAULT_MODEL_ID,
139
+ "label": "GLM 5.2",
140
+ "recommended": True,
141
  },
142
  {
143
  "id": DEEPSEEK_V4_PRO_MODEL_ID,
144
  "label": "DeepSeek V4 Pro",
 
145
  },
146
  ]
147
  return models
 
160
  raise HTTPException(status_code=400, detail=f"Unknown model: {model_id}")
161
 
162
 
163
+ def _default_model() -> str:
164
+ return DEFAULT_MODEL_ID
165
 
166
 
167
+ def _model_override_for_new_session(requested_model: str | None) -> str | None:
 
 
 
168
  """Return the model override to use when creating a new session.
169
 
170
+ Explicit model requests are honored. Empty web requests default to GLM 5.2.
 
171
  """
172
+ return requested_model or _default_model()
173
 
174
 
175
  def _user_hf_token(user: dict[str, Any] | None) -> str | None:
 
281
 
282
 
283
  @router.get("/health/llm", response_model=LLMHealthResponse)
284
+ async def llm_health_check(
285
+ request: Request,
286
+ user: dict = Depends(get_current_user),
287
+ ) -> LLMHealthResponse:
288
  """Check if the LLM provider is reachable and the API key is valid.
289
 
290
+ Makes a minimal 1-token completion call against the authenticated user's
291
+ default model when a token is available. For token-less HF Router requests,
292
+ returns ``status="skipped"`` instead of making an unauthenticated probe.
293
+ Catches common errors:
294
  - 401 → invalid API key
295
  - 402/insufficient_quota → out of credits
296
  - 429 → rate limited
297
  - timeout / network → provider unreachable
298
  """
299
+ model = _default_model()
300
  hf_token = resolve_hf_request_token(request)
301
  if _model_requires_hf_router_token(model) and not hf_token:
302
  return LLMHealthResponse(status="skipped", model=model)
 
435
  behalf of the user.
436
 
437
  Optional body ``{"model"?: <id>}`` selects the session's LLM; unknown
438
+ ids are rejected (400). Empty requests use the web default.
439
 
440
  Returns 503 if the server or user has reached the session limit.
441
  """
 
453
 
454
  _validate_model_id(model)
455
 
456
+ # Empty requests use the web default.
457
+ model = _model_override_for_new_session(model)
458
 
459
  try:
460
  session_id = await session_manager.create_session(
 
487
  session's context as a user-role system note.
488
 
489
  Optional ``"model"`` in the body overrides the session's LLM; otherwise
490
+ the new session uses the web default.
491
  """
492
  messages = body.get("messages")
493
  if not isinstance(messages, list) or not messages:
 
498
  model = body.get("model")
499
  _validate_model_id(model)
500
 
501
+ model = _model_override_for_new_session(model)
502
 
503
  try:
504
  session_id = await session_manager.create_session(
 
555
  request: Request,
556
  user: dict = Depends(get_current_user),
557
  ) -> SessionInfo:
558
+ """Mark a session as actively revisited without resetting usage."""
559
  await _check_session_access(session_id, user, request)
560
+ info = await session_manager.activate_session(session_id)
561
  if not info:
562
  raise HTTPException(status_code=404, detail="Session not found")
563
  return SessionInfo(**info)
backend/session_manager.py CHANGED
@@ -13,7 +13,7 @@ from typing import Any, Optional
13
  from agent.config import load_config
14
  from agent.core.agent_loop import process_submission
15
  from agent.core.model_ids import (
16
- KIMI_K26_MODEL_ID,
17
  is_known_router_model_id,
18
  strip_huggingface_model_prefix,
19
  )
@@ -269,7 +269,7 @@ class SessionManager:
269
  if normalized and is_known_router_model_id(normalized):
270
  return normalized
271
 
272
- fallback_model = KIMI_K26_MODEL_ID
273
  logger.warning(
274
  "Saved session model %r failed validation; using %r",
275
  model,
@@ -2012,6 +2012,22 @@ class SessionManager:
2012
  )
2013
  return self.get_session_info(session_id)
2014
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2015
  def set_notification_destinations(
2016
  self, session_id: str, destinations: list[str]
2017
  ) -> list[str]:
 
13
  from agent.config import load_config
14
  from agent.core.agent_loop import process_submission
15
  from agent.core.model_ids import (
16
+ GLM_52_MODEL_ID,
17
  is_known_router_model_id,
18
  strip_huggingface_model_prefix,
19
  )
 
269
  if normalized and is_known_router_model_id(normalized):
270
  return normalized
271
 
272
+ fallback_model = GLM_52_MODEL_ID
273
  logger.warning(
274
  "Saved session model %r failed validation; using %r",
275
  model,
 
2012
  )
2013
  return self.get_session_info(session_id)
2014
 
2015
+ async def activate_session(self, session_id: str) -> dict[str, Any] | None:
2016
+ """Mark a session as revisited without resetting its usage window."""
2017
+ agent_session = self.sessions.get(session_id)
2018
+ if not agent_session:
2019
+ return None
2020
+
2021
+ self._touch(agent_session)
2022
+
2023
+ store = self._store()
2024
+ if getattr(store, "enabled", False):
2025
+ await store.update_session_fields(
2026
+ session_id,
2027
+ last_active_at=agent_session.last_active_at,
2028
+ )
2029
+ return self.get_session_info(session_id)
2030
+
2031
  def set_notification_destinations(
2032
  self, session_id: str, destinations: list[str]
2033
  ) -> list[str]:
configs/cli_agent_config.json CHANGED
@@ -1,5 +1,5 @@
1
  {
2
- "model_name": "anthropic/claude-opus-4.8:fal-ai",
3
  "save_sessions": true,
4
  "session_dataset_repo": "smolagents/ml-intern-sessions",
5
  "share_traces": true,
 
1
  {
2
+ "model_name": "zai-org/GLM-5.2:novita",
3
  "save_sessions": true,
4
  "session_dataset_repo": "smolagents/ml-intern-sessions",
5
  "share_traces": true,
configs/frontend_agent_config.json CHANGED
@@ -1,5 +1,5 @@
1
  {
2
- "model_name": "${ML_INTERN_DEFAULT_MODEL_ID:-moonshotai/Kimi-K2.6}",
3
  "save_sessions": true,
4
  "session_dataset_repo": "smolagents/ml-intern-sessions",
5
  "share_traces": true,
 
1
  {
2
+ "model_name": "${ML_INTERN_DEFAULT_MODEL_ID:-zai-org/GLM-5.2:novita}",
3
  "save_sessions": true,
4
  "session_dataset_repo": "smolagents/ml-intern-sessions",
5
  "share_traces": true,
frontend/src/components/Chat/ChatInput.tsx CHANGED
@@ -26,10 +26,10 @@ import { useSessionStore } from '@/store/sessionStore';
26
  import {
27
  CLAUDE_OPUS_48_MODEL_PATH,
28
  DEEPSEEK_V4_PRO_MODEL_PATH,
29
- GLM_51_MODEL_PATH,
30
  GPT_55_MODEL_PATH,
31
- KIMI_K26_MODEL_PATH,
32
- MINIMAX_M27_MODEL_PATH,
33
  isClaudePath,
34
  } from '@/utils/model';
35
 
@@ -53,7 +53,6 @@ const DEFAULT_MODEL_OPTIONS: ModelOption[] = [
53
  name: 'Claude Opus 4.8',
54
  modelPath: CLAUDE_OPUS_48_MODEL_PATH,
55
  avatarUrl: getHfAvatarUrl(CLAUDE_OPUS_48_MODEL_PATH),
56
- recommended: true,
57
  },
58
  {
59
  id: 'gpt-5.5',
@@ -62,22 +61,23 @@ const DEFAULT_MODEL_OPTIONS: ModelOption[] = [
62
  avatarUrl: getHfAvatarUrl(GPT_55_MODEL_PATH),
63
  },
64
  {
65
- id: 'kimi-k2.6',
66
- name: 'Kimi K2.6',
67
- modelPath: KIMI_K26_MODEL_PATH,
68
- avatarUrl: getHfAvatarUrl(KIMI_K26_MODEL_PATH),
69
  },
70
  {
71
- id: 'minimax-m2.7',
72
- name: 'MiniMax M2.7',
73
- modelPath: MINIMAX_M27_MODEL_PATH,
74
- avatarUrl: getHfAvatarUrl('MiniMaxAI/MiniMax-M2.7'),
75
  },
76
  {
77
- id: 'glm-5.1',
78
- name: 'GLM 5.1',
79
- modelPath: GLM_51_MODEL_PATH,
80
- avatarUrl: getHfAvatarUrl('zai-org/GLM-5.1'),
 
81
  },
82
  {
83
  id: 'deepseek-v4-pro',
@@ -87,7 +87,7 @@ const DEFAULT_MODEL_OPTIONS: ModelOption[] = [
87
  },
88
  ];
89
 
90
- const DEFAULT_FREE_MODEL_OPTION_ID = 'kimi-k2.6';
91
 
92
  const normalizeModelPath = (path: string | undefined) => (
93
  (path ?? '')
@@ -124,7 +124,6 @@ const modelOptionId = (modelPath: string) => (
124
  const modelOptionFromApi = (model: {
125
  id?: string;
126
  label?: string;
127
- provider?: string;
128
  recommended?: boolean;
129
  }): ModelOption | null => {
130
  if (!model.id) return null;
@@ -199,10 +198,10 @@ export default function ChatInput({ sessionId, initialModelPath, onSend, onStop,
199
  const [modelOptions, setModelOptions] = useState<ModelOption[]>(DEFAULT_MODEL_OPTIONS);
200
  const modelOptionsRef = useRef<ModelOption[]>(DEFAULT_MODEL_OPTIONS);
201
  const sessionIdRef = useRef<string | undefined>(sessionId);
202
- const [selectedModelId, setSelectedModelId] = useState<string>(
203
  () => (
204
- findModelByPath(initialModelPath ?? '', DEFAULT_MODEL_OPTIONS)?.id
205
- ?? DEFAULT_FREE_MODEL_OPTION_ID
206
  ),
207
  );
208
  const [modelAnchorEl, setModelAnchorEl] = useState<null | HTMLElement>(null);
@@ -239,7 +238,7 @@ export default function ChatInput({ sessionId, initialModelPath, onSend, onStop,
239
  setModelOptions(next);
240
  if (!sessionIdRef.current) {
241
  const current = data.current ? findModelByPath(data.current, next) : null;
242
- if (current) setSelectedModelId(current.id);
243
  }
244
  })
245
  .catch(() => { /* ignore */ });
@@ -257,7 +256,7 @@ export default function ChatInput({ sessionId, initialModelPath, onSend, onStop,
257
  if (cancelled) return;
258
  if (data?.model) {
259
  const model = findModelByPath(data.model, modelOptionsRef.current);
260
- if (model) setSelectedModelId(model.id);
261
  updateSessionModel(sessionId, data.model);
262
  }
263
  })
@@ -267,8 +266,10 @@ export default function ChatInput({ sessionId, initialModelPath, onSend, onStop,
267
 
268
  const visibleModelOptions = modelOptions;
269
  const selectedModel = (
270
- visibleModelOptions.find(m => m.id === selectedModelId)
271
- || modelOptions.find(m => m.id === selectedModelId)
 
 
272
  || visibleModelOptions[0]
273
  || modelOptions[0]
274
  );
@@ -389,7 +390,7 @@ export default function ChatInput({ sessionId, initialModelPath, onSend, onStop,
389
  body: JSON.stringify({ model: model.modelPath }),
390
  });
391
  if (res.ok) {
392
- setSelectedModelId(model.id);
393
  updateSessionModel(sessionId, model.modelPath);
394
  setModelSwitchError(null);
395
  return;
@@ -706,7 +707,7 @@ export default function ChatInput({ sessionId, initialModelPath, onSend, onStop,
706
  <MenuItem
707
  key={model.id}
708
  onClick={() => handleSelectModel(model)}
709
- selected={selectedModelId === model.id}
710
  sx={{
711
  py: 1.5,
712
  '&.Mui-selected': {
 
26
  import {
27
  CLAUDE_OPUS_48_MODEL_PATH,
28
  DEEPSEEK_V4_PRO_MODEL_PATH,
29
+ GLM_52_MODEL_PATH,
30
  GPT_55_MODEL_PATH,
31
+ KIMI_K27_CODE_MODEL_PATH,
32
+ MINIMAX_M3_MODEL_PATH,
33
  isClaudePath,
34
  } from '@/utils/model';
35
 
 
53
  name: 'Claude Opus 4.8',
54
  modelPath: CLAUDE_OPUS_48_MODEL_PATH,
55
  avatarUrl: getHfAvatarUrl(CLAUDE_OPUS_48_MODEL_PATH),
 
56
  },
57
  {
58
  id: 'gpt-5.5',
 
61
  avatarUrl: getHfAvatarUrl(GPT_55_MODEL_PATH),
62
  },
63
  {
64
+ id: 'kimi-k2.7-code',
65
+ name: 'Kimi K2.7 Code',
66
+ modelPath: KIMI_K27_CODE_MODEL_PATH,
67
+ avatarUrl: getHfAvatarUrl(KIMI_K27_CODE_MODEL_PATH),
68
  },
69
  {
70
+ id: 'minimax-m3',
71
+ name: 'MiniMax M3',
72
+ modelPath: MINIMAX_M3_MODEL_PATH,
73
+ avatarUrl: getHfAvatarUrl(MINIMAX_M3_MODEL_PATH),
74
  },
75
  {
76
+ id: 'glm-5.2',
77
+ name: 'GLM 5.2',
78
+ modelPath: GLM_52_MODEL_PATH,
79
+ avatarUrl: getHfAvatarUrl(GLM_52_MODEL_PATH),
80
+ recommended: true,
81
  },
82
  {
83
  id: 'deepseek-v4-pro',
 
87
  },
88
  ];
89
 
90
+ const DEFAULT_MODEL_PATH = GLM_52_MODEL_PATH;
91
 
92
  const normalizeModelPath = (path: string | undefined) => (
93
  (path ?? '')
 
124
  const modelOptionFromApi = (model: {
125
  id?: string;
126
  label?: string;
 
127
  recommended?: boolean;
128
  }): ModelOption | null => {
129
  if (!model.id) return null;
 
198
  const [modelOptions, setModelOptions] = useState<ModelOption[]>(DEFAULT_MODEL_OPTIONS);
199
  const modelOptionsRef = useRef<ModelOption[]>(DEFAULT_MODEL_OPTIONS);
200
  const sessionIdRef = useRef<string | undefined>(sessionId);
201
+ const [selectedModelPath, setSelectedModelPath] = useState<string>(
202
  () => (
203
+ findModelByPath(initialModelPath ?? '', DEFAULT_MODEL_OPTIONS)?.modelPath
204
+ ?? DEFAULT_MODEL_PATH
205
  ),
206
  );
207
  const [modelAnchorEl, setModelAnchorEl] = useState<null | HTMLElement>(null);
 
238
  setModelOptions(next);
239
  if (!sessionIdRef.current) {
240
  const current = data.current ? findModelByPath(data.current, next) : null;
241
+ if (current) setSelectedModelPath(current.modelPath);
242
  }
243
  })
244
  .catch(() => { /* ignore */ });
 
256
  if (cancelled) return;
257
  if (data?.model) {
258
  const model = findModelByPath(data.model, modelOptionsRef.current);
259
+ setSelectedModelPath(model?.modelPath ?? data.model);
260
  updateSessionModel(sessionId, data.model);
261
  }
262
  })
 
266
 
267
  const visibleModelOptions = modelOptions;
268
  const selectedModel = (
269
+ findModelByPath(selectedModelPath, visibleModelOptions)
270
+ || findModelByPath(selectedModelPath, modelOptions)
271
+ || visibleModelOptions.find(m => m.recommended)
272
+ || modelOptions.find(m => m.recommended)
273
  || visibleModelOptions[0]
274
  || modelOptions[0]
275
  );
 
390
  body: JSON.stringify({ model: model.modelPath }),
391
  });
392
  if (res.ok) {
393
+ setSelectedModelPath(model.modelPath);
394
  updateSessionModel(sessionId, model.modelPath);
395
  setModelSwitchError(null);
396
  return;
 
707
  <MenuItem
708
  key={model.id}
709
  onClick={() => handleSelectModel(model)}
710
+ selected={selectedModel.modelPath === model.modelPath}
711
  sx={{
712
  py: 1.5,
713
  '&.Mui-selected': {
frontend/src/components/SessionSidebar/SessionSidebar.tsx CHANGED
@@ -125,9 +125,9 @@ export default function SessionSidebar({ onClose }: SessionSidebarProps) {
125
 
126
  const handleSelect = useCallback(
127
  (sessionId: string) => {
128
- const shouldResetUsageWindow = sessionId !== activeSessionId;
129
  switchSession(sessionId);
130
- if (shouldResetUsageWindow) {
131
  void (async () => {
132
  try {
133
  const response = await apiFetch(`/api/session/${sessionId}/activate`, {
@@ -138,7 +138,7 @@ export default function SessionSidebar({ onClose }: SessionSidebarProps) {
138
  mergeServerSessions([info]);
139
  void useUsageStore.getState().fetchUsage(sessionId);
140
  } catch {
141
- /* best effort: usage falls back to the previously persisted window */
142
  }
143
  })();
144
  }
 
125
 
126
  const handleSelect = useCallback(
127
  (sessionId: string) => {
128
+ const shouldActivateSession = sessionId !== activeSessionId;
129
  switchSession(sessionId);
130
+ if (shouldActivateSession) {
131
  void (async () => {
132
  try {
133
  const response = await apiFetch(`/api/session/${sessionId}/activate`, {
 
138
  mergeServerSessions([info]);
139
  void useUsageStore.getState().fetchUsage(sessionId);
140
  } catch {
141
+ /* best effort: usage falls back to the existing session metadata */
142
  }
143
  })();
144
  }
frontend/src/components/WelcomeScreen/WelcomeScreen.tsx CHANGED
@@ -389,7 +389,7 @@ export default function WelcomeScreen() {
389
  variant="caption"
390
  sx={{ mt: 4, color: 'var(--muted-text)', opacity: 0.5, fontSize: '0.7rem' }}
391
  >
392
- Conversations are stored locally in your browser. Usage is billed based on the compute time of your agent's actions.
393
  </Typography>
394
  </Box>
395
  </Box>
 
389
  variant="caption"
390
  sx={{ mt: 4, color: 'var(--muted-text)', opacity: 0.5, fontSize: '0.7rem' }}
391
  >
392
+ Conversations are saved to a Hugging Face Hub dataset under your account. Usage is billed based on the compute time of your agent's actions.
393
  </Typography>
394
  </Box>
395
  </Box>
frontend/src/utils/model.ts CHANGED
@@ -8,9 +8,9 @@
8
 
9
  export const CLAUDE_OPUS_48_MODEL_PATH = 'anthropic/claude-opus-4.8:fal-ai';
10
  export const GPT_55_MODEL_PATH = 'openai/gpt-5.5:fal-ai';
11
- export const KIMI_K26_MODEL_PATH = 'moonshotai/Kimi-K2.6:novita';
12
- export const MINIMAX_M27_MODEL_PATH = 'MiniMaxAI/MiniMax-M2.7:novita';
13
- export const GLM_51_MODEL_PATH = 'zai-org/GLM-5.1:novita';
14
  export const DEEPSEEK_V4_PRO_MODEL_PATH = 'deepseek-ai/DeepSeek-V4-Pro:novita';
15
 
16
  export function isClaudePath(modelPath: string | undefined): boolean {
 
8
 
9
  export const CLAUDE_OPUS_48_MODEL_PATH = 'anthropic/claude-opus-4.8:fal-ai';
10
  export const GPT_55_MODEL_PATH = 'openai/gpt-5.5:fal-ai';
11
+ export const KIMI_K27_CODE_MODEL_PATH = 'moonshotai/Kimi-K2.7-Code:novita';
12
+ export const MINIMAX_M3_MODEL_PATH = 'MiniMaxAI/MiniMax-M3:novita';
13
+ export const GLM_52_MODEL_PATH = 'zai-org/GLM-5.2:novita';
14
  export const DEEPSEEK_V4_PRO_MODEL_PATH = 'deepseek-ai/DeepSeek-V4-Pro:novita';
15
 
16
  export function isClaudePath(modelPath: string | undefined): boolean {
tests/unit/test_agent_model_gating.py CHANGED
@@ -21,23 +21,23 @@ BILLING_SESSION_ID = "00000000-0000-4000-8000-000000000001"
21
  def test_available_models_exclude_sonnet_and_have_no_pro_gate():
22
  models = {model["id"]: model for model in agent.AVAILABLE_MODELS}
23
 
24
- assert models[agent.DEFAULT_OPUS_MODEL_ID]["label"] == "Claude Opus 4.8"
25
- assert models[agent.DEFAULT_OPUS_MODEL_ID]["recommended"] is True
26
- assert "recommended" not in models[agent.DEFAULT_FREE_MODEL_ID]
 
 
 
 
27
  assert all("minimum_plan" not in model for model in models.values())
28
  assert all("tier" not in model for model in models.values())
29
 
30
 
31
- def test_default_model_for_user_is_plan_aware():
32
- assert agent._default_model_for_user({"plan": "pro"}) == agent.DEFAULT_OPUS_MODEL_ID
33
- assert (
34
- agent._default_model_for_user({"plan": "free"}) == agent.DEFAULT_FREE_MODEL_ID
35
- )
36
- assert agent._default_model_for_user({}) == agent.DEFAULT_FREE_MODEL_ID
37
 
38
 
39
  @pytest.mark.asyncio
40
- async def test_llm_health_uses_request_hf_token(monkeypatch):
41
  class Request:
42
  headers = {"Authorization": "Bearer user-token"}
43
  cookies = {}
@@ -64,15 +64,15 @@ async def test_llm_health_uses_request_hf_token(monkeypatch):
64
  monkeypatch.setattr(
65
  agent.session_manager,
66
  "config",
67
- SimpleNamespace(model_name=agent.DEFAULT_FREE_MODEL_ID),
68
  )
69
  monkeypatch.setattr(agent, "_resolve_llm_params", fake_resolve_llm_params)
70
  monkeypatch.setattr(agent, "acompletion", fake_acompletion)
71
 
72
- response = await agent.llm_health_check(Request())
73
 
74
  assert response.status == "ok"
75
- assert resolved == [(agent.DEFAULT_FREE_MODEL_ID, "user-token", "high", False)]
76
  assert completions[0]["api_key"] == "user-token"
77
 
78
 
@@ -94,15 +94,17 @@ async def test_llm_health_skips_router_probe_without_token(monkeypatch):
94
  monkeypatch.setattr(
95
  agent.session_manager,
96
  "config",
97
- SimpleNamespace(model_name=agent.DEFAULT_FREE_MODEL_ID),
98
  )
99
  monkeypatch.setattr(agent, "_resolve_llm_params", fail_resolve_llm_params)
100
  monkeypatch.setattr(agent, "acompletion", fail_acompletion)
101
 
102
- response = await agent.llm_health_check(Request())
 
 
103
 
104
  assert response.status == "skipped"
105
- assert response.model == agent.DEFAULT_FREE_MODEL_ID
106
 
107
 
108
  @pytest.mark.asyncio
@@ -166,24 +168,12 @@ async def test_generate_title_omits_session_id_from_hf_router(monkeypatch):
166
  assert titles == [("session-1", "Clean title")]
167
 
168
 
169
- @pytest.mark.asyncio
170
- async def test_empty_session_model_uses_plan_default():
171
- assert (
172
- await agent._model_override_for_new_session(None, {"plan": "pro"})
173
- == agent.DEFAULT_OPUS_MODEL_ID
174
- )
175
- assert (
176
- await agent._model_override_for_new_session(None, {"plan": "free"})
177
- == agent.DEFAULT_FREE_MODEL_ID
178
- )
179
 
180
 
181
- @pytest.mark.asyncio
182
- async def test_explicit_session_model_is_honored():
183
- model = await agent._model_override_for_new_session(
184
- agent.DEFAULT_GPT_MODEL_ID,
185
- {"plan": "free"},
186
- )
187
 
188
  assert model == agent.DEFAULT_GPT_MODEL_ID
189
 
@@ -209,13 +199,13 @@ async def test_switching_to_opus_is_allowed_for_free_user(monkeypatch):
209
 
210
  response = await agent.set_session_model(
211
  "s1",
212
- {"model": agent.DEFAULT_OPUS_MODEL_ID},
213
  request=None,
214
  user={"user_id": "u1", "plan": "free"},
215
  )
216
 
217
- assert response == {"session_id": "s1", "model": agent.DEFAULT_OPUS_MODEL_ID}
218
- assert updated == [("s1", agent.DEFAULT_OPUS_MODEL_ID)]
219
 
220
 
221
  @pytest.mark.asyncio
@@ -298,9 +288,9 @@ async def test_restore_summary_uses_default_model_without_quota_gate(monkeypatch
298
  )
299
 
300
  assert response.session_id == "s1"
301
- assert response.model == agent.DEFAULT_FREE_MODEL_ID
302
  assert events == [
303
- ("create", agent.DEFAULT_FREE_MODEL_ID, "free"),
304
  ("check", "s1", False),
305
  ("seed", "s1"),
306
  ]
 
21
  def test_available_models_exclude_sonnet_and_have_no_pro_gate():
22
  models = {model["id"]: model for model in agent.AVAILABLE_MODELS}
23
 
24
+ assert models[agent.CLAUDE_OPUS_48_MODEL_ID]["label"] == "Claude Opus 4.8"
25
+ assert models[agent.DEFAULT_MODEL_ID]["label"] == "GLM 5.2"
26
+ assert models["moonshotai/Kimi-K2.7-Code:novita"]["label"] == "Kimi K2.7 Code"
27
+ assert models["MiniMaxAI/MiniMax-M3:novita"]["label"] == "MiniMax M3"
28
+ assert "recommended" not in models[agent.CLAUDE_OPUS_48_MODEL_ID]
29
+ assert models[agent.DEFAULT_MODEL_ID]["recommended"] is True
30
+ assert all("provider" not in model for model in models.values())
31
  assert all("minimum_plan" not in model for model in models.values())
32
  assert all("tier" not in model for model in models.values())
33
 
34
 
35
+ def test_default_model_is_glm():
36
+ assert agent._default_model() == agent.DEFAULT_MODEL_ID
 
 
 
 
37
 
38
 
39
  @pytest.mark.asyncio
40
+ async def test_llm_health_uses_default_and_request_hf_token(monkeypatch):
41
  class Request:
42
  headers = {"Authorization": "Bearer user-token"}
43
  cookies = {}
 
64
  monkeypatch.setattr(
65
  agent.session_manager,
66
  "config",
67
+ SimpleNamespace(model_name=agent.DEFAULT_MODEL_ID),
68
  )
69
  monkeypatch.setattr(agent, "_resolve_llm_params", fake_resolve_llm_params)
70
  monkeypatch.setattr(agent, "acompletion", fake_acompletion)
71
 
72
+ response = await agent.llm_health_check(Request(), {"user_id": "u1", "plan": "pro"})
73
 
74
  assert response.status == "ok"
75
+ assert resolved == [(agent.DEFAULT_MODEL_ID, "user-token", "high", False)]
76
  assert completions[0]["api_key"] == "user-token"
77
 
78
 
 
94
  monkeypatch.setattr(
95
  agent.session_manager,
96
  "config",
97
+ SimpleNamespace(model_name=agent.CLAUDE_OPUS_48_MODEL_ID),
98
  )
99
  monkeypatch.setattr(agent, "_resolve_llm_params", fail_resolve_llm_params)
100
  monkeypatch.setattr(agent, "acompletion", fail_acompletion)
101
 
102
+ response = await agent.llm_health_check(
103
+ Request(), {"user_id": "u1", "plan": "free"}
104
+ )
105
 
106
  assert response.status == "skipped"
107
+ assert response.model == agent.DEFAULT_MODEL_ID
108
 
109
 
110
  @pytest.mark.asyncio
 
168
  assert titles == [("session-1", "Clean title")]
169
 
170
 
171
+ def test_empty_session_model_uses_glm_default():
172
+ assert agent._model_override_for_new_session(None) == agent.DEFAULT_MODEL_ID
 
 
 
 
 
 
 
 
173
 
174
 
175
+ def test_explicit_session_model_is_honored():
176
+ model = agent._model_override_for_new_session(agent.DEFAULT_GPT_MODEL_ID)
 
 
 
 
177
 
178
  assert model == agent.DEFAULT_GPT_MODEL_ID
179
 
 
199
 
200
  response = await agent.set_session_model(
201
  "s1",
202
+ {"model": agent.CLAUDE_OPUS_48_MODEL_ID},
203
  request=None,
204
  user={"user_id": "u1", "plan": "free"},
205
  )
206
 
207
+ assert response == {"session_id": "s1", "model": agent.CLAUDE_OPUS_48_MODEL_ID}
208
+ assert updated == [("s1", agent.CLAUDE_OPUS_48_MODEL_ID)]
209
 
210
 
211
  @pytest.mark.asyncio
 
288
  )
289
 
290
  assert response.session_id == "s1"
291
+ assert response.model == agent.DEFAULT_MODEL_ID
292
  assert events == [
293
+ ("create", agent.DEFAULT_MODEL_ID, "free"),
294
  ("check", "s1", False),
295
  ("seed", "s1"),
296
  ]
tests/unit/test_auto_approval_policy.py CHANGED
@@ -12,7 +12,7 @@ from agent.core.cost_estimation import CostEstimate
12
 
13
  def _config(**overrides):
14
  data = {
15
- "model_name": "moonshotai/Kimi-K2.6",
16
  "confirm_cpu_jobs": True,
17
  "auto_file_upload": False,
18
  "yolo_mode": False,
 
12
 
13
  def _config(**overrides):
14
  data = {
15
+ "model_name": "moonshotai/Kimi-K2.7-Code",
16
  "confirm_cpu_jobs": True,
17
  "auto_file_upload": False,
18
  "yolo_mode": False,
tests/unit/test_build_kpis.py CHANGED
@@ -369,9 +369,9 @@ def test_aggregate_sessions_by_model_split():
369
  s_claude = _session([], user_id="a")
370
  s_claude["model_name"] = "anthropic/claude-opus-4.8:fal-ai"
371
  s_kimi = _session([], user_id="b")
372
- s_kimi["model_name"] = "moonshotai/Kimi-K2.6"
373
  s_kimi2 = _session([], user_id="c")
374
- s_kimi2["model_name"] = "moonshotai/Kimi-K2.6"
375
  row = mod._aggregate(
376
  [
377
  mod._session_metrics(s_claude),
@@ -381,7 +381,7 @@ def test_aggregate_sessions_by_model_split():
381
  )
382
  assert _json.loads(row["sessions_by_model_json"]) == {
383
  "anthropic/claude-opus-4.8:fal-ai": 1,
384
- "moonshotai/Kimi-K2.6": 2,
385
  }
386
 
387
 
 
369
  s_claude = _session([], user_id="a")
370
  s_claude["model_name"] = "anthropic/claude-opus-4.8:fal-ai"
371
  s_kimi = _session([], user_id="b")
372
+ s_kimi["model_name"] = "moonshotai/Kimi-K2.7-Code"
373
  s_kimi2 = _session([], user_id="c")
374
+ s_kimi2["model_name"] = "moonshotai/Kimi-K2.7-Code"
375
  row = mod._aggregate(
376
  [
377
  mod._session_metrics(s_claude),
 
381
  )
382
  assert _json.loads(row["sessions_by_model_json"]) == {
383
  "anthropic/claude-opus-4.8:fal-ai": 1,
384
+ "moonshotai/Kimi-K2.7-Code": 2,
385
  }
386
 
387
 
tests/unit/test_cli_local_models.py CHANGED
@@ -39,16 +39,16 @@ def test_suggested_models_include_router_claude_models_and_no_native_ids():
39
  assert all(model_id.count("/") >= 1 for model_id in ids)
40
 
41
 
42
- def test_cli_default_model_is_opus():
43
  config = load_config(CLI_CONFIG_PATH)
44
 
45
- assert config.model_name == "anthropic/claude-opus-4.8:fal-ai"
46
 
47
 
48
  def test_model_switcher_accepts_router_model_ids():
49
  assert model_switcher.is_valid_model_id("openai/gpt-5.5:fal-ai")
50
  assert model_switcher.is_valid_model_id("openai/gpt-oss-120b")
51
- assert model_switcher.is_valid_model_id("moonshotai/Kimi-K2.6")
52
 
53
 
54
  def test_local_models_skip_hf_router_catalog_output():
 
39
  assert all(model_id.count("/") >= 1 for model_id in ids)
40
 
41
 
42
+ def test_cli_default_model_is_glm():
43
  config = load_config(CLI_CONFIG_PATH)
44
 
45
+ assert config.model_name == "zai-org/GLM-5.2:novita"
46
 
47
 
48
  def test_model_switcher_accepts_router_model_ids():
49
  assert model_switcher.is_valid_model_id("openai/gpt-5.5:fal-ai")
50
  assert model_switcher.is_valid_model_id("openai/gpt-oss-120b")
51
+ assert model_switcher.is_valid_model_id("moonshotai/Kimi-K2.7-Code")
52
 
53
 
54
  def test_local_models_skip_hf_router_catalog_output():
tests/unit/test_cli_rendering.py CHANGED
@@ -216,7 +216,7 @@ async def test_interactive_main_applies_model_override_before_banner(monkeypatch
216
  main_mod,
217
  "load_config",
218
  lambda _path, **_kwargs: SimpleNamespace(
219
- model_name="moonshotai/Kimi-K2.6",
220
  mcpServers={},
221
  tool_runtime="local",
222
  ),
@@ -378,6 +378,8 @@ async def test_interactive_main_passes_user_plan_to_submission_loop(monkeypatch)
378
  async def fake_submission_loop(submission_queue, _event_queue, **kwargs):
379
  seen["user_plan"] = kwargs.get("user_plan")
380
  seen["hf_token"] = kwargs.get("hf_token")
 
 
381
  while True:
382
  submission = await submission_queue.get()
383
  if submission.operation.op_type == main_mod.OpType.SHUTDOWN:
@@ -432,6 +434,8 @@ async def test_interactive_main_passes_user_plan_to_submission_loop(monkeypatch)
432
  "plan_token": "hf-token",
433
  "user_plan": "free",
434
  "hf_token": "hf-token",
 
 
435
  }
436
 
437
 
@@ -464,6 +468,8 @@ async def test_headless_main_passes_user_plan_to_submission_loop(monkeypatch):
464
  async def fake_submission_loop(submission_queue, event_queue, **kwargs):
465
  seen["user_plan"] = kwargs.get("user_plan")
466
  seen["hf_token"] = kwargs.get("hf_token")
 
 
467
  await event_queue.put(Event(event_type="ready"))
468
  submission = await submission_queue.get()
469
  seen["prompt"] = submission.operation.data["text"]
@@ -497,6 +503,8 @@ async def test_headless_main_passes_user_plan_to_submission_loop(monkeypatch):
497
  "plan_token": "hf-token",
498
  "user_plan": "pro",
499
  "hf_token": "hf-token",
 
 
500
  "prompt": "train a model",
501
  }
502
 
 
216
  main_mod,
217
  "load_config",
218
  lambda _path, **_kwargs: SimpleNamespace(
219
+ model_name="moonshotai/Kimi-K2.7-Code",
220
  mcpServers={},
221
  tool_runtime="local",
222
  ),
 
378
  async def fake_submission_loop(submission_queue, _event_queue, **kwargs):
379
  seen["user_plan"] = kwargs.get("user_plan")
380
  seen["hf_token"] = kwargs.get("hf_token")
381
+ seen["hf_username"] = kwargs.get("hf_username")
382
+ seen["autonomous_mode"] = kwargs.get("autonomous_mode")
383
  while True:
384
  submission = await submission_queue.get()
385
  if submission.operation.op_type == main_mod.OpType.SHUTDOWN:
 
434
  "plan_token": "hf-token",
435
  "user_plan": "free",
436
  "hf_token": "hf-token",
437
+ "hf_username": "tester",
438
+ "autonomous_mode": False,
439
  }
440
 
441
 
 
468
  async def fake_submission_loop(submission_queue, event_queue, **kwargs):
469
  seen["user_plan"] = kwargs.get("user_plan")
470
  seen["hf_token"] = kwargs.get("hf_token")
471
+ seen["hf_username"] = kwargs.get("hf_username")
472
+ seen["autonomous_mode"] = kwargs.get("autonomous_mode")
473
  await event_queue.put(Event(event_type="ready"))
474
  submission = await submission_queue.get()
475
  seen["prompt"] = submission.operation.data["text"]
 
503
  "plan_token": "hf-token",
504
  "user_plan": "pro",
505
  "hf_token": "hf-token",
506
+ "hf_username": "tester",
507
+ "autonomous_mode": True,
508
  "prompt": "train a model",
509
  }
510
 
tests/unit/test_config.py CHANGED
@@ -17,7 +17,7 @@ def test_load_config_does_not_apply_slack_user_defaults_by_default(
17
  _write_json(
18
  config_path,
19
  {
20
- "model_name": "moonshotai/Kimi-K2.6",
21
  "messaging": {
22
  "enabled": False,
23
  "destinations": {},
@@ -35,7 +35,7 @@ def test_load_config_does_not_apply_slack_user_defaults_by_default(
35
 
36
  def test_load_config_applies_slack_user_defaults_from_env(tmp_path, monkeypatch):
37
  config_path = tmp_path / "config.json"
38
- _write_json(config_path, {"model_name": "moonshotai/Kimi-K2.6"})
39
  monkeypatch.delenv("ML_INTERN_CLI_CONFIG", raising=False)
40
  monkeypatch.setattr(
41
  config_module,
@@ -63,7 +63,7 @@ def test_load_config_applies_slack_user_defaults_from_env(tmp_path, monkeypatch)
63
  def test_load_config_merges_user_config_before_env_substitution(tmp_path, monkeypatch):
64
  config_path = tmp_path / "config.json"
65
  user_config_path = tmp_path / "user-config.json"
66
- _write_json(config_path, {"model_name": "moonshotai/Kimi-K2.6"})
67
  _write_json(
68
  user_config_path,
69
  {
@@ -103,7 +103,7 @@ def test_slack_user_defaults_can_be_disabled(tmp_path, monkeypatch):
103
  _write_json(
104
  config_path,
105
  {
106
- "model_name": "moonshotai/Kimi-K2.6",
107
  "messaging": {
108
  "enabled": False,
109
  "destinations": {},
@@ -128,7 +128,7 @@ def test_slack_user_defaults_can_be_disabled(tmp_path, monkeypatch):
128
 
129
  def test_tool_runtime_defaults_to_local(tmp_path):
130
  config_path = tmp_path / "config.json"
131
- _write_json(config_path, {"model_name": "moonshotai/Kimi-K2.6"})
132
 
133
  config = config_module.load_config(str(config_path))
134
 
@@ -138,7 +138,7 @@ def test_tool_runtime_defaults_to_local(tmp_path):
138
  def test_user_config_can_set_sandbox_tool_runtime(tmp_path, monkeypatch):
139
  config_path = tmp_path / "config.json"
140
  user_config_path = tmp_path / "user-config.json"
141
- _write_json(config_path, {"model_name": "moonshotai/Kimi-K2.6"})
142
  _write_json(user_config_path, {"tool_runtime": "sandbox"})
143
  monkeypatch.setenv("ML_INTERN_CLI_CONFIG", str(user_config_path))
144
 
@@ -151,7 +151,7 @@ def test_invalid_tool_runtime_is_rejected(tmp_path):
151
  config_path = tmp_path / "config.json"
152
  _write_json(
153
  config_path,
154
- {"model_name": "moonshotai/Kimi-K2.6", "tool_runtime": "hybrid"},
155
  )
156
 
157
  with pytest.raises(ValidationError):
 
17
  _write_json(
18
  config_path,
19
  {
20
+ "model_name": "moonshotai/Kimi-K2.7-Code",
21
  "messaging": {
22
  "enabled": False,
23
  "destinations": {},
 
35
 
36
  def test_load_config_applies_slack_user_defaults_from_env(tmp_path, monkeypatch):
37
  config_path = tmp_path / "config.json"
38
+ _write_json(config_path, {"model_name": "moonshotai/Kimi-K2.7-Code"})
39
  monkeypatch.delenv("ML_INTERN_CLI_CONFIG", raising=False)
40
  monkeypatch.setattr(
41
  config_module,
 
63
  def test_load_config_merges_user_config_before_env_substitution(tmp_path, monkeypatch):
64
  config_path = tmp_path / "config.json"
65
  user_config_path = tmp_path / "user-config.json"
66
+ _write_json(config_path, {"model_name": "moonshotai/Kimi-K2.7-Code"})
67
  _write_json(
68
  user_config_path,
69
  {
 
103
  _write_json(
104
  config_path,
105
  {
106
+ "model_name": "moonshotai/Kimi-K2.7-Code",
107
  "messaging": {
108
  "enabled": False,
109
  "destinations": {},
 
128
 
129
  def test_tool_runtime_defaults_to_local(tmp_path):
130
  config_path = tmp_path / "config.json"
131
+ _write_json(config_path, {"model_name": "moonshotai/Kimi-K2.7-Code"})
132
 
133
  config = config_module.load_config(str(config_path))
134
 
 
138
  def test_user_config_can_set_sandbox_tool_runtime(tmp_path, monkeypatch):
139
  config_path = tmp_path / "config.json"
140
  user_config_path = tmp_path / "user-config.json"
141
+ _write_json(config_path, {"model_name": "moonshotai/Kimi-K2.7-Code"})
142
  _write_json(user_config_path, {"tool_runtime": "sandbox"})
143
  monkeypatch.setenv("ML_INTERN_CLI_CONFIG", str(user_config_path))
144
 
 
151
  config_path = tmp_path / "config.json"
152
  _write_json(
153
  config_path,
154
+ {"model_name": "moonshotai/Kimi-K2.7-Code", "tool_runtime": "hybrid"},
155
  )
156
 
157
  with pytest.raises(ValidationError):
tests/unit/test_effort_probe.py CHANGED
@@ -22,7 +22,7 @@ async def test_probe_effort_sends_session_id_to_hf_router(monkeypatch):
22
  monkeypatch.setattr(effort_probe, "acompletion", fake_acompletion)
23
 
24
  outcome = await effort_probe.probe_effort(
25
- "moonshotai/Kimi-K2.6:novita",
26
  "high",
27
  "hf_fake",
28
  session=SimpleNamespace(
 
22
  monkeypatch.setattr(effort_probe, "acompletion", fake_acompletion)
23
 
24
  outcome = await effort_probe.probe_effort(
25
+ "moonshotai/Kimi-K2.7-Code:novita",
26
  "high",
27
  "hf_fake",
28
  session=SimpleNamespace(
tests/unit/test_llm_error_classification.py CHANGED
@@ -28,7 +28,7 @@ from agent.core.agent_loop import (
28
 
29
 
30
  def test_kimi_prompt_too_long_is_context_overflow():
31
- # Verbatim error text from session 62ccfdcb (2026-04-25, Kimi K2.6).
32
  err = Exception(
33
  "litellm.BadRequestError: OpenAIException - The prompt is too long: "
34
  "365407, model maximum context length: 262143"
 
28
 
29
 
30
  def test_kimi_prompt_too_long_is_context_overflow():
31
+ # Verbatim error text from session 62ccfdcb (2026-04-25, Kimi-family model).
32
  err = Exception(
33
  "litellm.BadRequestError: OpenAIException - The prompt is too long: "
34
  "365407, model maximum context length: 262143"
tests/unit/test_llm_params.py CHANGED
@@ -64,7 +64,7 @@ def test_router_params_fall_back_to_hf_cache_when_session_token_missing(monkeypa
64
 
65
 
66
  def test_router_params_never_set_bill_to_headers():
67
- params = _resolve_llm_params("moonshotai/Kimi-K2.6", "session-token")
68
 
69
  assert params["api_key"] == "session-token"
70
  assert "extra_headers" not in params
@@ -203,7 +203,7 @@ def test_hf_router_params_allow_missing_token_without_headers(monkeypatch):
203
  monkeypatch.delenv("HF_TOKEN", raising=False)
204
  monkeypatch.setattr(huggingface_hub, "get_token", lambda: None)
205
 
206
- params = _resolve_llm_params("moonshotai/Kimi-K2.6")
207
 
208
  assert params["api_key"] is None
209
  assert "extra_headers" not in params
 
64
 
65
 
66
  def test_router_params_never_set_bill_to_headers():
67
+ params = _resolve_llm_params("moonshotai/Kimi-K2.7-Code", "session-token")
68
 
69
  assert params["api_key"] == "session-token"
70
  assert "extra_headers" not in params
 
203
  monkeypatch.delenv("HF_TOKEN", raising=False)
204
  monkeypatch.setattr(huggingface_hub, "get_token", lambda: None)
205
 
206
+ params = _resolve_llm_params("moonshotai/Kimi-K2.7-Code")
207
 
208
  assert params["api_key"] is None
209
  assert "extra_headers" not in params
tests/unit/test_messaging.py CHANGED
@@ -53,7 +53,7 @@ def _config_with_messaging(**destination_overrides) -> Config:
53
  }
54
  return Config.model_validate(
55
  {
56
- "model_name": "moonshotai/Kimi-K2.6",
57
  "messaging": {
58
  "enabled": True,
59
  "destinations": {
@@ -79,7 +79,7 @@ def test_messaging_config_validates_destination_names():
79
  with pytest.raises(ValidationError):
80
  Config.model_validate(
81
  {
82
- "model_name": "moonshotai/Kimi-K2.6",
83
  "messaging": {
84
  "enabled": True,
85
  "destinations": {
@@ -101,7 +101,7 @@ def test_messaging_config_validates_destination_names():
101
  def test_messaging_config_default_auto_destinations_only_returns_auto_enabled():
102
  config = Config.model_validate(
103
  {
104
- "model_name": "moonshotai/Kimi-K2.6",
105
  "messaging": {
106
  "enabled": True,
107
  "destinations": {
@@ -128,7 +128,7 @@ def test_messaging_config_default_auto_destinations_only_returns_auto_enabled():
128
  def test_messaging_config_default_auto_destinations_empty_when_disabled():
129
  config = Config.model_validate(
130
  {
131
- "model_name": "moonshotai/Kimi-K2.6",
132
  "messaging": {
133
  "enabled": False,
134
  "destinations": {
@@ -272,14 +272,14 @@ async def test_notify_tool_sends_to_allowlisted_destinations():
272
  assert len(gateway.sent) == 1
273
  sent = gateway.sent[0]
274
  assert sent.metadata["session_id"] == "sess-42"
275
- assert sent.metadata["model"] == "moonshotai/Kimi-K2.6"
276
 
277
 
278
  @pytest.mark.asyncio
279
  async def test_session_auto_notifications_only_send_opted_in_auto_destinations():
280
  config = Config.model_validate(
281
  {
282
- "model_name": "moonshotai/Kimi-K2.6",
283
  "messaging": {
284
  "enabled": True,
285
  "destinations": {
@@ -325,7 +325,7 @@ async def test_session_auto_notifications_only_send_opted_in_auto_destinations()
325
  async def test_turn_complete_auto_notification_includes_final_response_summary():
326
  config = Config.model_validate(
327
  {
328
- "model_name": "moonshotai/Kimi-K2.6",
329
  "messaging": {
330
  "enabled": True,
331
  "destinations": {
@@ -366,7 +366,7 @@ async def test_turn_complete_auto_notification_includes_final_response_summary()
366
  async def test_turn_complete_auto_notification_supports_longer_summary():
367
  config = Config.model_validate(
368
  {
369
- "model_name": "moonshotai/Kimi-K2.6",
370
  "messaging": {
371
  "enabled": True,
372
  "destinations": {
@@ -406,7 +406,7 @@ async def test_turn_complete_auto_notification_supports_longer_summary():
406
  async def test_turn_complete_auto_notification_can_be_deferred():
407
  config = Config.model_validate(
408
  {
409
- "model_name": "moonshotai/Kimi-K2.6",
410
  "messaging": {
411
  "enabled": True,
412
  "destinations": {
@@ -452,7 +452,7 @@ async def test_turn_complete_auto_notification_can_be_deferred():
452
  async def test_turn_complete_can_be_disabled_by_custom_auto_event_config():
453
  config = Config.model_validate(
454
  {
455
- "model_name": "moonshotai/Kimi-K2.6",
456
  "messaging": {
457
  "enabled": True,
458
  "auto_event_types": ["error"],
 
53
  }
54
  return Config.model_validate(
55
  {
56
+ "model_name": "moonshotai/Kimi-K2.7-Code",
57
  "messaging": {
58
  "enabled": True,
59
  "destinations": {
 
79
  with pytest.raises(ValidationError):
80
  Config.model_validate(
81
  {
82
+ "model_name": "moonshotai/Kimi-K2.7-Code",
83
  "messaging": {
84
  "enabled": True,
85
  "destinations": {
 
101
  def test_messaging_config_default_auto_destinations_only_returns_auto_enabled():
102
  config = Config.model_validate(
103
  {
104
+ "model_name": "moonshotai/Kimi-K2.7-Code",
105
  "messaging": {
106
  "enabled": True,
107
  "destinations": {
 
128
  def test_messaging_config_default_auto_destinations_empty_when_disabled():
129
  config = Config.model_validate(
130
  {
131
+ "model_name": "moonshotai/Kimi-K2.7-Code",
132
  "messaging": {
133
  "enabled": False,
134
  "destinations": {
 
272
  assert len(gateway.sent) == 1
273
  sent = gateway.sent[0]
274
  assert sent.metadata["session_id"] == "sess-42"
275
+ assert sent.metadata["model"] == "moonshotai/Kimi-K2.7-Code"
276
 
277
 
278
  @pytest.mark.asyncio
279
  async def test_session_auto_notifications_only_send_opted_in_auto_destinations():
280
  config = Config.model_validate(
281
  {
282
+ "model_name": "moonshotai/Kimi-K2.7-Code",
283
  "messaging": {
284
  "enabled": True,
285
  "destinations": {
 
325
  async def test_turn_complete_auto_notification_includes_final_response_summary():
326
  config = Config.model_validate(
327
  {
328
+ "model_name": "moonshotai/Kimi-K2.7-Code",
329
  "messaging": {
330
  "enabled": True,
331
  "destinations": {
 
366
  async def test_turn_complete_auto_notification_supports_longer_summary():
367
  config = Config.model_validate(
368
  {
369
+ "model_name": "moonshotai/Kimi-K2.7-Code",
370
  "messaging": {
371
  "enabled": True,
372
  "destinations": {
 
406
  async def test_turn_complete_auto_notification_can_be_deferred():
407
  config = Config.model_validate(
408
  {
409
+ "model_name": "moonshotai/Kimi-K2.7-Code",
410
  "messaging": {
411
  "enabled": True,
412
  "destinations": {
 
452
  async def test_turn_complete_can_be_disabled_by_custom_auto_event_config():
453
  config = Config.model_validate(
454
  {
455
+ "model_name": "moonshotai/Kimi-K2.7-Code",
456
  "messaging": {
457
  "enabled": True,
458
  "auto_event_types": ["error"],
tests/unit/test_personal_trace_repo.py CHANGED
@@ -11,7 +11,7 @@ class DummyToolRouter:
11
 
12
  def _session(*, user_id: str | None, hf_username: str | None) -> Session:
13
  config = SimpleNamespace(
14
- model_name="moonshotai/Kimi-K2.6",
15
  save_sessions=True,
16
  share_traces=True,
17
  personal_trace_repo_template="{hf_user}/ml-intern-sessions",
 
11
 
12
  def _session(*, user_id: str | None, hf_username: str | None) -> Session:
13
  config = SimpleNamespace(
14
+ model_name="moonshotai/Kimi-K2.7-Code",
15
  save_sessions=True,
16
  share_traces=True,
17
  personal_trace_repo_template="{hf_user}/ml-intern-sessions",
tests/unit/test_prompt_caching.py CHANGED
@@ -28,7 +28,7 @@ def _gpt55_fal_params() -> dict:
28
 
29
  def _kimi_novita_params() -> dict:
30
  return {
31
- "model": "openai/moonshotai/Kimi-K2.6:novita",
32
  "api_base": HF_ROUTER_BASE_URL,
33
  }
34
 
@@ -158,7 +158,7 @@ def test_prompt_caching_is_noop_for_non_fal_router_model():
158
  {"role": "user", "content": "current question"},
159
  ]
160
  llm_params = {
161
- "model": "openai/moonshotai/Kimi-K2.6",
162
  "api_base": HF_ROUTER_BASE_URL,
163
  }
164
 
 
28
 
29
  def _kimi_novita_params() -> dict:
30
  return {
31
+ "model": "openai/moonshotai/Kimi-K2.7-Code:novita",
32
  "api_base": HF_ROUTER_BASE_URL,
33
  }
34
 
 
158
  {"role": "user", "content": "current question"},
159
  ]
160
  llm_params = {
161
+ "model": "openai/moonshotai/Kimi-K2.7-Code",
162
  "api_base": HF_ROUTER_BASE_URL,
163
  }
164
 
tests/unit/test_sandbox_auto_start.py CHANGED
@@ -1,10 +1,11 @@
1
  import asyncio
2
- from types import SimpleNamespace
3
  from pathlib import Path
 
4
 
5
  import pytest
6
 
7
  from agent.config import Config
 
8
  from agent.core import agent_loop
9
  from agent.core.agent_loop import _base_needs_approval
10
  from agent.core.session import OpType
@@ -66,10 +67,215 @@ def test_prompt_and_hf_jobs_spec_require_gpu_preflight_for_gpu_jobs():
66
  assert "GPU preflight is mandatory before hf_jobs" in prompt
67
  assert "GPU sandbox smoke test" in prompt
68
  assert "If you skip GPU sandbox preflight" in prompt
 
 
69
  assert "you MUST create a GPU sandbox with sandbox_create first" in jobs_description
70
  assert "If skipped, state why before calling hf_jobs" in jobs_description
71
 
72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  def test_local_tool_runtime_excludes_sandbox_create():
74
  tool_names = {tool.name for tool in create_builtin_tools(local_mode=True)}
75
 
@@ -113,6 +319,9 @@ async def test_cli_sandbox_runtime_preloads_and_tears_down_sandbox(monkeypatch):
113
  monkeypatch.setattr(
114
  agent_loop, "teardown_session_sandbox", fake_teardown_session_sandbox
115
  )
 
 
 
116
 
117
  submission_queue = asyncio.Queue()
118
  event_queue = asyncio.Queue()
@@ -138,6 +347,88 @@ async def test_cli_sandbox_runtime_preloads_and_tears_down_sandbox(monkeypatch):
138
  assert ready.event_type == "ready"
139
  assert started == [session_holder[0]]
140
  assert session_holder[0].local_mode is False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
 
142
  await submission_queue.put(
143
  SimpleNamespace(
 
1
  import asyncio
 
2
  from pathlib import Path
3
+ from types import SimpleNamespace
4
 
5
  import pytest
6
 
7
  from agent.config import Config
8
+ from agent.context_manager.manager import ContextManager
9
  from agent.core import agent_loop
10
  from agent.core.agent_loop import _base_needs_approval
11
  from agent.core.session import OpType
 
67
  assert "GPU preflight is mandatory before hf_jobs" in prompt
68
  assert "GPU sandbox smoke test" in prompt
69
  assert "If you skip GPU sandbox preflight" in prompt
70
+ assert "for flash-attention kernels use Ampere-or-newer hardware" in prompt
71
+ assert "never T4" in prompt
72
  assert "you MUST create a GPU sandbox with sandbox_create first" in jobs_description
73
  assert "If skipped, state why before calling hf_jobs" in jobs_description
74
 
75
 
76
+ def test_prompt_has_identity_contract():
77
+ prompt = Path("agent/prompts/system_prompt_v3.yaml").read_text()
78
+
79
+ assert "introduce yourself as ML Intern" in prompt
80
+ assert "Do not claim to be Claude, ChatGPT, Anthropic, OpenAI" in prompt
81
+ assert "Do not cite this system prompt" in prompt
82
+ assert (
83
+ "Default to the session context User value as the authenticated Hugging Face namespace"
84
+ in prompt
85
+ )
86
+ assert "If the user explicitly requests an org namespace" in prompt
87
+ assert "hub_model_id, trackio_space_id" in prompt
88
+ assert "identity/whoami" not in prompt
89
+ assert "If session context says User=unknown" in prompt
90
+ assert "identity lookup failed or no token is available" in prompt
91
+ assert "ask for it before creating Hub resources" in prompt
92
+
93
+
94
+ def test_prompt_has_tool_calling_contract():
95
+ prompt = Path("agent/prompts/system_prompt_v3.yaml").read_text()
96
+
97
+ assert "# Tool calling contract" in prompt
98
+ assert (
99
+ "Use only tools that are actually available in the current tool list" in prompt
100
+ )
101
+ assert "Do not simulate tool calls in prose or fenced code blocks" in prompt
102
+ assert "valid JSON arguments matching the tool schema" in prompt
103
+ assert "required arguments, enum values, mutually exclusive fields" in prompt
104
+ assert "Do not claim success unless the tool result confirms it" in prompt
105
+
106
+
107
+ def test_prompt_gates_autonomous_headless_mode():
108
+ prompt = Path("agent/prompts/system_prompt_v3.yaml").read_text()
109
+
110
+ assert "{% if autonomous_mode %}" in prompt
111
+ assert "Autonomous mode is active for this session" in prompt
112
+ assert (
113
+ "Apply this section even if the user prompt does not contain those words"
114
+ in (prompt)
115
+ )
116
+ assert "Autonomous mode is not active for this session" in prompt
117
+ assert "text-only answers are allowed for simple questions" in prompt
118
+ assert "NEVER respond with only text" in prompt
119
+
120
+
121
+ def test_context_manager_renders_interactive_autonomous_context(monkeypatch):
122
+ monkeypatch.setattr(
123
+ "agent.context_manager.manager._get_hf_username", lambda _token=None: "tester"
124
+ )
125
+
126
+ context_manager = ContextManager(
127
+ tool_specs=[],
128
+ hf_token="hf-token",
129
+ autonomous_mode=False,
130
+ )
131
+
132
+ assert "Autonomous=false" in context_manager.system_prompt
133
+ assert "Autonomous mode is not active for this session" in (
134
+ context_manager.system_prompt
135
+ )
136
+ assert "Autonomous mode is active for this session" not in (
137
+ context_manager.system_prompt
138
+ )
139
+ assert "text-only answers are allowed for simple questions" in (
140
+ context_manager.system_prompt
141
+ )
142
+ assert "NEVER respond with only text" not in context_manager.system_prompt
143
+ assert "NEVER STOP WORKING" not in context_manager.system_prompt
144
+
145
+
146
+ def test_context_manager_renders_headless_autonomous_context(monkeypatch):
147
+ monkeypatch.setattr(
148
+ "agent.context_manager.manager._get_hf_username", lambda _token=None: "tester"
149
+ )
150
+
151
+ context_manager = ContextManager(
152
+ tool_specs=[],
153
+ hf_token="hf-token",
154
+ autonomous_mode=True,
155
+ )
156
+
157
+ assert "Autonomous=true" in context_manager.system_prompt
158
+ assert "Autonomous mode is active for this session" in (
159
+ context_manager.system_prompt
160
+ )
161
+ assert "Autonomous mode is not active for this session" not in (
162
+ context_manager.system_prompt
163
+ )
164
+ assert (
165
+ "Apply this section even if the user prompt does not contain those words"
166
+ in (context_manager.system_prompt)
167
+ )
168
+ assert "NEVER respond with only text" in context_manager.system_prompt
169
+
170
+
171
+ def test_context_manager_prefers_resolved_hf_username(monkeypatch):
172
+ def fail_hf_lookup(_token=None):
173
+ raise AssertionError("token lookup should not run when username is provided")
174
+
175
+ monkeypatch.setattr(
176
+ "agent.context_manager.manager._get_hf_username", fail_hf_lookup
177
+ )
178
+
179
+ context_manager = ContextManager(
180
+ tool_specs=[],
181
+ hf_token="hf-token",
182
+ hf_username="resolved-user",
183
+ )
184
+
185
+ assert "User=resolved-user" in context_manager.system_prompt
186
+
187
+
188
+ def test_prompt_and_hf_jobs_spec_require_exact_tested_scripts():
189
+ prompt = Path("agent/prompts/system_prompt_v3.yaml").read_text()
190
+ jobs_description = HF_JOBS_TOOL_SPEC["description"]
191
+ script_description = HF_JOBS_TOOL_SPEC["parameters"]["properties"]["script"][
192
+ "description"
193
+ ]
194
+ dependencies_description = HF_JOBS_TOOL_SPEC["parameters"]["properties"][
195
+ "dependencies"
196
+ ]["description"]
197
+
198
+ assert "For non-trivial hf_jobs scripts, use an exact-source workflow" in prompt
199
+ assert "Submit the exact tested script source or the exact tested sandbox file" in (
200
+ prompt
201
+ )
202
+ assert "Do not reconstruct a similar script from memory" in prompt
203
+ assert "For training scripts, make sure one training step succeeds" in prompt
204
+ assert "plus one evaluation step when the final workflow includes evaluation" in (
205
+ prompt
206
+ )
207
+ assert "assert required dataset columns exist" in prompt
208
+ assert "assert hub_model_id and trackio_space_id contain no placeholders" in prompt
209
+ assert (
210
+ "include every imported third-party package in hf_jobs.dependencies" in prompt
211
+ )
212
+ assert "CORE ML DEPENDENCY FRESHNESS" in prompt
213
+ assert "Do not rely on preinstalled packages in sandboxes or HF Jobs" in prompt
214
+ assert "Use unpinned latest stable versions by default" in prompt
215
+ assert "kernels~=0.12.0" in prompt
216
+ assert "Do NOT fall back to default attention or compiled flash-attn" in prompt
217
+ assert "never choose T4 sandboxes or T4 HF Jobs" in prompt
218
+ assert "T4 is pre-Ampere" in prompt
219
+ assert (
220
+ "Never leave placeholder values such as <username>, <model-name>, <project>, TODO"
221
+ in prompt
222
+ )
223
+
224
+ assert "submit the exact tested script source or exact tested sandbox file" in (
225
+ jobs_description
226
+ )
227
+ assert "Do NOT reconstruct a similar script from memory" in jobs_description
228
+ assert "make sure one training step succeeds" in jobs_description
229
+ assert "when the final workflow includes evaluation" in jobs_description
230
+ assert "Training scripts MUST fail fast on missing dataset columns" in (
231
+ jobs_description
232
+ )
233
+ assert (
234
+ "Do NOT leave placeholders such as <username>, <model-name>, <project>, TODO"
235
+ in (jobs_description)
236
+ )
237
+ assert "dependencies MUST include every imported third-party package" in (
238
+ jobs_description
239
+ )
240
+ assert "Do NOT install compiled flash-attn" in jobs_description
241
+ assert "never choose T4 sandboxes or T4 HF Jobs" in jobs_description
242
+ assert "T4 is pre-Ampere" in jobs_description
243
+ assert "Do NOT rely on preinstalled ML packages" in jobs_description
244
+ assert "Use unpinned latest stable versions by default" in jobs_description
245
+ assert "kernels~=0.12.0" in jobs_description
246
+ assert "torch, transformers, trl, accelerate, datasets, trackio" in (
247
+ jobs_description
248
+ )
249
+ assert (
250
+ "exact tested script source or exact tested sandbox file" in script_description
251
+ )
252
+ assert "Must include every imported third-party package" in dependencies_description
253
+ assert "Common training set: ['torch', 'transformers', 'trl'" in (
254
+ dependencies_description
255
+ )
256
+ assert "kernels~=0.12.0" in dependencies_description
257
+
258
+
259
+ def test_rendered_prompt_contains_hf_jobs_safety_guidance(monkeypatch):
260
+ monkeypatch.setattr(
261
+ "agent.context_manager.manager._get_hf_username", lambda _token=None: "tester"
262
+ )
263
+
264
+ context_manager = ContextManager(tool_specs=[], hf_token="hf-token")
265
+ prompt = context_manager.system_prompt
266
+
267
+ assert "For non-trivial hf_jobs scripts, use an exact-source workflow" in prompt
268
+ assert "GPU preflight is mandatory before hf_jobs" in prompt
269
+ assert "Never leave placeholder values such as <username>" in prompt
270
+ assert (
271
+ "include every imported third-party package in hf_jobs.dependencies" in prompt
272
+ )
273
+ assert "CORE ML DEPENDENCY FRESHNESS" in prompt
274
+ assert "Print the installed versions before model loading" in prompt
275
+ assert "kernels~=0.12.0" in prompt
276
+ assert "never choose T4 sandboxes or T4 HF Jobs" in prompt
277
+
278
+
279
  def test_local_tool_runtime_excludes_sandbox_create():
280
  tool_names = {tool.name for tool in create_builtin_tools(local_mode=True)}
281
 
 
319
  monkeypatch.setattr(
320
  agent_loop, "teardown_session_sandbox", fake_teardown_session_sandbox
321
  )
322
+ monkeypatch.setattr(
323
+ "agent.context_manager.manager._get_hf_username", lambda _token=None: "tester"
324
+ )
325
 
326
  submission_queue = asyncio.Queue()
327
  event_queue = asyncio.Queue()
 
347
  assert ready.event_type == "ready"
348
  assert started == [session_holder[0]]
349
  assert session_holder[0].local_mode is False
350
+ assert session_holder[0].autonomous_mode is False
351
+ assert "Autonomous=false" in session_holder[0].context_manager.system_prompt
352
+
353
+ await submission_queue.put(
354
+ SimpleNamespace(
355
+ operation=SimpleNamespace(op_type=OpType.SHUTDOWN, data=None),
356
+ )
357
+ )
358
+ await asyncio.wait_for(task, timeout=1)
359
+
360
+ assert torn_down == [session_holder[0]]
361
+
362
+
363
+ @pytest.mark.asyncio
364
+ async def test_submission_loop_renders_autonomous_prompt(monkeypatch):
365
+ started = []
366
+ torn_down = []
367
+
368
+ class FakeToolRouter:
369
+ tools = {}
370
+
371
+ def get_tool_specs_for_llm(self):
372
+ return []
373
+
374
+ async def __aenter__(self):
375
+ return self
376
+
377
+ async def __aexit__(self, exc_type, exc, tb):
378
+ return None
379
+
380
+ monkeypatch.setattr(
381
+ agent_loop, "start_cpu_sandbox_preload", lambda session: started.append(session)
382
+ )
383
+
384
+ async def fake_teardown_session_sandbox(session):
385
+ torn_down.append(session)
386
+
387
+ monkeypatch.setattr(
388
+ agent_loop, "teardown_session_sandbox", fake_teardown_session_sandbox
389
+ )
390
+ monkeypatch.setattr(
391
+ "agent.context_manager.manager._get_hf_username",
392
+ lambda _token=None: "should-not-be-used",
393
+ )
394
+
395
+ submission_queue = asyncio.Queue()
396
+ event_queue = asyncio.Queue()
397
+ session_holder = [None]
398
+ config = Config.model_validate(
399
+ {"model_name": "openai/gpt-5.5:fal-ai", "save_sessions": False}
400
+ )
401
+
402
+ task = asyncio.create_task(
403
+ agent_loop.submission_loop(
404
+ submission_queue,
405
+ event_queue,
406
+ config=config,
407
+ tool_router=FakeToolRouter(),
408
+ session_holder=session_holder,
409
+ hf_token="hf-token",
410
+ user_id="tester",
411
+ hf_username="tester",
412
+ local_mode=False,
413
+ autonomous_mode=True,
414
+ )
415
+ )
416
+
417
+ ready = await asyncio.wait_for(event_queue.get(), timeout=1)
418
+ assert ready.event_type == "ready"
419
+ assert started == [session_holder[0]]
420
+ assert session_holder[0].autonomous_mode is True
421
+ assert "User=tester" in session_holder[0].context_manager.system_prompt
422
+ assert "Autonomous=true" in session_holder[0].context_manager.system_prompt
423
+ assert "Autonomous mode is active for this session" in (
424
+ session_holder[0].context_manager.system_prompt
425
+ )
426
+ assert "Autonomous mode is not active for this session" not in (
427
+ session_holder[0].context_manager.system_prompt
428
+ )
429
+ assert "NEVER respond with only text" in (
430
+ session_holder[0].context_manager.system_prompt
431
+ )
432
 
433
  await submission_queue.put(
434
  SimpleNamespace(
tests/unit/test_session_manager_persistence.py CHANGED
@@ -17,7 +17,7 @@ _BACKEND_DIR = Path(__file__).resolve().parent.parent.parent / "backend"
17
  if str(_BACKEND_DIR) not in sys.path:
18
  sys.path.insert(0, str(_BACKEND_DIR))
19
 
20
- from agent.core.model_ids import KIMI_K26_MODEL_ID # noqa: E402
21
  from agent.core.session_persistence import NoopSessionStore # noqa: E402
22
  from agent.core.usage_thresholds import USAGE_THRESHOLD_TOOL_NAME # noqa: E402
23
  from agent.core.yolo_budget import YOLO_BUDGET_TOOL_NAME # noqa: E402
@@ -217,6 +217,33 @@ async def test_reset_session_usage_window_updates_runtime_and_store():
217
  }
218
 
219
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
  def test_usage_threshold_pending_approval_serializes_and_restores():
221
  manager = _manager_with_store(NoopSessionStore())
222
  pending = {
@@ -826,10 +853,10 @@ async def test_yolo_budget_checker_uses_local_ledger_when_billing_lags(monkeypat
826
  assert pending["billing_source"] == "hf_billing_current_session"
827
 
828
 
829
- def test_unknown_saved_model_defaults_to_kimi():
830
  model = SessionManager._model_from_saved_metadata("unsupported/model")
831
 
832
- assert model == KIMI_K26_MODEL_ID
833
 
834
 
835
  @pytest.mark.asyncio
 
17
  if str(_BACKEND_DIR) not in sys.path:
18
  sys.path.insert(0, str(_BACKEND_DIR))
19
 
20
+ from agent.core.model_ids import GLM_52_MODEL_ID # noqa: E402
21
  from agent.core.session_persistence import NoopSessionStore # noqa: E402
22
  from agent.core.usage_thresholds import USAGE_THRESHOLD_TOOL_NAME # noqa: E402
23
  from agent.core.yolo_budget import YOLO_BUDGET_TOOL_NAME # noqa: E402
 
217
  }
218
 
219
 
220
+ @pytest.mark.asyncio
221
+ async def test_activate_session_preserves_usage_window_and_billing_id():
222
+ store = RestoreStore()
223
+ manager = _manager_with_store(store)
224
+ agent_session = _runtime_agent_session("s1")
225
+ manager.sessions["s1"] = agent_session
226
+ usage_window_started_at = datetime(2026, 6, 5, 12, 30, tzinfo=UTC)
227
+ billing_session_id = agent_session.inference_billing_session_id
228
+ old_last_active_at = datetime(2000, 1, 1)
229
+ agent_session.usage_window_started_at = usage_window_started_at
230
+ agent_session.last_active_at = old_last_active_at
231
+ agent_session.usage_warning_spend_cache = {"spend_usd": 12.0}
232
+
233
+ info = await manager.activate_session("s1")
234
+
235
+ assert agent_session.usage_window_started_at == usage_window_started_at
236
+ assert agent_session.inference_billing_session_id == billing_session_id
237
+ assert agent_session.session.inference_billing_session_id == billing_session_id
238
+ assert agent_session.usage_warning_spend_cache == {"spend_usd": 12.0}
239
+ assert agent_session.last_active_at > old_last_active_at
240
+ assert info is not None
241
+ assert info["usage_window_started_at"] == usage_window_started_at.isoformat()
242
+ session_id, fields = store.updated_fields[-1]
243
+ assert session_id == "s1"
244
+ assert fields == {"last_active_at": agent_session.last_active_at}
245
+
246
+
247
  def test_usage_threshold_pending_approval_serializes_and_restores():
248
  manager = _manager_with_store(NoopSessionStore())
249
  pending = {
 
853
  assert pending["billing_source"] == "hf_billing_current_session"
854
 
855
 
856
+ def test_unknown_saved_model_defaults_to_glm():
857
  model = SessionManager._model_from_saved_metadata("unsupported/model")
858
 
859
+ assert model == GLM_52_MODEL_ID
860
 
861
 
862
  @pytest.mark.asyncio
tests/unit/test_session_resume.py CHANGED
@@ -60,7 +60,7 @@ class _FakeContext:
60
  class _FakeSession:
61
  def __init__(self, *, user_id: str | None = "user-a") -> None:
62
  self.context_manager = _FakeContext()
63
- self.config = SimpleNamespace(model_name="moonshotai/Kimi-K2.6")
64
  self.session_id = "current-session"
65
  self.session_start_time = "2026-01-02T00:00:00"
66
  self.user_id = user_id
 
60
  class _FakeSession:
61
  def __init__(self, *, user_id: str | None = "user-a") -> None:
62
  self.context_manager = _FakeContext()
63
+ self.config = SimpleNamespace(model_name="moonshotai/Kimi-K2.7-Code")
64
  self.session_id = "current-session"
65
  self.session_start_time = "2026-01-02T00:00:00"
66
  self.user_id = user_id
tests/unit/test_sft_tagger.py CHANGED
@@ -21,7 +21,7 @@ def _traj(events=None, messages=None, model="anthropic/claude-opus-4.8:fal-ai"):
21
 
22
  def test_model_family():
23
  assert "model:opus" in tag_session(_traj(model="anthropic/claude-opus-4.8:fal-ai"))
24
- assert "model:kimi" in tag_session(_traj(model="moonshotai/Kimi-K2.6"))
25
  assert "model:other" in tag_session(_traj(model="unknown-model-xyz"))
26
 
27
 
 
21
 
22
  def test_model_family():
23
  assert "model:opus" in tag_session(_traj(model="anthropic/claude-opus-4.8:fal-ai"))
24
+ assert "model:kimi" in tag_session(_traj(model="moonshotai/Kimi-K2.7-Code"))
25
  assert "model:other" in tag_session(_traj(model="unknown-model-xyz"))
26
 
27
 
tests/unit/test_thinking_history.py CHANGED
@@ -1,5 +1,7 @@
 
1
  from types import SimpleNamespace
2
 
 
3
  import pytest
4
  from litellm import ChatCompletionMessageToolCall, Message
5
 
@@ -99,3 +101,160 @@ async def test_streaming_call_returns_wire_safe_result(monkeypatch):
99
 
100
  assert result.content == "done"
101
  assert result.token_count == 3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
  from types import SimpleNamespace
3
 
4
+ import httpx
5
  import pytest
6
  from litellm import ChatCompletionMessageToolCall, Message
7
 
 
101
 
102
  assert result.content == "done"
103
  assert result.token_count == 3
104
+
105
+
106
+ @pytest.mark.asyncio
107
+ async def test_streaming_call_retries_read_timeout_before_output(monkeypatch):
108
+ async def timeout_stream():
109
+ raise httpx.ReadTimeout("Timeout on reading data from socket")
110
+ yield # pragma: no cover
111
+
112
+ async def success_stream():
113
+ yield SimpleNamespace(
114
+ choices=[
115
+ SimpleNamespace(
116
+ delta=SimpleNamespace(content="ok", tool_calls=None),
117
+ finish_reason="stop",
118
+ )
119
+ ],
120
+ )
121
+ yield SimpleNamespace(choices=[], usage=SimpleNamespace(total_tokens=2))
122
+
123
+ attempts = 0
124
+
125
+ async def fake_acompletion(**_kwargs):
126
+ nonlocal attempts
127
+ attempts += 1
128
+ if attempts == 1:
129
+ return timeout_stream()
130
+ return success_stream()
131
+
132
+ events = []
133
+
134
+ async def send_event(event):
135
+ events.append(event)
136
+
137
+ sleeps = []
138
+
139
+ async def fake_sleep(delay):
140
+ sleeps.append(delay)
141
+
142
+ session = SimpleNamespace(
143
+ config=SimpleNamespace(model_name="MiniMaxAI/MiniMax-M3:novita"),
144
+ is_cancelled=False,
145
+ send_event=send_event,
146
+ )
147
+ monkeypatch.setattr("agent.core.agent_loop.acompletion", fake_acompletion)
148
+ monkeypatch.setattr("agent.core.agent_loop.asyncio.sleep", fake_sleep)
149
+
150
+ result = await _call_llm_streaming(
151
+ session,
152
+ messages=[Message(role="user", content="hi")],
153
+ tools=[],
154
+ llm_params={"model": "openai/MiniMaxAI/MiniMax-M3:novita"},
155
+ )
156
+
157
+ assert attempts == 2
158
+ assert sleeps == [5]
159
+ assert result.content == "ok"
160
+ assert [event.event_type for event in events] == [
161
+ "tool_log",
162
+ "assistant_chunk",
163
+ "llm_call",
164
+ ]
165
+
166
+
167
+ @pytest.mark.asyncio
168
+ async def test_streaming_call_does_not_retry_after_partial_output(monkeypatch):
169
+ async def partial_timeout_stream():
170
+ yield SimpleNamespace(
171
+ choices=[
172
+ SimpleNamespace(
173
+ delta=SimpleNamespace(content="partial", tool_calls=None),
174
+ finish_reason=None,
175
+ )
176
+ ],
177
+ )
178
+ raise httpx.ReadTimeout("Timeout on reading data from socket")
179
+
180
+ attempts = 0
181
+
182
+ async def fake_acompletion(**_kwargs):
183
+ nonlocal attempts
184
+ attempts += 1
185
+ return partial_timeout_stream()
186
+
187
+ events = []
188
+
189
+ async def send_event(event):
190
+ events.append(event)
191
+
192
+ session = SimpleNamespace(
193
+ config=SimpleNamespace(model_name="MiniMaxAI/MiniMax-M3:novita"),
194
+ is_cancelled=False,
195
+ send_event=send_event,
196
+ )
197
+ monkeypatch.setattr("agent.core.agent_loop.acompletion", fake_acompletion)
198
+
199
+ with pytest.raises(httpx.ReadTimeout):
200
+ await _call_llm_streaming(
201
+ session,
202
+ messages=[Message(role="user", content="hi")],
203
+ tools=[],
204
+ llm_params={"model": "openai/MiniMaxAI/MiniMax-M3:novita"},
205
+ )
206
+
207
+ assert attempts == 1
208
+ assert [event.event_type for event in events] == [
209
+ "assistant_chunk",
210
+ "assistant_stream_end",
211
+ "llm_call",
212
+ ]
213
+
214
+
215
+ @pytest.mark.asyncio
216
+ async def test_streaming_call_stops_retry_when_cancelled_during_delay(monkeypatch):
217
+ async def timeout_stream():
218
+ raise httpx.ReadTimeout("Timeout on reading data from socket")
219
+ yield # pragma: no cover
220
+
221
+ attempts = 0
222
+
223
+ async def fake_acompletion(**_kwargs):
224
+ nonlocal attempts
225
+ attempts += 1
226
+ return timeout_stream()
227
+
228
+ events = []
229
+
230
+ class CancellableSession:
231
+ def __init__(self):
232
+ self.config = SimpleNamespace(model_name="MiniMaxAI/MiniMax-M3:novita")
233
+ self._cancelled = asyncio.Event()
234
+
235
+ @property
236
+ def is_cancelled(self):
237
+ return self._cancelled.is_set()
238
+
239
+ def cancel(self):
240
+ self._cancelled.set()
241
+
242
+ async def send_event(self, event):
243
+ events.append(event)
244
+ if event.event_type == "tool_log":
245
+ self.cancel()
246
+
247
+ session = CancellableSession()
248
+ monkeypatch.setattr("agent.core.agent_loop.acompletion", fake_acompletion)
249
+
250
+ result = await _call_llm_streaming(
251
+ session,
252
+ messages=[Message(role="user", content="hi")],
253
+ tools=[],
254
+ llm_params={"model": "openai/MiniMaxAI/MiniMax-M3:novita"},
255
+ )
256
+
257
+ assert attempts == 1
258
+ assert result.content is None
259
+ assert session.is_cancelled is True
260
+ assert [event.event_type for event in events] == ["tool_log"]