Serialize SDK responses using API field aliases and omit unset optional
fields before persisting native replay state. Repair legacy async_ fields
on a copy at replay time without altering stored history or argument JSON.
Cover streaming and non-streaming SDK continuations, alias precedence,
and legacy SQLite replay.
Co-Authored-By: GPT-6.1 Sol High
* fix(i18n): accept Korean as a backend interface language
The web picker offers Korean (added in #2359), but the backend UiLanguage
contract, its normalizers and the settings spec never learned "ko". Choosing
Korean and applying settings therefore fails with HTTP 422 on
PUT /api/settings/ui, and the saved language falls back to English on the
next load.
Register "ko" in the same seams Japanese used in #2213: UiLanguage and
_normalize_language() in interface_settings.py, the launch-settings
normalizer, and _LANGUAGE_CHOICES in settings_spec.py, then regenerate the
frontend API contracts. Add Korean to the existing router and launch-settings
tests, and add a registry test that fails whenever a web APP_LANGUAGES code
is missing from the backend contract.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* style: apply ruff format
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* fix(llm): force temperature 1.0 for gpt-6 and treat reasoning_effort+tools rejection as tool-schema unsupported
* fix(llm): drop reasoning_effort instead of tools when combined request is rejected
---------
Co-authored-by: Shaikh Fardin <152140625+Fardin7798@users.noreply.github.com>
Co-authored-by: OrdoAbChao7 <2369980241@qq.com>
The sanitizer deleted every quote character to unwrap a quoted reply,
so "What's ...?" was shown as "Whats ...?". Only unwrap a matching
outer pair, as the chat and reading hints already do.
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Closes#2909.
Omit the fewest eligible historical tool-argument payloads so oversized completed exchanges remain replayable, without touching signed/native provider rounds or durable history.
IndexingRun.document() re-reads the journal and atomically rewrites the
whole .indexing-run.json on every call. The LlamaIndex loader marks each
accepted source "embedding" in a synchronous loop on the event loop, and
publication marks every loaded Document (one per page) "completed" the
same way, so recording n statuses costs O(n^2) bytes of I/O with no
await in between. On a 4,320-document reindex this held the loop for
over 100 s, /health/ready stopped answering, and the desktop supervisor
killed the core.
Add IndexingRun.documents(sources, status, **details), which applies one
status to many sources under a single ownership check and a single
journal write, and use it from the loader, the LlamaIndex publication
step and the RAG service's indexed-file callback. document() now
delegates to it, so single updates behave as before.
Fixes#3046
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Omit optional status on message/reasoning/function_call items when building
Responses requests for the custom binding, so gateways that reject
unknown_parameter inside an HTTP 200 stream no longer fail durable turns.
Keep the bounded HTTP-error retry for other cases.
Co-authored-by: zhouyao01 <zhouyao01@mucang.cn>
Mistral reasoning models return `content` as a list of typed blocks
(thinking + text). `_parse_chunks` joined those lists directly and raised
TypeError, and `_parse` / the streaming content callback passed the raw
list through. Normalise with the existing `_extract_text_content` helper.
Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
* feat(providers): add LiteLLM as a local OpenAI-compatible provider
* test(web): keep LiteLLM on the generic provider-branding fallback
---------
Co-authored-by: ZQR1101 <278034003+ZQR1101@users.noreply.github.com>
* fix(imagegen): prefill image models the providers still serve
The OpenAI image provider prefilled gpt-image-1, which OpenAI retired on 2026-10-23, and OpenRouter prefilled google/gemini-2.5-flash-image-preview, which OpenRouter no longer lists, so a user who kept the prefill got a failing first request. They now prefill gpt-image-2 and google/gemini-3.1-flash-image.
* fix(imagegen): prefill gpt-image-2.6-flare instead of gpt-image-2
OpenAI shuts gpt-image-2 down on 2027-02-10 and names gpt-image-2.6-flare or -sunburst as the replacement; its image guide recommends the 2.6 models for new integrations. Flare is the general, fast-iteration model and uses the same Images API, so the OpenAI prefill moves to it now instead of to another retiring model.
AnthropicProvider and the agentic client's Anthropic adapter fell back to claude-sonnet-4-20250514, which Anthropic retired on 2026-06-15, so an Anthropic binding with no model failed with not_found_error. Both now use one DEFAULT_ANTHROPIC_MODEL constant, claude-sonnet-5-5.
The maths single-source scan reads only prompt packs, capability modules,
capability Markdown prompts (such as notes/prompts/*/system.md) and the
fragment files instead of every file in the package. The zh/en playbook
comparison already checks line by line in
tests/capabilities/test_mastery_prompt_slimming.py.
Refs #2975
PromptManager.clear_cache() and reload_prompts() dropped cached packs but
the fragment lru_cache kept serving the old fragments/*.yaml, so a
reloaded pack still carried the previous rule text. Both now clear it.
Fragments are checked for "{" and "}" when loaded (the expanded text can
pass through str.format()), with a test over every fragment in en and
zh. The notes capability gets a test that its en and zh instructions
include the shared maths rule.
Refs #2975
PromptManager expanded shared fragments inside the try block that guards
reading a prompt file, so an unknown fragment name was caught as a load
failure and the manager quietly served another language's pack (or {}).
A marker that does not match the lowercase name pattern, such as
{{shared:Math}}, was left in the prompt as literal text. Expansion now
runs after the read; unknown names raise KeyError and leftover markers
raise ValueError. A repo scan checks that every marker in a prompt pack
names a fragment present in both en and zh.
Refs #2975
Chat, mastery, question FINISH and notes each carried their own copy of
the dollar-delimiter rule. They now reference {{shared:math_latex}}
(deeptutor/services/prompt/fragments), expanded by PromptManager at load
time; the notes capability expands the marker in its system.md, and
code-built prompts use shared_fragment(). The English notes prompt gains
the rule (and the mermaid line) its Chinese twin already had. The chat
loop no longer repeats the 'concise Markdown' line that runtime_policy
states.
Refs #2975
* fix(mcp): let operators declare Fake-IP ranges for self-service servers
A local proxy in Fake-IP mode (Loon, Clash, Surge) answers DNS for public
hostnames with synthetic private addresses, e.g. fd27:712::/32 from Loon,
and routes the connection by hostname. Strict validation then rejects
public MCP Store entries such as GitMCP as private-network targets.
Add DEEPTUTOR_MCP_FAKE_IP_RANGES (comma separated CIDRs, opt-in, read from
the process environment). In strict mode an address a hostname resolves to
inside a declared range is no longer rejected as private. IP-literal URLs,
loopback and the link-local/metadata ranges stay blocked regardless, and
any other private answer for the same host still fails validation.
Closes#2789
Assisted-by: Claude <noreply@anthropic.com>
* fix(mcp): warn on Fake-IP opt-in and document single-user SSRF trade-offs
Address review feedback from JinhangHE126 on #2857:
Document clearly that DEEPTUTOR_MCP_FAKE_IP_RANGES relaxes hostname-based SSRF protection for hostnames resolving into declared ranges (as the proxy resolves targets and connects).
Emit a startup security warning when DEEPTUTOR_MCP_FAKE_IP_RANGES is set, noting that the setting is intended strictly for single-user/desktop installations.
Assisted-by: Gemini (Google Vertex AI)
OpenAICodexProvider._request_codex called consume_sse without an
on_provider_event hook and built LLMResponse without usage, so Codex turns
were counted as 0 tokens/cost. Collect the terminal usage event and attach it
to the response, as the openai_compat Responses path already does.
Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
The composer-hint sanitizers used lstrip("-•*# ") to drop list markers,
which also ate the sign of "-3 squared...?", the star of "*args" and
the hash of "#include". Strip a marker only when whitespace follows it.
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
A KB-list / get_info sweep probes every version-N directory of every KB,
because the UI renders readiness per version. The docstore count cache is
keyed per version directory, so its capacity has to cover the whole
catalogue, not a single KB's worth.
At the old fixed 128 slots a real installation (13 KBs, 310 version
directories -- #2772) exceeded the working set on every sweep: each probe
evicted exactly what it had just read, the hit rate stayed at a permanent
0%, and every UI navigation re-parsed every multi-MB docstore.json. On a
memory-constrained host that showed up as a pinned event loop and hundreds
of GB of disk reads.
Raise the capacity to 4096. Each entry is a path plus an int, so this costs
about a megabyte even well above the working set.
Reproduced against v1.7.3 with a fixture matching the report (13 KBs, 310
versions, 52 MiB of docstore.json), replaying inspect_kb_versions() per KB:
before: 310 / 310 / 310 / 310 / 310 docstore parses per sweep, 0.0% hit rate
after: 310 / 0 / 0 / 0 / 0 docstore parses per sweep, 100% warm
A rewritten docstore still invalidates correctly (doc_count 400 -> 1), and
unchanged versions stay cached. The new regression test builds 2 KBs x 100
versions, which is above the old cap, and fails on the unfixed code
(400 parses instead of 200).
Closes#2772
* feat(rag): support local rerankers for LightRAG queries
Allow administrators to select a cross-encoder alongside the native LightRAG role models. Run scoring in a reusable worker and partition cached answers by reranker so model changes take effect on existing indexes.
Refs #2701
* fix(api): refresh the router index for LightRAG settings
* fix(rag): run LightRAG reranking in the shared reranker worker
anyio's process pool re-runs the server's __main__ file by path. When the
backend runs as `python -m deeptutor_cli.main serve` (the desktop app),
that file's relative imports fail, so every rerank call failed with
'Error during worker process initialization' and LightRAG silently kept
the original chunk order. Reuse the python -m reranker worker that the
LlamaIndex pipeline already uses.
---------
Co-authored-by: lipeih <lipeihan@eazytec.com>
Co-authored-by: zszz3 <zszz3@users.noreply.github.com>
* fix(mastery): grade within the objective's covered and own scope
- Reuse the preserved objective-scoped packet for an objective request
after a focus preparation replaced the live slot, and do not rebuild
an incomplete objective packet whose fingerprints are unchanged (#2363).
- mastery_assess grades a concept/design explanation against the covered
facets of an incomplete objective packet, records that scope, and
returns a structured coverage_gap result instead of a bare refusal.
- Tell the learner when an answer was not recorded or was graded only
against the covered part.
- Give the judge sibling objectives as out of scope and return the
single missing element with a next_step to ask for exactly it (#2364).
* test(mastery): cover the focus-only assessment deadlock from #2905
A complete focus-scoped packet with no assessment slot gets a structured
coverage_gap on every repeated mastery_assess, with no judge call and no
recorded evidence. One objective preparation then grades the retained
explanation together with the next reply.
Signed-off-by: Benjamin Schwing <63053132+BenjiAvH@users.noreply.github.com>
* fix(mastery): make the missing-element step the assess instruction
Since dev added a generic instruction to every final mastery_assess
payload, a non-passing verdict carried two competing moves: next_step
asked for exactly the named missing element (#2364) and instruction
asked the learner to explain the objective again. While the gate is not
cleared, the targeted step is now also the instruction, and it says to
record the reply with mastery_assess.
Signed-off-by: Benjamin Schwing <63053132+BenjiAvH@users.noreply.github.com>
* fix(mastery): say when an unclear explanation is kept for grading
A non-final verdict in a session keeps the explanation and grades it
together with the follow-up, so the generic "not recorded, progress
unchanged" notice misled the learner into repeating the whole answer.
Add an assessment_needs_clarification notice (en/zh) for that case; an
explanation outside a session keeps the not_recorded notice.
Signed-off-by: Benjamin Schwing <63053132+BenjiAvH@users.noreply.github.com>
* fix(mastery): preserve the missing assessment element on replay
---------
Signed-off-by: Benjamin Schwing <63053132+BenjiAvH@users.noreply.github.com>
Co-authored-by: Qiuner <wdst3635@163.com>
* test(parsing): stop racing interpreter startup in the MinerU lifecycle checks
The Windows `import-check` job flakes on `dev`. It failed at 2026-11-30 03:12
and 03:32 on `79a66cb3` and `6b00f010`, passed on the same step 90 minutes
later in another run, and passed on `218dbe31` the evening before. Nothing
between those runs touched `.github/`, `tests/services/parsing/`,
`tests/runtime/` or the MinerU engine, so the workflow and the code under test
were identical in the green and red runs.
Reproduced, and the cause is a timing premise in the tests, not the runner.
The race
--------
`test_deadline_and_cancellation_settle_the_owned_tree[True]` sets
`timeout=0.8` and only cancels once the fixture child has spawned a grandchild
and written `child.pid`:
def check():
if cancelled and list(...glob(".../child.pid")):
raise IndexingCancelled(...)
`local.py` starts its clock before `cli_process()`, which on Windows creates a
Job Object, spawns a suspended interpreter, resumes it and queries its threads.
That work plus two more interpreter startups has to fit inside the same 0.8s.
When it does not, the deadline wins before the marker exists and the assertion
reports `TIMEOUT is not CANCELLED`.
Measured on an idle machine the marker lands in 0.067-0.085s, so the margin
looked comfortable. Delaying only the child's first write, with no CPU
contention at all:
startup delay | result | expected | verdict
0.0s | cancelled | cancelled | pass
0.5s | cancelled | cancelled | pass
0.7s | timeout | cancelled | FAIL
0.9s | timeout | cancelled | FAIL
1.2s | timeout | cancelled | FAIL
CPU contention alone reproduced the same signature
`assert <LocalParseReason.TIMEOUT> is <LocalParseReason.CANCELLED>` at line 138,
plus `assert 2.087 < 2` and `assert 3.757 < 1.5` on neighbouring cases.
The production ordering is correct and is left alone: `run.check()` is
evaluated before the deadline comparison, so an available cancellation always
wins. What the tests must not do is depend on how fast the runner started a
Python interpreter.
What changed
------------
- `_await_marker()` waits for a fixture marker with a real timeout and a
message that distinguishes "the CLI never started" from "the runner was
slow". Bare `(path,) = glob(...)` unpacking turned both into
`ValueError: not enough values to unpack (expected 1, got 0)`, which is what
made these CI failures unreadable.
- The cancellation case waits for the recorded child before raising, so the
interruption is decided by policy rather than by interpreter startup. A 3s
startup delay now passes where 0.7s used to fail.
- Wall-clock bounds that were only guarding "did not wait for the descendant"
were widened off the interpreter-startup budget (`elapsed < 2` -> `< 15`,
`elapsed < 1.5` -> `< 10`, `elapsed < 2.5` -> `< 15`). The idle-threshold and
deadline assertions that carry the actual meaning are unchanged.
- `_await_settled()` treats `psutil.AccessDenied` as "not settled yet" instead
of raising mid-test.
- The decoy process in `test_parent_exit_does_not_wait_for_descendant_stdout`
lives 120s instead of 10s, so a slow run cannot make it die of old age and be
reported as "cleanup touched an unrelated process".
- `test_detached_venv_launcher_has_no_console` asserts the marker exists before
reading it, instead of raising `FileNotFoundError` after its 15s wait.
Observability
-------------
The Windows step now runs with `-rA --durations=15`. Without them the job
reported only "Process completed with exit code 1" with no test name, which is
why these failures needed a local reproduction to attribute.
Verification
------------
- `pytest -q -rA --durations=15 tests/services/parsing/test_mineru_process_lifecycle.py tests/runtime/test_launcher.py::test_detached_venv_launcher_has_no_console`
-> 7 passed, 10 skipped (the skips are POSIX/Darwin-only cases).
- Deliberate-startup-delay harness: 0.0/0.5/0.9/1.5/3.0s all report
`cancelled` after the change; 0.7s+ reported `timeout` before it.
- `ruff check` and `ruff format --check` clean on both files; workflow YAML
parses.
No production code is changed.
* test(parsing): synchronise the deadline fixtures with grandchild startup
Addresses review on #3089. Two real defects:
1. The deadline case of test_deadline_and_cancellation_settle_the_owned_tree
still raced. Only the cancellation branch waited for `child.pid`; the
deadline branch killed the fixture at 0.8s and then read a marker that was
never written, so a 1.3s startup delay produced `TIMEOUT` and then a failed
marker read. Both branches now synchronise through `check()`: it waits for
the recorded grandchild and only then either raises (cancellation) or returns
and lets the deadline comparison run. The timeout assertion is preserved.
test_explicit_client_timeout_also_bounds_parent_runtime had the same shape —
it read `deadline.txt` after a 1.2s kill. The record is written before the
child parks, so it exists whenever the child started at all, and the read now
reports "CLI did not start" instead of an unpacking error.
2. test_parent_exit_does_not_wait_for_descendant_stdout had lost its teeth: the
new 10s bound exceeded the grandchild's 2s sleep, so an implementation that
waited for inherited stdout could finish inside the bound and pass. The
grandchild now lives 60s and the bound is 20s, derived from the fixture, so
waiting for it fails the test again.
Verified with a 1.3s pre-startup delay (the reviewer's repro): both lifecycle
cases report the expected reason and the tree is settled. 0.0/1.3/2.0/3.0s all
pass. `7 passed, 10 skipped`; ruff clean.
* test: wait for the MinerU deadline record before enforcing the timeout
---------
Co-authored-by: Qiuner <wdst3635@163.com>
* fix(rag): keep figure captions out of the chunk metadata budget
Figure documents carried the caption, asset ids, bbox, source locator and
absolute path in metadata that LlamaIndex counts against every chunk. A long
caption (common for CJK textbook figures) pushed the metadata past the
default 512-token chunk size, so SentenceSplitter raised "Metadata length
(...) is longer than chunk size (512)" and the whole indexing run failed.
Keep those keys on the node for citations and pixel delivery, but exclude
them from the embed and LLM metadata text. The caption is already part of
the document text, so retrieval content is unchanged.
Closes#2865
* test(rag): split sentences without NLTK in the caption budget test
The new regression test ran SentenceSplitter with its default punkt
tokenizer, which loads NLTK data. CI runners refuse that data, so the
test failed with LookupError on all Python versions. Pass a regex
sentence splitter instead. The test still fails without the loader fix.
Long mastery sessions froze the event loop: every existence-only probe
(history_groups, context-builder guards) ran normalize_model_turn, which
deep-copies the whole request record via a JSON round-trip. A 121-message
session re-serialized megabytes per probe, holding the GIL long enough for
health checks to time out and the worker to be declared lost.
Extract the structural acceptance checks into _is_complete_model_turn and
add has_model_turn for existence-only sites. normalize_model_turn delegates
to the same predicate, then cleans and copies as before, so replay keeps its
full isolation. Stored records are normalize's own JSON-safe outputs, so the
predicate accepts exactly what normalize accepts on stored rows; a parity
corpus pins the shared rejections.
Fixes#2788
Co-authored-by: ZQR1101 <278034003+ZQR1101@users.noreply.github.com>
* fix(llm): close an evicted pooled provider on the loop that owns it
The runtime provider pool is keyed per event loop and shared by the server
loop and synchronous callers that run asyncio.run() in a worker thread, such
as the exam question extractor. Two cross-loop problems followed:
- When a worker loop's lookup evicted a server-loop client, the client's
aclose() was scheduled on the worker loop. It ran on the wrong thread, or
never ran when asyncio.run() cancelled it on exit. For Claude Code this
tears down the server loop's persistent CLI sessions from a foreign thread.
- Every finished worker loop left its entry behind. With a pool of two,
that stale entry could push the server loop's live client out, discarding
warm CLI sessions.
Each entry now records its loop. Evictions close on that loop: directly
when it is the running loop, otherwise through run_coroutine_threadsafe.
Entries whose loop is closed are dropped before a new client is added.
Signed-off-by: Benjamin Schwing <63053132+BenjiAvH@users.noreply.github.com>
* fix(llm): close every retired pooled provider on its own loop
close_runtime_provider_pool() awaited aclose() of every pooled client on
the caller's loop, and reset_runtime_provider_pool() scheduled them on the
caller's loop or ran each on a fresh asyncio.run() loop. A client built on
another loop, such as a long-lived worker loop, was therefore closed on a
loop that does not own its sockets or tasks.
The bulk paths now keep each retired entry's loop. close awaits only the
clients owned by the current loop and hands the rest to their owner loop;
reset routes every client through the same owner-loop close. The final
release of a leased client also uses the entry's recorded loop.
Signed-off-by: Benjamin Schwing <63053132+BenjiAvH@users.noreply.github.com>
* fix(llm): create a cross-loop close coroutine on the owner loop
run_coroutine_threadsafe() builds the close coroutine on the calling
thread. When the owner loop is stopped but not yet closed and never runs
again, that coroutine is dropped unawaited and Python warns "coroutine was
never awaited". Schedule a callback instead that creates the close task on
the owner loop, so a loop that never runs again leaves nothing behind. A
closed loop rejects the callback, which also replaces the separate
is_closed() check.
Signed-off-by: Benjamin Schwing <63053132+BenjiAvH@users.noreply.github.com>
---------
Signed-off-by: Benjamin Schwing <63053132+BenjiAvH@users.noreply.github.com>
EngineDetail renders the readiness panel for every engine, and its check button calls /api/knowledge-bases/rag-pipelines/{provider}/preflight, which runs engine_preflight() -> _PREFLIGHTS[normalize_provider_name(provider)]().
weknora and kiwix are in KNOWN_PROVIDERS but were never registered in _PREFLIGHTS, so the lookup raised KeyError and the route answered 500 for those engine pages.
One shared _connected_preflight now reports them ready: each knowledge base supplies its own server URL and credentials, validated by the connect probe, so nothing is configured account-wide. This matches doctor.py, which already skips these providers in its preflight loop.
The new test walks KNOWN_PROVIDERS and asserts every entry returns a report, so a future provider constant cannot silently miss the registry again.
Co-authored-by: enlightenmengt2 <227120787+enlightenmengt2@users.noreply.github.com>
* fix(rag): avoid NLTK regex CPU timeout during splitting and clean failed version dirs
* fix(rag): construct PunktSentenceTokenizer directly without globals_helper stopwords