repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
DeepTutor
deeptutor/services/session/turn_runtime.py
.py
""" Turn-level runtime manager for unified chat streaming. """ from __future__ import annotations import asyncio from collections.abc import AsyncIterator, Callable, Sequence import contextlib from contextvars import Token from dataclasses import dataclass, field import json import logging from typing import TYPE_CHE...
2,170
96,939
DeepTutor
deeptutor/services/session/pocketbase_store.py
.py
""" PocketBase-backed session store. Implements SessionStoreProtocol using PocketBase collections for all durable storage. The key performance design: - Most methods make direct PocketBase HTTP calls. These are called at most a handful of times per turn (create, get, update status, add message) and the ~5–10 ms ...
708
27,319
DeepTutor
deeptutor/services/session/base_session_manager.py
.py
#!/usr/bin/env python """ BaseSessionManager - Unified session management base class. This module provides a base class for managing persistent sessions across different agent modules (solve, chat, etc.). Features: - Consistent JSON storage format - Session CRUD operations - Message management within sessions - Autom...
257
7,861
DeepTutor
deeptutor/services/session/__init__.py
.py
""" Session Management Module ========================= Provides unified session management for all agent modules. Usage: from deeptutor.services.session import BaseSessionManager class MySessionManager(BaseSessionManager): def __init__(self): super().__init__("my_module") def _g...
60
1,581
DeepTutor
deeptutor/services/session/unified_session_manager.py
.py
""" Unified Session Manager ======================= Single session manager that handles all conversation types (chat, deep_solve, deep_question, etc.) via a ``mode`` field in the session data. """ from __future__ import annotations from typing import Any from .base_session_manager import BaseSessionManager class ...
77
2,434
DeepTutor
deeptutor/services/session/protocol.py
.py
""" Structural protocol for session stores. Both SQLiteSessionStore and PocketBaseSessionStore satisfy this protocol, allowing the rest of the codebase to be store-agnostic. """ from __future__ import annotations from typing import Any, Protocol, runtime_checkable @runtime_checkable class SessionStoreProtocol(Prot...
83
2,682
DeepTutor
deeptutor/services/session/source_inventory.py
.py
"""Branch-isolated, cumulative source inventory for the chat capability. The chat pipeline shows the LLM an "Attached Sources" manifest each turn so it can decide whether to call ``read_source(id)`` for full text. Historically this manifest only listed sources the user attached in the *current* turn — so the model for...
831
30,588
DeepTutor
deeptutor/services/session/artifact_attachments.py
.py
"""Generated-file attachments carried by a turn's stream events. The ``exec`` / ``code_execution`` / media tools write files into the turn workspace and publish them in two places: each ``tool_result`` event carries them in ``metadata.tool_metadata.artifacts`` the moment the tool finishes (the source that survives can...
147
6,139
DeepTutor
deeptutor/services/session/context_builder.py
.py
""" Build bounded conversation history for unified chat sessions. """ from __future__ import annotations from dataclasses import dataclass from typing import Any, Awaitable, Callable from deeptutor.agents.base_agent import BaseAgent from deeptutor.core.stream import StreamEvent, StreamEventType from deeptutor.core.t...
479
19,666
DeepTutor
deeptutor/services/session/sqlite_store.py
.py
""" SQLite-backed unified chat session store. """ from __future__ import annotations import asyncio from collections.abc import Iterator from contextlib import contextmanager from dataclasses import dataclass import json import os from pathlib import Path import re import sqlite3 import time from typing import Any im...
1,903
78,794
DeepTutor
deeptutor/services/cron/__init__.py
.py
"""Built-in cron — scheduled tasks for chat and partners.""" from deeptutor.services.cron.service import ( CronJob, CronOwner, CronSchedule, CronService, compute_next_run, get_cron_service, validate_schedule, ) __all__ = [ "CronJob", "CronOwner", "CronSchedule", "CronServic...
22
401
DeepTutor
deeptutor/services/cron/executor.py
.py
"""Run a due cron job for its owner (chat session or partner conversation).""" from __future__ import annotations import asyncio import logging import sys from typing import Any import uuid from deeptutor.services.cron.service import CronJob logger = logging.getLogger(__name__) async def execute_job(job: CronJob)...
199
7,161
DeepTutor
deeptutor/services/cron/service.py
.py
"""Built-in cron service — scheduled tasks for chat and partners. A trimmed-down take on nanobot's CronService (docs/ref/nanobot): same job semantics (``at`` / ``every`` / ``cron`` schedules, JSON persistence, run bookkeeping) without the multi-process file-lock/action-log machinery — DeepTutor runs one server process...
415
14,723
DeepTutor
deeptutor/services/mcp/secrets.py
.py
"""Credentials for a user's own MCP servers. A remote MCP server is reached with an API key that belongs to the person who configured it, and that key has to travel somewhere specific — an env var for one service, a request header for another, a URL query parameter or a command argument for a third. Two consequences s...
193
7,279
DeepTutor
deeptutor/services/mcp/pageindex_server.py
.py
"""Built-in PageIndex MCP server entry. PageIndex retrieval is agentic: the chat agent reads documents through the hosted PageIndex MCP server instead of a REST retrieval endpoint. When a PageIndex API key is configured, the connection manager overlays a reserved ``pageindex`` server entry onto the user-editable MCP c...
51
2,001
DeepTutor
deeptutor/services/mcp/session_state.py
.py
""" Per-session deferred-tool state. Records which deferred tools the model has loaded (via ``load_tools``) in a chat session, so subsequent turns include those schemas from the start instead of forcing a re-load. File-backed JSON inside the session workspace — multi-user-safe because the path service resolves per-use...
60
1,833
DeepTutor
deeptutor/services/mcp/network.py
.py
""" Network guards for remote MCP servers (SSRF protection). Two postures, because the two kinds of server carry different trust: **Deployment servers** (an administrator's ``mcp.json``) keep the original, permissive rules. A self-hosted deployment legitimately runs MCP servers on localhost or its own LAN, and the ad...
122
4,540
DeepTutor
deeptutor/services/mcp/manager.py
.py
""" MCP connection manager ====================== App-level singleton that owns the lifecycle of every configured MCP server connection and exposes their tools as chat :class:`BaseTool` adapters. Lifecycle model --------------- DeepTutor's chat runs as per-turn tasks inside one event loop, while MCP sessions must be...
1,023
43,743
DeepTutor
deeptutor/services/mcp/__init__.py
.py
"""MCP integration: deployment-global server registry + deferred tool adapters.""" from deeptutor.services.mcp.config import ( MCPConfig, MCPServerConfig, load_mcp_config, mcp_config_path, save_mcp_config, ) from deeptutor.services.mcp.manager import ( MCPConnectionManager, MCPToolAdapter, ...
33
812
DeepTutor
deeptutor/services/mcp/user_config.py
.py
"""A user's own MCP servers. The deployment's servers live in one admin-owned ``mcp.json`` (:mod:`deeptutor.services.mcp.config`). This module is the parallel store for servers an individual configures for themselves, and it differs in three ways that are all load-bearing: **Location.** ``data/system/user-mcp/<owner>...
234
8,426
DeepTutor
deeptutor/services/mcp/oauth.py
.py
"""OAuth 2.1 for MCP servers that require it. Most hosted MCP servers moved to OAuth: Notion, Linear, Sentry, Asana, monday, Canva and Prisma all answer an unauthenticated request with ``401``. A store that only knows how to put a static API key in a header cannot offer any of them, so this module adds the missing hal...
439
16,838
DeepTutor
deeptutor/services/mcp/config.py
.py
""" MCP configuration ================= Pydantic models + persistence for the deployment's MCP server registry. This file's config is deployment-global (``settings/mcp.json`` in the admin workspace): every account talks to the same set of connected servers, and only an administrator writes it. The servers an individu...
163
5,774
DeepTutor
deeptutor/services/mcp/catalog/models.py
.py
"""Curated MCP catalog: the shape of one installable entry. The catalog is a *template* store, not a second config store. An entry knows the connection an MCP service needs and, separately, which credentials the person installing it has to supply and **where each one has to travel** — an env var for one service, a req...
333
13,453
DeepTutor
deeptutor/services/mcp/catalog/__init__.py
.py
"""The curated MCP catalog: one-click installable MCP services. :mod:`models` is the entry shape and the template-to-config projection; :mod:`loader` reads the JSON that ships in ``vendor/`` and serves search, filtering and pagination over it. Everything is pure and offline — a caller turns an entry plus credential va...
45
1,133
DeepTutor
deeptutor/services/mcp/catalog/loader.py
.py
"""Load, search and paginate the vendored MCP catalog. The catalog ships as a JSON file inside this package and is parsed once into frozen dataclasses. **Nothing on the request path touches the network.** That is a deliberate rejection of the pattern this feature replaces, where opening the store did a blocking upstre...
250
8,473
DeepTutor
deeptutor/services/cli_apps/provider.py
.py
"""Installed CLI apps, presented to a chat turn as deferred tools. One tool per app, named ``cli_<app id>``. The tool takes an **argument vector** rather than a command line, so the model composes ``["scene", "list"]`` and never a string that something downstream has to parse. Progressive disclosure does the heavy li...
371
14,763
DeepTutor
deeptutor/services/cli_apps/catalog.py
.py
"""Read the vendored CLI app catalog, and search it. The snapshot ships in the package (``vendor/catalog.json``) rather than being fetched: a store that reaches out to a third-party registry at request time turns every page render into a dependency on somebody else's uptime, and makes "what can this deployment install...
210
6,735
DeepTutor
deeptutor/services/cli_apps/installer.py
.py
"""Install and remove CLI apps. Administrator only. This module is the one place in the feature that executes code **outside** the sandbox: ``pip install`` runs the package's own ``setup.py`` in the application container, as the application user. No amount of care makes that a self-service action, which is why install...
297
10,650
DeepTutor
deeptutor/services/cli_apps/state.py
.py
"""What is installed, and who may use it. Two independent pieces of state, kept apart because they answer different questions and are owned by different people: **Installed** (``data/cli-apps/state.json``) — deployment-wide, written only by an administrator's install. Installing runs somebody else's ``setup.py`` in t...
219
7,326
DeepTutor
deeptutor/services/cli_apps/models.py
.py
"""CLI app catalog: one installable command-line tool, and how to install it. The catalog is a snapshot of the two `CLI-Anything <https://github.com/HKUDS/CLI-Anything>`_ registries. Three rules shape this module, and each one exists because the snapshot is **third-party data**: **We never run the registry's ``instal...
314
11,739
DeepTutor
deeptutor/services/cli_apps/runner.py
.py
"""Execute one installed CLI app, through the sandbox. Arguments come from the model, so they are passed as an **argument vector** and never as a shell string: :meth:`ExecRequest.of_argv` derives the shell form for older runner images, and every backend that understands ``argv`` execs it directly. That is the whole re...
145
5,733
DeepTutor
deeptutor/services/cli_apps/__init__.py
.py
"""CLI apps: command-line tools an administrator installs and the chat agent calls. Layering, innermost first — each layer imports only from the ones above it: ``models`` the shape of a catalog entry, and the install-command parser ``catalog`` the vendored snapshot, searchable ``paths`` where installs live o...
53
1,591
DeepTutor
deeptutor/services/cli_apps/paths.py
.py
"""Where CLI apps live on disk, and why it is that particular place. Installed apps sit in ``data/cli-apps`` — a third location, deliberately neither of the two the rest of the data tree uses: * **Not under ``data/system``.** That subtree is never bind-mounted into the sandbox runner (it holds auth state and per-ow...
132
4,733
DeepTutor
deeptutor/services/videogen/__init__.py
.py
"""Video-generation service — text-to-video via the active model catalog. Public facade used by the chat tool, the API router and the config test runner. Config is resolved from ``services.videogen`` exactly like llm/embedding/tts, so video providers are configured through the same Settings catalog UI. Generation is ...
66
2,574
DeepTutor
deeptutor/services/videogen/config.py
.py
"""Resolved runtime configuration for video-generation providers. Unlike image generation, text-to-video has no synchronous OpenAI standard: the common shape is an async task (submit → poll → download). This dataclass carries the generation knobs plus the polling budget used by the async-task adapter. """ from __futu...
40
1,348
DeepTutor
deeptutor/services/videogen/base.py
.py
"""Base abstraction for video-generation adapters.""" from __future__ import annotations from abc import ABC, abstractmethod from collections.abc import Awaitable, Callable from deeptutor.services.videogen.config import VideogenConfig # Optional async progress callback invoked during long renders. Receives a short ...
43
1,358
DeepTutor
deeptutor/services/videogen/adapters/__init__.py
.py
"""Video-generation adapter registry. Adapters are stateless singletons keyed by the ``adapter`` field on the resolved config. The async-task adapter covers the submit → poll → download lifecycle shared by Volcengine Ark Seedance and similar providers; register bespoke providers by adding new keys here. """ from __fu...
28
977
DeepTutor
deeptutor/services/videogen/adapters/async_task.py
.py
"""Async task-based video-generation adapter. Text-to-video providers don't share a synchronous standard. The common shape — used by Volcengine Ark (Seedance) and most others — is a task lifecycle:: POST {base}/contents/generations/tasks -> {"id": ...} GET {base}/contents/generations/tasks/{id} -> {...
183
7,781
DeepTutor
deeptutor/services/memory/ids.py
.py
"""Stable, time-ordered identifiers for trace events and document entries. Format: 26-character Crockford-base32 (ULID-style). - Trace ids: ``<surface>:<ULID>`` — e.g. ``chat:01HZK4ABCDEFGHJKMNPQRSTVWX`` - Entry ids: ``m_<ULID>`` — used in MD footnote labels The ULID's leading 10 characters encode a millise...
81
2,670
DeepTutor
deeptutor/services/memory/trace.py
.py
"""L1 raw event trace: append-only JSONL files, one per surface per UTC day. Trace capture must never break the producing surface — every append is wrapped and failures are logged-and-swallowed. Writes are serialized per-surface with an asyncio lock so multiple turns in the same process don't interleave JSON lines. ""...
154
4,832
DeepTutor
deeptutor/services/memory/store.py
.py
"""High-level facade for the three-layer memory subsystem. All callers — API routers, LLM tools, surface event hooks — go through :class:`MemoryStore`. The store is stateless; per-user isolation is inherited from :func:`paths.memory_root` which resolves :class:`PathService` lazily via context variables. """ from __fu...
460
17,607
DeepTutor
deeptutor/services/memory/__init__.py
.py
"""Three-layer memory subsystem. - ``trace`` : L1 raw event capture (append-only JSONL per surface per day) - ``document``: L2/L3 markdown + footnote-citation parser/serializer (pure) - ``ops`` : add/edit/delete batch applier (pure) - ``paths`` : per-user path resolution - ``ids`` : ULID-style trace and en...
43
1,248
DeepTutor
deeptutor/services/memory/ops.py
.py
"""Atomic add/edit/delete operations on memory documents. A batch of ops is validated as a whole and applied only if all ops pass. Conflicting ops (e.g. ``delete`` and ``edit`` on the same id within one batch) reject the entire batch — the LLM doesn't get to self-contradict. Pure functions; no I/O, no LLM. """ from ...
150
5,237
DeepTutor
deeptutor/services/memory/settings.py
.py
"""User-tunable parameters for the memory consolidator. Single source of truth is ``data/user/settings/main.yaml`` under the ``memory:`` subtree. Defaults live here. The frontend ``/settings/memory`` page reads/writes the same subtree via the API. Decoupled from the algorithm code: every mode picks values up via :fun...
199
6,123
DeepTutor
deeptutor/services/memory/paths.py
.py
"""Path resolution for the three-layer memory subsystem. Layout under the per-user memory root:: trace/<surface>/<YYYY-MM-DD>.jsonl (L1, append-only) L2/<surface>.md (L2, per-surface summaries) L3/<recent|profile|scope|preferences>.md (L3, cross-surface) backup/<timestamp>/.....
104
2,970
DeepTutor
deeptutor/services/memory/document.py
.py
"""Markdown documents with footnote-style citations. Each L2/L3 file is a markdown document of the form:: # <Title> ## <section_a> - <text> [^1][^2] <!--m_xxx--> - <text> [^1] <!--m_yyy--> ## <section_b> - <text> [^3] <!--m_zzz--> --- [^1]: notebook:abc [^2]: chat:def [^3]:...
236
8,249
DeepTutor
deeptutor/services/memory/snapshot/diff.py
.py
"""Pure-function diff between two snapshot states. A ``state`` is ``{entity_id: fingerprint}``. ``label_map`` carries human-readable titles for the change-log so we don't have to re-read workspace state when rendering history. """ from __future__ import annotations from datetime import datetime, timezone from deept...
68
2,152
DeepTutor
deeptutor/services/memory/snapshot/store.py
.py
"""On-disk persistence for snapshot state + change log. Each surface gets its own ``<memory_dir>/snapshot/<surface>/`` directory holding: - ``state.json`` — current ``{entity_id: fingerprint}`` map plus a parallel ``labels`` map (so removals can show the old human-rea...
114
3,503
DeepTutor
deeptutor/services/memory/snapshot/__init__.py
.py
"""Workspace snapshot subsystem for L1 memory. Public API: - :func:`read_snapshot` — current entities for a surface (no I/O on ``state.json`` / ``changes.jsonl``). - :func:`refresh_snapshot` — re-read workspace, diff against last persisted state, append changes, persist new state. Returns the computed change li...
101
3,173
DeepTutor
deeptutor/services/memory/snapshot/adapters.py
.py
"""Workspace → ``Entity`` adapters. One pure read-only function per surface. Adapters never mutate workspace state. They read whatever lives under ``data/user/workspace/`` (or, for chat/quiz, the chat history SQLite DB; for kb-list, the kb config JSON; for the ``partner`` surface, the per-partner conversation JSONL un...
528
18,996
DeepTutor
deeptutor/services/memory/snapshot/entity.py
.py
"""Snapshot data types. An ``Entity`` is one unit of L1 content for a non-KB surface — e.g. one notebook record, one co-writer document, one book, one chat session. The snapshot is the *current* set of these on disk; the diff log records how that set has changed across refreshes. These types are intentionally pure da...
46
1,130
DeepTutor
deeptutor/services/memory/consolidator/parse.py
.py
"""Tolerant JSON parsers shared across the consolidator. Two shapes are supported: * :func:`parse_action` — one-action-per-turn envelope used by the agentic loop driver. Returns ``None`` on failure so the loop can surface a retry hint instead of crashing. * :func:`_parse_ops_response` — legacy ``{"ops": [...]}`` ...
136
4,545
DeepTutor
deeptutor/services/memory/consolidator/guards.py
.py
"""Op-emit guards: banned-phrase filter + budgets. Run at op-emit time (during the loop) so the model gets an observation back when an op is rejected and can rewrite. Today's pre-redesign code filtered banned phrases after the LLM call returned all ops at once, which meant rejection was a silent drop. """ from __futu...
105
2,889
DeepTutor
deeptutor/services/memory/consolidator/references.py
.py
"""Reference validation + raw-trace lookup used by update / audit. Two distinct concerns share this module because they both center on "the set of refs the LLM is allowed to cite": * **Update mode** — refs must point at entities that appear in the current chunk's source range. :func:`refs_in_chunk` returns the al...
389
13,406
DeepTutor
deeptutor/services/memory/consolidator/runs.py
.py
"""Persistent, cancellable consolidator runs. A "run" is one invocation of :func:`run_update` / :func:`run_audit` / :func:`run_dedup`. The run is owned by an asyncio task; events flow through a buffered ring so a disconnecting client can re-attach by posting ``since=<cursor>`` to the events endpoint and replay everyth...
424
13,621
DeepTutor
deeptutor/services/memory/consolidator/__init__.py
.py
"""Memory consolidator — chunk-based update / audit / dedup. Public surface (call these from the API router / store / tests): * :class:`ConsolidateResult`, :data:`OnEvent` — legacy types preserved for :mod:`deeptutor.services.memory.store`. * :func:`consolidate_l2`, :func:`consolidate_l3` — legacy shims that dele...
63
2,183
DeepTutor
deeptutor/services/memory/consolidator/chunker.py
.py
"""Character-based chunking with boundary expansion. The L2 / L3 update flow concatenates inputs into one string, then :func:`chunk_with_boundary` cuts it into ≤ budget pieces. Each piece's right edge is extended forward to the next paragraph or sentence boundary — content is **never truncated mid-statement**. Adjacen...
132
4,507
DeepTutor
deeptutor/services/memory/consolidator/line_doc.py
.py
"""Line-numbered view of a memory document + line-level edit ops. The audit / dedup modes ask the LLM to operate on a memory document the same way an IDE assistant operates on source code: it sees numbered lines and emits structured edits referencing those numbers. To keep the document's invariants intact, the LLM on...
483
17,051
DeepTutor
deeptutor/services/memory/consolidator/meta.py
.py
"""Per-doc consolidator metadata (``*.meta.json`` files). For each L2/L3 markdown doc we keep a sidecar JSON capturing the set of upstream ids "seen" at the last update. ``run_update`` uses set diff against the live state to compute "what's new since last update" — a purely id-based diff is robust against mtime / time...
195
5,331
DeepTutor
deeptutor/services/memory/consolidator/modes/audit.py
.py
"""Audit mode — line-level edits checked against raw evidence. Algorithm --------- 1. Render the target md as a line-numbered, footnote-stripped view (:func:`line_doc.render_view`). 2. Chunk the rendered view into ≤ budget pieces; each chunk is a contiguous slice of lines whose bullet entries get **annotated wit...
485
15,549
DeepTutor
deeptutor/services/memory/consolidator/modes/__init__.py
.py
"""Four user-visible consolidation modes. * :func:`run_update` — chunk-based incremental fact extraction. * :func:`run_audit` — chunk-based line-level edits against raw evidence. * :func:`run_dedup` — iterative line-level dedup over the full doc. * :func:`run_merge` — no-LLM footnote consolidation (collapse dup...
32
1,116
DeepTutor
deeptutor/services/memory/consolidator/modes/dedup.py
.py
"""Dedup mode — iterative line-level merge / delete over the full doc. Each iteration: 1. Render the full md as a line-numbered view (footnote-stripped). 2. One LLM call returns ``{"edits": [...]}`` (replace + delete only — the dedup prompt forbids inserts). 3. Apply in reverse line order. 4. If the LLM returned ze...
229
6,582
DeepTutor
deeptutor/services/memory/consolidator/modes/update.py
.py
"""Update mode — chunk-based incremental fact extraction. Algorithm --------- 1. Compute "new since last update" by id-set diff against ``*.meta.json``. 2. Concatenate the new inputs by time (oldest first). 3. ``chunk_with_boundary`` cuts the concat into ≤ budget pieces, never truncating mid-paragraph (or mid-sente...
707
22,709
DeepTutor
deeptutor/services/memory/consolidator/modes/_shims.py
.py
"""Legacy public-API shims for :mod:`deeptutor.services.memory.store`. The pre-redesign module exposed ``consolidate_l2`` and ``consolidate_l3`` returning a :class:`ConsolidateResult`. The store / API router still call these names. We keep them as thin wrappers around :func:`run_update` so the surface that the router ...
130
4,404
DeepTutor
deeptutor/services/memory/consolidator/modes/merge.py
.py
"""Merge mode — consolidate footnote references on a single doc. This mode is a *no-LLM* refactor pass. It loads the L2 or L3 document and rewrites it through :func:`serialize`, which: 1. Migrates legacy entry-keyed footnotes (``[^m_xxx]: r1, r2``) to the new ref-keyed layout (``[^1]: r1``, ``[^2]: r2``). 2. Colla...
228
7,748
DeepTutor
deeptutor/services/memory/consolidator/modes/_runtime.py
.py
"""Shared runtime helpers used by every mode. These keep the per-mode files focused on algorithm, not plumbing: * Prompt loading (en/zh, cached). * SSE event emission (``_emit``). * Document load + atomic write. * LLM call wrapper with retries + a one-line warning on failure. """ from __future__ import annotations ...
338
10,881
DeepTutor
deeptutor/services/subagent/types.py
.py
"""Value types for the subagent driver layer. These are the only shapes that cross the boundary between a backend (which knows how to drive one local agent CLI) and the rest of the app (the consult tool, the API, the tests). Keeping them dependency-free lets the backends stay small and the capability layer stay ignora...
107
3,255
DeepTutor
deeptutor/services/subagent/process.py
.py
"""Stream a child process's stdout/stderr line-by-line as it runs. The single low-level primitive the subagent backends share: spawn a command and yield every stdout and stderr line the moment it arrives — so a long, multi-step agent run surfaces live in the sidebar instead of all at once at the end — then guarantee t...
140
5,042
DeepTutor
deeptutor/services/subagent/gemini.py
.py
"""Gemini CLI backend — drive the local ``gemini`` CLI in headless print mode. Uses ``gemini -p <question> --output-format stream-json`` (stream-json exists since v0.11.0): a newline-delimited JSON event stream with a small, fixed event vocabulary — ``init`` (session id + model), ``message`` (assistant text arrives as...
302
11,104
DeepTutor
deeptutor/services/subagent/kimi.py
.py
"""Kimi CLI backend — drive the local ``kimi`` CLI in headless print mode. Uses ``kimi --print --output-format stream-json``: a JSONL stream of chat-shaped messages, one object per line, flushed live at step boundaries. Lines are discriminated by their ``role`` key — ``assistant`` (text / ``think`` parts / ``tool_call...
278
10,375
DeepTutor
deeptutor/services/subagent/models.py
.py
"""Backend option discovery — the synced model + reasoning-effort lists. The /settings "Partners & Agents" page lets the user pick the model and reasoning effort DeepTutor drives each backend with. Those lists change over time (vendors add/retire models), so this is read live, not hard-coded, and the page's "sync" but...
338
12,472
DeepTutor
deeptutor/services/subagent/claude_models.py
.py
"""Sync Claude Code's model catalog by scraping its ``/model`` TUI. Unlike Codex (which keeps a clean ``models_cache.json``), Claude Code exposes no machine-readable model list — ``/model`` lives only inside its interactive terminal UI. So on an explicit sync we drive ``claude`` in a pseudo-terminal, open ``/model``, ...
239
8,524
DeepTutor
deeptutor/services/subagent/claude_code.py
.py
"""Claude Code backend — drive the local ``claude`` CLI in headless print mode. Uses ``claude -p <question> --output-format stream-json --verbose``: a newline-delimited JSON event stream that mirrors exactly what an interactive session does — the system init, each assistant text block, every tool_use and its tool_resu...
374
14,507
DeepTutor
deeptutor/services/subagent/__init__.py
.py
"""Subagent driver layer — drive a user's local agent CLI as a subagent. DeepTutor runs on the same machine as the user's configured agent CLIs — Claude Code, Codex, Gemini CLI, Kimi CLI, opencode, MiMo Code — so the backend can drive them directly (spawned in print mode, or via a managed local server for the opencode...
55
1,749
DeepTutor
deeptutor/services/subagent/codex.py
.py
"""Codex backend — drive the local ``codex`` CLI non-interactively. Uses ``codex exec --json``: a JSONL event stream (``thread.started`` carries the session id; ``item.*`` events carry reasoning, command executions, file changes, MCP tool calls and the agent's messages; ``turn.completed`` / ``turn.failed`` close it ou...
330
13,536
DeepTutor
deeptutor/services/subagent/opencode_family.py
.py
"""opencode-family backends — opencode and its fork MiMo-Code, over serve+SSE. Both CLIs share one integration because MiMo-Code is a source-level fork of opencode: same server API, same bus events, same session model. Instead of the part-granular ``run --format json`` subprocess mode, we drive the CLI's local HTTP se...
519
18,898
DeepTutor
deeptutor/services/subagent/registry.py
.py
"""Backend registry — the single place that knows which subagents exist. Add a new subagent by writing a :class:`SubagentBackend` and listing it here; the capability, API and UI all discover it through these helpers. Local-CLI backends (Claude Code, Codex, Gemini CLI, Kimi CLI, opencode, MiMo Code) and the in-process ...
80
2,711
DeepTutor
deeptutor/services/subagent/sessions.py
.py
"""Persistent subagent session ids — continuity across DeepTutor turns. The backend session/thread id from one consult is remembered (keyed by the chat session + the connection) so the NEXT turn resumes the SAME local agent session: the agent keeps the full context of everything DeepTutor — and the user, from the side...
84
2,622
DeepTutor
deeptutor/services/subagent/images.py
.py
"""Materialize image attachments to files so a subagent CLI can ingest them. When ``forward_images`` is on for a backend, the consult tool writes the turn's image attachments to a temp directory and hands the backend their paths — Codex attaches them with ``-i``, Claude Code is pointed at them for its Read tool. The b...
102
3,452
DeepTutor
deeptutor/services/subagent/partner.py
.py
"""Partner backend — consult one of the user's own partners as a subagent. Unlike the local-CLI backends (Claude Code / Codex) this drives no subprocess: it puts the question to a running partner through the partner manager's web entry point, exactly as if the user opened a new session on the partner page. The partner...
250
10,362
DeepTutor
deeptutor/services/subagent/config.py
.py
"""Subagent settings — the consult budget and per-backend permission knobs. Stored as ``data/user/settings/subagent.json`` (same convention as the other runtime settings files). Everything has a safe default so the feature works the moment a CLI is detected, with no configuration step required. * ``consult_budget`` —...
190
7,429
DeepTutor
deeptutor/services/subagent/base.py
.py
"""The backend contract: drive one local agent CLI as a subagent. A backend knows two things about its CLI: how to tell whether it's installed and usable on this machine (:meth:`detect`), and how to put one question to it and stream back every native event (:meth:`consult`). Everything CLI-specific — flags, the JSON e...
65
2,618
DeepTutor
deeptutor/services/subagent/opencode_server.py
.py
"""Managed ``opencode serve`` instances — one live server per (CLI, workdir). The opencode family (opencode and its fork MiMo-Code) exposes its best streaming through a local HTTP server: ``<cli> serve`` + an SSE ``/event`` firehose with true token-level ``message.part.delta`` events — richer than the part-granular ``...
202
6,495
DeepTutor
deeptutor/services/notebook/__init__.py
.py
"""Shared notebook service used by CLI, Web, and runtime.""" from .service import ( Notebook, NotebookManager, NotebookRecord, RecordType, get_notebook_manager, notebook_manager, ) __all__ = [ "Notebook", "NotebookManager", "NotebookRecord", "RecordType", "get_notebook_mana...
20
352
DeepTutor
deeptutor/services/notebook/service.py
.py
""" Shared notebook manager. This module keeps the notebook storage format unchanged so Web and CLI can operate on the same files under ``data/user``. """ from __future__ import annotations from enum import Enum import json from pathlib import Path import time import uuid from pydantic import BaseModel from deeptu...
447
14,295
DeepTutor
deeptutor/services/setup/__init__.py
.py
""" Setup Service ============= System setup and initialization for DeepTutor. Port configuration is done via data/user/settings/system.json. Usage: from deeptutor.services.setup import init_user_directories, get_backend_port # Initialize user directories init_user_directories() # Get server ports ...
33
622
DeepTutor
deeptutor/services/setup/init.py
.py
#!/usr/bin/env python """ System Setup and Initialization Combines user directory initialization and port configuration management. """ import json import logging from pathlib import Path import yaml from deeptutor.services.path_service import get_path_service # Initialize logger for setup operations _setup_logger ...
291
9,306
DeepTutor
deeptutor/services/codex_auth/catalog.py
.py
"""Account-scoped live model catalog for Codex OAuth.""" from __future__ import annotations from collections.abc import Callable, Mapping from dataclasses import replace import hashlib import time from typing import Any import httpx from .constants import ( CODEX_CLIENT_VERSION, CODEX_FRESH_CACHE_SECONDS, ...
267
9,040
DeepTutor
deeptutor/services/codex_auth/contracts.py
.py
"""Data contracts shared by the independent Codex OAuth components.""" from __future__ import annotations import base64 from collections.abc import Mapping from dataclasses import dataclass, field import json from typing import Any, Literal CatalogSource = Literal["live", "fresh-cache", "revalidated-cache", "stale-c...
264
9,550
DeepTutor
deeptutor/services/codex_auth/storage.py
.py
"""Private, generation-safe storage for DeepTutor Codex credentials.""" from __future__ import annotations from collections.abc import Iterator, Mapping from contextlib import contextmanager from dataclasses import replace import json import os from pathlib import Path import stat import sys import tempfile import th...
262
9,326
DeepTutor
deeptutor/services/codex_auth/__init__.py
.py
"""Independent OpenAI Codex OAuth support for DeepTutor.""" from .contracts import ( CatalogSnapshot, CodexAuthError, CodexCredentials, CodexModel, CodexToken, TokenClaims, decode_codex_jwt, ) from .service import ( CodexOAuthService, get_codex_oauth_service, reconcile_codex_cat...
30
592
DeepTutor
deeptutor/services/codex_auth/constants.py
.py
"""Audited OpenAI Codex compatibility constants.""" CODEX_UPSTREAM_COMMIT = "81da9deb065d7adb283816b19b40f89bcc484276" CODEX_CLIENT_VERSION = "0.145.0" CODEX_OAUTH_ISSUER = "https://auth.openai.com" CODEX_OAUTH_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann" CODEX_OAUTH_SCOPE = "openid profile email offline_access api.conn...
24
1,114
DeepTutor
deeptutor/services/codex_auth/oauth.py
.py
"""PKCE, loopback callback, and HTTP operations for Codex OAuth.""" from __future__ import annotations import asyncio import base64 from collections.abc import Iterable from dataclasses import dataclass import hashlib import secrets from typing import Any from urllib.parse import parse_qs, urlencode, urlsplit import...
352
12,340
DeepTutor
deeptutor/services/codex_auth/service.py
.py
"""Codex OAuth orchestration and managed model-catalog integration.""" from __future__ import annotations import asyncio from collections.abc import AsyncIterator, Awaitable, Callable, Mapping from contextlib import asynccontextmanager from copy import deepcopy from dataclasses import dataclass import hashlib import ...
1,194
47,019
DeepTutor
deeptutor/services/embedding/__init__.py
.py
"""Unified embedding client and adapters for all DeepTutor modules. Supported bindings are resolved by ``services.config.provider_runtime`` and currently include openai, custom, azure_openai, cohere, jina, ollama, vllm, siliconflow, aliyun, openrouter, plus legacy custom_openai_sdk configs. """ from .adapters import ...
42
1,294
DeepTutor
deeptutor/services/embedding/client.py
.py
"""Unified embedding client backed by normalized provider runtime config.""" from __future__ import annotations import logging from typing import Any, Dict, List, Optional from deeptutor.services.config.embedding_endpoint import ( redact_embedding_endpoint_for_display, ) from deeptutor.services.config.provider_r...
270
10,629
DeepTutor
deeptutor/services/embedding/config.py
.py
"""Normalized embedding configuration resolved from the model catalog.""" from __future__ import annotations from dataclasses import dataclass from deeptutor.services.config import resolve_embedding_runtime_config @dataclass class EmbeddingConfig: """Embedding runtime configuration.""" model: str api_...
63
2,029
DeepTutor
deeptutor/services/embedding/validation.py
.py
"""Validation helpers for embedding vectors.""" from __future__ import annotations from collections.abc import Sequence import math from numbers import Real from typing import Any def _context( *, binding: str | None, model: str | None, batch_index: int | None, total_batches: int | None, ) -> st...
129
4,465
DeepTutor
deeptutor/services/embedding/adapters/gemini.py
.py
"""Gemini embeddings via the native batch API with legacy compatibility.""" from __future__ import annotations import asyncio from dataclasses import replace import json import logging import math from typing import Any, Dict from urllib.parse import parse_qsl, unquote, urlparse import httpx from deeptutor.services...
368
14,759
DeepTutor
deeptutor/services/embedding/adapters/__init__.py
.py
"""Embedding adapter implementations and backend registry.""" from .base import ( BaseEmbeddingAdapter, EmbeddingProviderError, EmbeddingRequest, EmbeddingResponse, ) from .cohere import CohereEmbeddingAdapter from .dashscope_native import DashScopeMultiModalEmbeddingAdapter from .gemini import GeminiE...
41
1,284