@simplexai/localmodels-linux-x64 0.1.0-dev.36 → 0.1.0-dev.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +119 -98
  3. package/kit.py +1 -0
  4. package/modules/localmodels/__init__.py +1 -1
  5. package/modules/localmodels/__main__.py +9 -3
  6. package/modules/localmodels/bifrost_config.py +188 -0
  7. package/modules/localmodels/budget.py +13 -2
  8. package/modules/localmodels/catalog.py +51 -320
  9. package/modules/localmodels/catalog_add.py +2 -8
  10. package/modules/localmodels/catalog_recipes.py +321 -0
  11. package/modules/localmodels/cli_parser.py +4 -1
  12. package/modules/localmodels/console.py +5 -4
  13. package/modules/localmodels/contracts.py +13 -3
  14. package/modules/localmodels/debug_cli.py +158 -0
  15. package/modules/localmodels/debug_mode.py +727 -0
  16. package/modules/localmodels/debug_stub_server.py +192 -0
  17. package/modules/localmodels/decode_calibration.json +1 -1
  18. package/modules/localmodels/decode_calibration.py +34 -17
  19. package/modules/localmodels/gateway.py +21 -155
  20. package/modules/localmodels/gateway_accept.py +201 -0
  21. package/modules/localmodels/gateway_bifrost.py +19 -184
  22. package/modules/localmodels/gateway_cli.py +11 -4
  23. package/modules/localmodels/gateway_foundations.py +2 -4
  24. package/modules/localmodels/gateway_probe.py +0 -1
  25. package/modules/localmodels/gateway_server.py +2 -3
  26. package/modules/localmodels/gpu_specs.py +12 -0
  27. package/modules/localmodels/guard.py +2 -7
  28. package/modules/localmodels/harness.py +16 -129
  29. package/modules/localmodels/harness_cleanup.py +135 -0
  30. package/modules/localmodels/harness_gateway.py +16 -14
  31. package/modules/localmodels/harness_probe.py +12 -4
  32. package/modules/localmodels/hosts.py +25 -2
  33. package/modules/localmodels/http_local.py +59 -0
  34. package/modules/localmodels/install.py +23 -8
  35. package/modules/localmodels/library_gateway.py +9 -9
  36. package/modules/localmodels/library_jobs.py +76 -27
  37. package/modules/localmodels/library_serve.py +12 -1
  38. package/modules/localmodels/library_state.py +6 -1
  39. package/modules/localmodels/llm_rank.py +102 -9
  40. package/modules/localmodels/probe.py +108 -174
  41. package/modules/localmodels/process_identity.py +109 -154
  42. package/modules/localmodels/process_windows.py +86 -0
  43. package/modules/localmodels/recommend.py +1 -1
  44. package/modules/localmodels/recommend_cli.py +14 -6
  45. package/modules/localmodels/remote_ops.py +65 -0
  46. package/modules/localmodels/remote_ops_service.py +14 -2
  47. package/modules/localmodels/runtime_args.py +10 -3
  48. package/modules/localmodels/runtime_auth.py +5 -9
  49. package/modules/localmodels/runtime_cli.py +128 -129
  50. package/modules/localmodels/runtime_discovery.py +84 -0
  51. package/modules/localmodels/runtime_install.py +101 -0
  52. package/modules/localmodels/runtime_releases.py +302 -0
  53. package/modules/localmodels/service_stop.py +8 -108
  54. package/modules/localmodels/service_upgrade.py +394 -63
  55. package/modules/localmodels/services_cli.py +24 -14
  56. package/modules/localmodels/setup_inspection.py +97 -9
  57. package/modules/localmodels/setup_text.py +7 -0
  58. package/modules/localmodels/sizecalc.py +0 -1
  59. package/modules/localmodels/stack.py +14 -221
  60. package/modules/localmodels/stack_arena.py +732 -0
  61. package/modules/localmodels/stack_args.py +15 -9
  62. package/modules/localmodels/stack_auto.py +384 -3
  63. package/modules/localmodels/stack_aux_gpu.py +4 -3
  64. package/modules/localmodels/stack_capacity.py +138 -0
  65. package/modules/localmodels/stack_cleanup.py +9 -4
  66. package/modules/localmodels/stack_cli.py +286 -0
  67. package/modules/localmodels/stack_compose.py +58 -25
  68. package/modules/localmodels/stack_console.py +9 -6
  69. package/modules/localmodels/stack_hardware.py +92 -263
  70. package/modules/localmodels/stack_hardware_text.py +263 -0
  71. package/modules/localmodels/stack_journal.py +3 -9
  72. package/modules/localmodels/stack_ledger.py +48 -18
  73. package/modules/localmodels/stack_lifecycle.py +33 -312
  74. package/modules/localmodels/stack_mcp.py +729 -0
  75. package/modules/localmodels/stack_memory.py +0 -2
  76. package/modules/localmodels/stack_picks.py +59 -12
  77. package/modules/localmodels/stack_plan.py +19 -1
  78. package/modules/localmodels/stack_preflight.py +11 -19
  79. package/modules/localmodels/stack_remove.py +373 -0
  80. package/modules/localmodels/stack_route.py +101 -17
  81. package/modules/localmodels/stack_suite.py +11 -7
  82. package/modules/localmodels/stack_summary.py +14 -0
  83. package/modules/localmodels/stack_try.py +238 -24
  84. package/modules/localmodels/stack_try_client.py +53 -15
  85. package/modules/localmodels/stack_try_docs.py +2 -2
  86. package/modules/localmodels/stack_view.py +24 -171
  87. package/modules/localmodels/stack_view_access.py +114 -1
  88. package/modules/localmodels/stack_view_agent.py +3 -13
  89. package/modules/localmodels/stack_view_hub.py +9 -10
  90. package/modules/localmodels/stack_view_llm.py +1 -1
  91. package/modules/localmodels/stack_view_sandbox.py +2 -2
  92. package/modules/localmodels/stack_view_schema.py +183 -0
  93. package/modules/localmodels/stack_view_serve.py +7 -1
  94. package/modules/localmodels/stack_view_service.py +1 -2
  95. package/modules/localmodels/stack_view_text.py +13 -9
  96. package/modules/localmodels/stack_warm.py +3 -0
  97. package/modules/localmodels/stack_warm_store.py +517 -0
  98. package/modules/localmodels/tui.py +28 -4
  99. package/modules/localmodels/tui_dialogs.py +136 -0
  100. package/modules/localmodels/tui_modals.py +279 -0
  101. package/modules/localmodels/tui_screen.py +113 -154
  102. package/modules/localmodels/tui_views.py +134 -203
  103. package/modules/localmodels/web/index.html +510 -101
  104. package/modules/localmodels/web/sizecalc/app.js +363 -10
  105. package/modules/localmodels/web/sizecalc/page.html +27 -3
  106. package/modules/localmodels/web/view/fleet.html +11 -2
  107. package/modules/localmodels/web/view/fleet.js +191 -17
  108. package/modules/localmodels/web/view/i18n.js +3 -2
  109. package/modules/localmodels/web/view/index.html +1 -1
  110. package/modules/localmodels/web/view/nav.js +22 -3
  111. package/modules/localmodels/web/view/view.css +63 -18
  112. package/modules/localmodels/web/view/view.js +169 -32
  113. package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/METADATA +1 -1
  114. package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/RECORD +115 -94
  115. package/package.json +1 -1
  116. package/tool.json +1 -1
  117. package/modules/localmodels/engines-strata-0.1.49.1.json +0 -31
  118. /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/WHEEL +0 -0
  119. /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/entry_points.txt +0 -0
  120. /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/licenses/NOTICE +0 -0
  121. /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev37.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -22,11 +22,11 @@ from localmodels import (
22
22
  suite,
23
23
  vision,
24
24
  )
25
- from localmodels.budget import gib
25
+ from localmodels.budget import gib, holders, placements
26
26
  from localmodels.context_policy import AgentPosture
27
27
  from localmodels.probe import HostFacts
28
28
  from localmodels.records import PinnedFile, Plan
29
- from localmodels.stack_plan import Parts, StackError, StackOptions, own_name
29
+ from localmodels.stack_plan import Hardware, Parts, StackError, StackOptions, own_name
30
30
 
31
31
 
32
32
  def validate(options: StackOptions, facts: HostFacts) -> None:
@@ -51,6 +51,30 @@ def validate(options: StackOptions, facts: HostFacts) -> None:
51
51
  )
52
52
 
53
53
 
54
+ def _approved_fast_pick(
55
+ seen: Hardware, options: StackOptions, primary_id: str, approved: Plan
56
+ ) -> stack_picks.Pick | None:
57
+ """Keep the approved routed secondary model when observational speeds change on rebuild."""
58
+ target_id = str(approved.get("model", {}).get("id") or "")
59
+ if not target_id or target_id == primary_id:
60
+ return None
61
+ gpu = options.get("gpu")
62
+ cards = [c for c in seen["cards"] if c["index"] == gpu] if gpu is not None else seen["cards"]
63
+ free = [c for c in cards if c["auto"] and c["llm"]]
64
+ shared = not free
65
+ gpus = approved["placement"].get("gpus")
66
+ first_gpu = gpus[0] if isinstance(gpus, list) and gpus else None
67
+ pref = first_gpu.get("index") if isinstance(first_gpu, dict) else None
68
+ ordered = sorted(
69
+ free or cards, key=lambda c: (c["index"] != pref, -c["free_bytes"], c["index"])
70
+ )
71
+ for card in ordered:
72
+ for fit in card["llm"]:
73
+ if fit["id"] == target_id and fit["decode_tok_s"] is not None:
74
+ return {**fit, "role": "fastest", "card": card["index"], "shared": shared}
75
+ return None
76
+
77
+
54
78
  def add(
55
79
  facts: HostFacts,
56
80
  options: StackOptions,
@@ -71,7 +95,11 @@ def add(
71
95
  if options.get("gpu") is not None:
72
96
  offered = stack_picks.picks([c for c in seen["cards"] if c["index"] == options["gpu"]])
73
97
  pick = next((p for p in offered if p["role"] == "fastest"), None)
74
- if pick is None or pick["id"] == parts["llm"]["model"]["id"]:
98
+ if approved is not None:
99
+ kept = _approved_fast_pick(seen, options, parts["llm"]["model"]["id"], approved)
100
+ if kept is not None:
101
+ pick = kept
102
+ if pick is None or pick["decode_tok_s"] is None or pick["id"] == parts["llm"]["model"]["id"]:
75
103
  raise StackError("--route fastest has no distinct, worthwhile fastest pick on this device")
76
104
  window = int(str(parts["llm"]["launch"]["window"]))
77
105
  posture = replace(
@@ -132,18 +160,9 @@ def add(
132
160
  resolver=resolver,
133
161
  )
134
162
  except deploy.AgentMemoryError as exc:
135
- needed, usable = exc.needed_bytes, exc.available_bytes
136
- capacity = (
137
- "the primary Strata expert cache retains its approved allocation"
138
- if _strata(parts["llm"]) is not None
139
- else f"only {gib(usable)} remains"
140
- )
141
- raise StackError(
142
- f"--route fastest: {pick['id']} needs at least about {gib(needed)} {exc.memory} "
143
- f"including KV/runtime; {capacity}, short about "
144
- f"{gib(max(0, needed - usable))}; primary window is unchanged; "
145
- "use a second idle card or a larger memory tier"
146
- ) from None
163
+ raise _memory_refusal(pick["id"], exc, facts, placement, parts["llm"], approved) from None
164
+ if reads_images(parts["llm"]) != reads_images(fast):
165
+ raise _vision_mismatch(parts["llm"], fast)
147
166
  _, ram = stack_suite.fit_llama_ram(
148
167
  facts,
149
168
  options,
@@ -167,6 +186,71 @@ def add(
167
186
  )
168
187
 
169
188
 
189
+ def reads_images(part: Plan) -> bool:
190
+ return vision.reads_pictures(part["launch"]) and part["launch"].get("vision") not in (
191
+ None,
192
+ "",
193
+ "off",
194
+ )
195
+
196
+
197
+ def _target_vram(facts: HostFacts, placement: str, primary: Plan) -> int:
198
+ candidates = [p for p in placements(facts, planning=True) if not p.pooled and p.gpu_indices]
199
+ if placement != "auto":
200
+ matched = [p for p in candidates if p.id == placement]
201
+ return max((p.budget.total_device_bytes for p in matched), default=0)
202
+ primary_indices = {
203
+ int(g["index"])
204
+ for g in cast(list[dict[str, Any]], primary["placement"].get("gpus") or [])
205
+ if isinstance(g.get("index"), int)
206
+ }
207
+ held_by = holders(facts)
208
+ free_indices = {g["index"] for g in facts.get("gpus") or [] if g["uuid"] not in held_by}
209
+ allowed = primary_indices | free_indices
210
+ eligible = [p for p in candidates if not p.conflicts and set(p.gpu_indices).issubset(allowed)]
211
+ return max((p.budget.total_device_bytes for p in eligible), default=0)
212
+
213
+
214
+ def _memory_refusal(
215
+ model_id: str,
216
+ exc: deploy.AgentMemoryError,
217
+ facts: HostFacts,
218
+ placement: str,
219
+ primary: Plan,
220
+ approved: Plan | None,
221
+ ) -> StackError:
222
+ needed, usable = exc.needed_bytes, exc.available_bytes
223
+ if _strata(primary) is not None:
224
+ capacity = (
225
+ "the primary Strata expert cache retains its approved allocation"
226
+ if approved is not None
227
+ else "the primary Strata expert cache fills the card"
228
+ )
229
+ else:
230
+ capacity = f"only {gib(usable)} remains"
231
+ largest_vram = _target_vram(facts, placement, primary)
232
+ action = (
233
+ "use a second idle card"
234
+ if exc.memory in ("GPU memory", "VRAM") and largest_vram >= 88 * (1 << 30)
235
+ else "use a second idle card or a larger memory tier"
236
+ )
237
+ return StackError(
238
+ f"--route fastest: {model_id} needs at least about {gib(needed)} {exc.memory} "
239
+ f"including KV/runtime; {capacity}, short about "
240
+ f"{gib(max(0, needed - usable))}; primary window is unchanged; {action}"
241
+ )
242
+
243
+
244
+ def _vision_mismatch(primary: Plan, fast: Plan) -> StackError:
245
+ primary_mode = "reads images" if reads_images(primary) else "is text-only"
246
+ fast_mode = "reads images" if reads_images(fast) else "is text-only"
247
+ return StackError(
248
+ "--route fastest requires matching image input support between the primary LLM "
249
+ f"({primary['model']['id']} {primary_mode}) and fastest LLM "
250
+ f"({fast['model']['id']} {fast_mode}); pass --vision off for text-only routing"
251
+ )
252
+
253
+
170
254
  def reusable(
171
255
  part: Plan, primary: Plan, posture: AgentPosture, approved: Plan | None = None
172
256
  ) -> bool:
@@ -181,8 +265,8 @@ def reusable(
181
265
  return (
182
266
  int(str(launch.get("window") or 0)) >= int(str(primary["launch"]["window"]))
183
267
  and launch.get("slots") == posture.slots
184
- and (launch.get("vision") not in (None, "", "off"))
185
- == vision.llama_reader_enabled(entry.mmproj, posture.vision)
268
+ and reads_images(part) == reads_images(primary)
269
+ and reads_images(part) == vision.llama_reader_enabled(entry.mmproj, posture.vision)
186
270
  and kv_matches
187
271
  )
188
272
 
@@ -3,7 +3,7 @@
3
3
  The Strata branch runs only for a recipe named with ``--llm``: the Strata LLM and a GPU decision
4
4
  model share one idle card, and what does not fit is refused rather than replaced. Both branches
5
5
  fit the CPU auxiliaries (embedding, reranker, STT when asked for; the free web search unless
6
- --no-search; the debug TTS only when the plan opts in) into the host RAM the LLM and decision
6
+ --search; the debug TTS only when the plan opts in) into the host RAM the LLM and decision
7
7
  model leave, each a memory-bounded, swap-free unit in one slice (suite.py). stack_compose.assemble prices the parts as one stack."""
8
8
 
9
9
  from __future__ import annotations
@@ -41,7 +41,8 @@ from localmodels.suite import bounded_ram
41
41
  AUX_TASKS = ("embedding", "reranker", "stt")
42
42
  # The auxiliaries a front-end's background worker installs (service_jobs.ROLES less decision).
43
43
  FOUNDATION_TASKS = ("embedding", "reranker")
44
- # Planned unless the plan's own option is False (--no-search); plans that omit it include it.
44
+ # Planned when the plan's own option is set (--search, off by default since 2026-11-17); plans
45
+ # that omit it are older plans, which included it.
45
46
  DEFAULT_TASKS = ("search",)
46
47
  # Debug and test auxiliaries each join on the same-named plan option, fitted after AUX_TASKS.
47
48
  OPT_IN_TASKS = ("tts",)
@@ -84,8 +85,9 @@ def add_arguments(plan: argparse._ActionsContainer) -> None:
84
85
  nargs=0,
85
86
  const=True,
86
87
  default=False,
87
- help="free web search (DuckDuckGo first, through ddgs on loopback) as the gateway's "
88
- "web_search: on by default since roadmap decision 37, unaffected by --aux",
88
+ help="free web search (DuckDuckGo first, through ddgs on loopback); under Bifrost it is "
89
+ "injected as web_search into every LLM request, so it is off by default (roadmap "
90
+ "decision 55, amending 37) and unaffected by --aux",
89
91
  )
90
92
  search.add_argument(
91
93
  "--no-search",
@@ -93,7 +95,7 @@ def add_arguments(plan: argparse._ActionsContainer) -> None:
93
95
  nargs=0,
94
96
  const=True,
95
97
  default=False,
96
- help="leave out the free web search",
98
+ help="leave out the free web search; new plans already do, so this drops an installed one",
97
99
  )
98
100
 
99
101
 
@@ -101,7 +103,9 @@ def with_aux_tasks(options: StackOptions, args: argparse.Namespace) -> StackOpti
101
103
  """``options`` with the requested auxiliary subset and explicit search selection."""
102
104
  if options["aux"] and args.aux != "auto":
103
105
  options["aux_tasks"] = args.aux.split(",")
104
- options["search"] = not getattr(args, "no_search", False)
106
+ options["search"] = bool(getattr(args, "search", False)) and not getattr(
107
+ args, "no_search", False
108
+ )
105
109
  return options
106
110
 
107
111
 
@@ -591,7 +595,7 @@ def aux_plans(
591
595
  "search: the search terms of a web search go through this host's search service to "
592
596
  "public search engines such as DuckDuckGo, and to You.com (no key, 100 per day) when "
593
597
  "none of those has results; no account or key needed, "
594
- "subject to each engine's rate limits; use --no-search when not needed"
598
+ "subject to each engine's rate limits; leave out --search when not needed"
595
599
  )
596
600
  return planned
597
601
 
@@ -278,8 +278,22 @@ def _styled(t: console.Term, row: str, first: bool) -> str:
278
278
  if row.startswith(prefix):
279
279
  head, _, cmd = row.rpartition(": ")
280
280
  return t.paint(head + ": ", "bold") + t.paint(cmd, "cyan", "bold")
281
+ if row.startswith(" fix: "):
282
+ lead, _, fix = row.partition("fix: ")
283
+ return lead + t.paint("fix: ", "cyan", "bold") + fix
281
284
  if row.startswith(" "):
282
285
  return t.paint(row, "dim")
286
+ if row.startswith((" preflight ✗ ", " preflight ! ")):
287
+ mark = "✗" if "✗" in row[:14] else "!"
288
+ head, _, rest = row.partition(f" {mark} ")
289
+ return (
290
+ " "
291
+ + t.paint(head[2:], "cyan", "bold")
292
+ + " "
293
+ + t.paint(mark, "red" if mark == "✗" else "yellow", "bold")
294
+ + " "
295
+ + rest
296
+ )
283
297
  label, gap, rest = row[2:].partition(" ")
284
298
  if not row.startswith(" ") or not gap or not label:
285
299
  return row
@@ -10,13 +10,18 @@ from __future__ import annotations
10
10
 
11
11
  import argparse
12
12
  import base64
13
+ import datetime as dt
13
14
  import http.client
15
+ import json
16
+ import re
14
17
  import sys
18
+ import time
15
19
  import urllib.error
16
20
  import urllib.parse
17
21
  from pathlib import Path
18
22
 
19
23
  from localmodels import (
24
+ bifrost_checks,
20
25
  bifrost_search,
21
26
  cli_help,
22
27
  gateway,
@@ -31,8 +36,9 @@ from localmodels import (
31
36
  stack_verify,
32
37
  vision,
33
38
  )
39
+ from localmodels.records import Plan
34
40
  from localmodels.stack_plan import StackError, StackPlan, command
35
- from localmodels.stack_try_client import DemoError, Gateway
41
+ from localmodels.stack_try_client import DemoError, Gateway, InputError, StreamStats
36
42
 
37
43
  MAX_IMAGE_BYTES = 10 << 20
38
44
  MAX_QUESTION_CHARS = 8192
@@ -81,21 +87,33 @@ def _search_wired(plan: StackPlan, owned: hosts.Owned) -> bool:
81
87
  )
82
88
 
83
89
 
84
- def _installed(mode: str) -> tuple[Gateway, str | None]:
90
+ def _lacks_vision(part: Plan) -> bool:
91
+ return not vision.reads_pictures(part["launch"]) or part["launch"].get("vision") == "off"
92
+
93
+
94
+ def _check_image_vision(plan: StackPlan) -> None:
95
+ if _lacks_vision(plan["llm"]):
96
+ raise StackError(
97
+ "The installed LLM has no image reader; run "
98
+ f"{command()} install --vision auto with an image-capable --llm."
99
+ )
100
+ fast = plan.get("llm_fast")
101
+ if fast is not None and _lacks_vision(fast):
102
+ raise StackError(
103
+ "The routed fastest LLM has no image reader; "
104
+ f"reinstall without --route fastest or run {command()} install --vision auto."
105
+ )
106
+
107
+
108
+ def _installed(mode: str) -> tuple[Gateway, str | None, StackPlan]:
85
109
  plan = stack_up._accepted()
86
110
  if plan is None:
87
111
  raise StackError(f"No accepted stack is installed; run {command()} install.")
88
112
  if stack_up.drift(plan):
89
113
  raise StackError(f"The installed stack changed; run {command()} install to review it.")
90
114
  embedding = _component(plan, "embedding")
91
- if mode == "image" and (
92
- not vision.reads_pictures(plan["llm"]["launch"])
93
- or plan["llm"]["launch"].get("vision") == "off"
94
- ):
95
- raise StackError(
96
- "The installed LLM has no image reader; run "
97
- f"{command()} install --vision auto with an image-capable --llm."
98
- )
115
+ if mode == "image":
116
+ _check_image_vision(plan)
99
117
  if mode == "docs" and embedding is None:
100
118
  tasks = {"embedding", *(stack_suite.task_of(part) for part in plan["aux"])}
101
119
  aux = ",".join(task for task in stack_suite.AUX_TASKS if task in tasks)
@@ -120,8 +138,6 @@ def _installed(mode: str) -> tuple[Gateway, str | None]:
120
138
  owned = hosts.load_owned(tools["tools_dir"])
121
139
  kind = harness.gateway_kind(gw)
122
140
  if mode == "docs":
123
- from localmodels import bifrost_checks
124
-
125
141
  wired = (
126
142
  bifrost_checks.wired_providers(owned)
127
143
  if kind == "bifrost"
@@ -135,7 +151,7 @@ def _installed(mode: str) -> tuple[Gateway, str | None]:
135
151
  raise StackError(f"Web search is not wired to the gateway; run {command()} stack doctor.")
136
152
  model = gw["group"] if kind == "bifrost" else f"group/{gw['group']}"
137
153
  client = Gateway(f"http://{gw['addr']}", model, gateway_keys.CALLER_KEY, kind)
138
- return client, embedding
154
+ return client, embedding, plan
139
155
 
140
156
 
141
157
  def _image(path: Path) -> str:
@@ -311,37 +327,235 @@ def add_parser(actions: argparse._SubParsersAction[argparse.ArgumentParser]) ->
311
327
  )
312
328
 
313
329
 
330
+ def _chat_log_signatures(addr: str) -> set[str]:
331
+ try:
332
+ rows = bifrost_checks.logs(addr, objects="chat_completion")
333
+ except (urllib.error.URLError, OSError, ValueError, http.client.HTTPException):
334
+ return set()
335
+ return {json.dumps(row, sort_keys=True) for row in rows}
336
+
337
+
338
+ def _utc_ms_now() -> dt.datetime:
339
+ now = dt.datetime.now(dt.timezone.utc)
340
+ return now.replace(microsecond=(now.microsecond // 1000) * 1000)
341
+
342
+
343
+ def _parse_iso_utc(value: str) -> dt.datetime | None:
344
+ text = value.strip()
345
+ if not text:
346
+ return None
347
+ if text.endswith(("Z", "z")):
348
+ text = text[:-1] + "+00:00"
349
+ text = re.sub(
350
+ r"\.(\d+)",
351
+ lambda match: "." + match.group(1)[:6].ljust(6, "0"),
352
+ text,
353
+ count=1,
354
+ )
355
+ try:
356
+ parsed = dt.datetime.fromisoformat(text)
357
+ except ValueError:
358
+ return None
359
+ return (
360
+ parsed.astimezone(dt.timezone.utc)
361
+ if parsed.tzinfo is not None
362
+ else parsed.replace(tzinfo=dt.timezone.utc)
363
+ )
364
+
365
+
366
+ def _row_completion_tokens(row: dict[str, object]) -> int | None:
367
+ usage = row.get("token_usage")
368
+ count = usage.get("completion_tokens") if isinstance(usage, dict) else None
369
+ return count if isinstance(count, int) and not isinstance(count, bool) else None
370
+
371
+
372
+ def _candidate_log_row(
373
+ row: dict[str, object],
374
+ before_logs: set[str],
375
+ started_at: dt.datetime,
376
+ llm_provider: str,
377
+ ) -> bool:
378
+ if row.get("status") != "success":
379
+ return False
380
+ if row.get("provider") not in (gateway_bifrost.FAST_PROVIDER, llm_provider):
381
+ return False
382
+ rule = row.get("routing_rule_id")
383
+ if rule not in (None, "", gateway_bifrost.COMPLEX_RULE, gateway_bifrost.AGENT_RULE):
384
+ return False
385
+ if json.dumps(row, sort_keys=True) in before_logs:
386
+ return False
387
+ raw_ts = row.get("timestamp")
388
+ if raw_ts in (None, ""):
389
+ return True
390
+ if not isinstance(raw_ts, str):
391
+ return False
392
+ parsed = _parse_iso_utc(raw_ts)
393
+ return parsed is not None and parsed >= started_at
394
+
395
+
396
+ def _narrow_candidates(
397
+ candidates: list[dict[str, object]], completion_tokens: int | None
398
+ ) -> list[dict[str, object]]:
399
+ if completion_tokens is None:
400
+ return candidates
401
+ return [
402
+ row
403
+ for row in candidates
404
+ if (tokens := _row_completion_tokens(row)) is None or tokens == completion_tokens
405
+ ]
406
+
407
+
408
+ def _model_attribution(
409
+ response_model: str | None, primary: Plan, fast: Plan, llm_provider: str
410
+ ) -> str | None:
411
+ if not response_model:
412
+ return None
413
+ fast_id = fast["model"]["id"]
414
+ primary_id = primary["model"]["id"]
415
+ fast_aliases = {fast["endpoint"]["model"], fast_id}
416
+ primary_aliases = {primary["endpoint"]["model"], primary_id}
417
+ fast_prefixed = {f"{gateway_bifrost.FAST_PROVIDER}/{name}" for name in fast_aliases}
418
+ primary_prefixed = {f"{llm_provider}/{name}" for name in primary_aliases}
419
+ if response_model in fast_prefixed - primary_prefixed:
420
+ return f"fastest ({fast_id})"
421
+ if response_model in primary_prefixed - fast_prefixed:
422
+ return f"primary ({primary_id})"
423
+ if response_model in fast_aliases - primary_aliases:
424
+ return f"fastest ({fast_id})"
425
+ if response_model in primary_aliases - fast_aliases:
426
+ return f"primary ({primary_id})"
427
+ return None
428
+
429
+
430
+ def _row_matches_request(row: dict[str, object], correlation_ids: set[str]) -> bool:
431
+ if not correlation_ids:
432
+ return False
433
+ for key in ("request_id", "id"):
434
+ val = row.get(key)
435
+ if isinstance(val, str) and val.strip() in correlation_ids:
436
+ return True
437
+ ids = row.get("llm_request_ids")
438
+ return isinstance(ids, list) and any(
439
+ isinstance(item, str) and item.strip() in correlation_ids for item in ids
440
+ )
441
+
442
+
443
+ def _log_attribution(
444
+ addr: str,
445
+ before_logs: set[str],
446
+ started_at: dt.datetime,
447
+ correlation_ids: set[str],
448
+ completion_tokens: int | None,
449
+ primary_id: str,
450
+ fast_id: str,
451
+ llm_provider: str,
452
+ ) -> str | None:
453
+ for attempt in range(4):
454
+ if attempt:
455
+ time.sleep(0.1)
456
+ try:
457
+ rows = bifrost_checks.logs(addr, objects="chat_completion")
458
+ except (urllib.error.URLError, OSError, ValueError, http.client.HTTPException):
459
+ rows = []
460
+ candidates = [
461
+ row
462
+ for row in rows
463
+ if _candidate_log_row(row, before_logs, started_at, llm_provider)
464
+ and _row_matches_request(row, correlation_ids)
465
+ ]
466
+ candidates = _narrow_candidates(candidates, completion_tokens)
467
+ if not candidates:
468
+ continue
469
+ providers = {row.get("provider") for row in candidates}
470
+ if len(providers) > 1:
471
+ return None
472
+ provider = next(iter(providers))
473
+ if provider == gateway_bifrost.FAST_PROVIDER:
474
+ return f"fastest ({fast_id})"
475
+ return f"primary ({primary_id})"
476
+ return None
477
+
478
+
479
+ def _answered_by(
480
+ plan: StackPlan,
481
+ stats: StreamStats,
482
+ before_logs: set[str],
483
+ started_at: dt.datetime,
484
+ ) -> str | None:
485
+ fast = plan.get("llm_fast")
486
+ if fast is None:
487
+ return None
488
+ primary = plan["llm"]
489
+ gw = plan["harness"]["gateway"]
490
+ llm_provider = gw["llm_provider"]
491
+ matched = _model_attribution(stats.response_model, primary, fast, llm_provider)
492
+ if matched is not None:
493
+ return matched
494
+ if harness.gateway_kind(gw) == "bifrost":
495
+ correlation_ids = ({stats.request_id} if stats.request_id else set()) | stats.response_ids
496
+ logged = _log_attribution(
497
+ gw["addr"],
498
+ before_logs,
499
+ started_at,
500
+ correlation_ids,
501
+ stats.completion_tokens,
502
+ primary["model"]["id"],
503
+ fast["model"]["id"],
504
+ llm_provider,
505
+ )
506
+ if logged is not None:
507
+ return logged
508
+ return "routed gateway (target LLM not reported)"
509
+
510
+
511
+ def _http_error_message(code: int) -> str:
512
+ if code == 401:
513
+ return "The gateway rejected the stack's key; run stack doctor to repair access."
514
+ if code == 413:
515
+ return "The question or documents are too long; use shorter input and retry."
516
+ if code == 400:
517
+ return (
518
+ "The gateway or model rejected the request (HTTP 400); "
519
+ "shorten the input or run stack doctor."
520
+ )
521
+ if 500 <= code < 600:
522
+ return "The gateway or model service failed; run stack doctor and retry."
523
+ return "The gateway refused the request; run stack doctor."
524
+
525
+
314
526
  def cli(args: argparse.Namespace) -> int:
315
527
  try:
316
528
  if not args.question.strip() or len(args.question) > MAX_QUESTION_CHARS:
317
529
  raise StackError("Question must contain 1 to 8192 characters.")
318
- client, embedding = _installed(args.try_command)
530
+ client, embedding, plan = _installed(args.try_command)
319
531
  body = _body(args, client, embedding)
532
+ gw = plan["harness"]["gateway"]
533
+ routed_chat = args.try_command == "chat" and plan.get("llm_fast") is not None
534
+ before_logs = (
535
+ _chat_log_signatures(gw["addr"])
536
+ if routed_chat and harness.gateway_kind(gw) == "bifrost"
537
+ else set()
538
+ )
320
539
 
321
540
  def write(text: str) -> None:
322
541
  sys.stdout.write(text)
323
542
  sys.stdout.flush()
324
543
 
544
+ started_at = _utc_ms_now()
325
545
  stats = client.stream(body, write)
546
+ if routed_chat:
547
+ stats.answered_by = _answered_by(plan, stats, before_logs, started_at)
326
548
  write("\n")
327
549
  print("\n".join(stats.lines()), file=sys.stderr)
328
550
  return 0
329
- except (StackError, harness.HarnessError) as exc:
551
+ except (StackError, InputError, harness.HarnessError) as exc:
330
552
  print(f"stack try: {exc}", file=sys.stderr)
331
553
  return 2
332
554
  except DemoError as exc:
333
555
  print(f"\nstack try: {exc}", file=sys.stderr)
334
556
  return 1
335
557
  except urllib.error.HTTPError as exc:
336
- if exc.code == 401:
337
- message = "The gateway rejected the stack's key; run stack doctor to repair access."
338
- elif exc.code in (400, 413):
339
- message = "The question or documents are too long; use shorter input and retry."
340
- elif 500 <= exc.code < 600:
341
- message = "The gateway or model service failed; run stack doctor and retry."
342
- else:
343
- message = "The gateway refused the request; run stack doctor."
344
- print(f"\nstack try: {message}", file=sys.stderr)
558
+ print(f"\nstack try: {_http_error_message(exc.code)}", file=sys.stderr)
345
559
  return 1
346
560
  except BrokenPipeError:
347
561
  raise