Compare commits
334 Commits
f7aa2de410
..
dev
| Author | SHA1 | Date | |
|---|---|---|---|
| 160267417e | |||
| ed18192a8e | |||
| 076e8c93c9 | |||
| a226c94df7 | |||
| 057ec0552c | |||
| cdae9879f2 | |||
| 39a802bea2 | |||
| 1cc8a373b0 | |||
| a52ac6822b | |||
| 7475779b7c | |||
| e7ffc69729 | |||
| 396e26b4bf | |||
| 0bfc7750a2 | |||
| 790ef81b06 | |||
| 804691501f | |||
| 8e6a2e89f8 | |||
| dbcc7874bf | |||
| 16e660ad09 | |||
| b51d83b16d | |||
| f70db19cc6 | |||
| 56ba144875 | |||
| 97a7f59fe7 | |||
| 24ace44888 | |||
| 93569b141b | |||
| 9a00401507 | |||
| 76562ae31d | |||
| 497f455da6 | |||
| dd20c2bc75 | |||
| a36b423a4e | |||
| 4e477741e7 | |||
| a2261c38c1 | |||
| bf56010aad | |||
| ee72d71872 | |||
| 2b519bf355 | |||
| d795d9a923 | |||
| 648db61b45 | |||
| 260ce8ba59 | |||
| 2f9ae43a58 | |||
| 293bbfabf4 | |||
| 0086399656 | |||
| 9d2989f386 | |||
| b5edbd3df7 | |||
| 33fe7276be | |||
| a031a94a2e | |||
| 4d10c16d02 | |||
| 745c10e0d7 | |||
| 6b7a4c1e70 | |||
| 422f23fb12 | |||
| 0f966d6b9f | |||
| 7b09491557 | |||
| fafaf089c5 | |||
| b58af4267b | |||
| 8ff76f083c | |||
| 2196869c86 | |||
| dd2e23c9af | |||
| facc50cb0f | |||
| 074a1e6eff | |||
| 2fab378c6a | |||
| 5bafc30622 | |||
| d6d2e17214 | |||
| f4e8990635 | |||
| fc3a5e555e | |||
| 270b8570fc | |||
| 0750486654 | |||
| d38e2cbc07 | |||
| 7fd937fa57 | |||
| c41caac438 | |||
| 1747c13133 | |||
| ffd0aaf69b | |||
| 81e7074d93 | |||
| f66a23d19d | |||
| f602819523 | |||
| 85a773ea02 | |||
| fb0a64fe4f | |||
| bcf46dafb9 | |||
| b118c33e37 | |||
| da74cc23e4 | |||
| d792b61722 | |||
| 1faadf7e10 | |||
| e87b44126c | |||
| 62476ddb55 | |||
| e899817969 | |||
| 1cc9a003fd | |||
| 6d507f8128 | |||
| 2cbd55b8bd | |||
| 1fcec32a3c | |||
| 768bcb565a | |||
| 63b4ad2e9c | |||
| d70eb99a0d | |||
| d44de3af43 | |||
| 25dd94234c | |||
| 600fa6be8a | |||
| 781a3ee829 | |||
| a9de61771a | |||
| 9873f9b44f | |||
| 09a82852c0 | |||
| 4074e77d93 | |||
| d3944be1be | |||
| ce964b9a00 | |||
| 1d7d9c5e9c | |||
| adac89c8e2 | |||
| 65a2e51af8 | |||
| 04a97adbb3 | |||
| 8829ae2675 | |||
| 09a1718103 | |||
| f03a9e79a7 | |||
| bb66914b1e | |||
| 8053d6a50a | |||
| 7cbf5a2c00 | |||
| 0895c70fc9 | |||
| 16c41612ca | |||
| 7ef3e353c6 | |||
| 10b9e6b81f | |||
| 360ce696e0 | |||
| 0548d335d4 | |||
| 79d55b46a6 | |||
| 93c0529e00 | |||
| a29c2b25d0 | |||
| 654f9f82c7 | |||
| 45b3cd15df | |||
| d006e38a2f | |||
| 438db357ff | |||
| 3ff4eb5519 | |||
| f34cb42b07 | |||
| ac4de93928 | |||
| 6763fe4d44 | |||
| 44a60c1261 | |||
| f09f606bec | |||
| e6349c016e | |||
| e630605aef | |||
| 74e563dabc | |||
| ae0b29af3d | |||
| d68c75a82c | |||
| a615f7f786 | |||
| 0808de0b3b | |||
| aba3a7ae43 | |||
| fa3adca5fc | |||
| f78084c230 | |||
| 7004e1de7b | |||
| e2a30c0600 | |||
| eb0abe7c90 | |||
| c822d34ce6 | |||
| 0889eb4e01 | |||
| 77f00eeab1 | |||
| 86daf254cf | |||
| 9ea3a250db | |||
| c537d2b95c | |||
| f538da9a8e | |||
| 015aeb1fab | |||
| 0d27480719 | |||
| 81a9a1fed3 | |||
| a01ca5a0a1 | |||
| 3239430996 | |||
| 65ead1f799 | |||
| 6cc45a4f77 | |||
| f6c4c9a67c | |||
| 10a25f5959 | |||
| a57327c13f | |||
| 37e49246a6 | |||
| 0351e5e166 | |||
| 98c05dd08d | |||
| 4811af7ab2 | |||
| ba17829202 | |||
| 8f696064d5 | |||
| 3819a23344 | |||
| cedc38fee8 | |||
| 198af4709d | |||
| 696ff78302 | |||
| f2da86b455 | |||
| 5212758698 | |||
| 9e73912d24 | |||
| 6d328b1ad7 | |||
| 27c92caee8 | |||
| 85966881d3 | |||
| dc170b1f58 | |||
| 37269fd96a | |||
| e832133e47 | |||
| 51a41c0c30 | |||
| 8b8ec7fb1d | |||
| 8f4747b1ff | |||
| be7b3d796c | |||
| 760c8ef72c | |||
| 3c4fb62d3a | |||
| cc86c3dd04 | |||
| 32898a68eb | |||
| 55e438d18c | |||
| a653f74cab | |||
| 4913a1363b | |||
| 6edcc07c1b | |||
| 7369c7c642 | |||
| 7db4e8df4a | |||
| 5d5cfc07d7 | |||
| d592b1e6af | |||
| b5449ea3f9 | |||
| 73dbf3cde7 | |||
| debd2cd386 | |||
| d95abaff1b | |||
| 13086c3662 | |||
| 5719e4db5f | |||
| 9ac3f40955 | |||
| 3a5c58da75 | |||
| 7cf3402ef4 | |||
| 6066d0af02 | |||
| 7e029db44a | |||
| f569b9394e | |||
| fce9942ae0 | |||
| 93ae65f99f | |||
| f8d3890e6a | |||
| 85a11ad416 | |||
| 2be0c5c892 | |||
| e0af7bd8a0 | |||
| 1d1678214a | |||
| 06899c669c | |||
| 05f05dd372 | |||
| a195f4f194 | |||
| 28caa40e68 | |||
| 6c1ce446f5 | |||
| 729494a59b | |||
| df69bced42 | |||
| 12c8f9637f | |||
| 7fe8a70032 | |||
| 2e8e097683 | |||
| 24dfd04964 | |||
| 86965950ac | |||
| 79e9225c68 | |||
| 1a3880347f | |||
| 20968d5a87 | |||
| a7200dd39b | |||
| d1f732bae1 | |||
| d849189b8c | |||
| d30b2d11e6 | |||
| 156009f9ad | |||
| 0aa8d17d6c | |||
| 39331fafb5 | |||
| 05f87b0f50 | |||
| 9f1435f761 | |||
| 772ddf4a86 | |||
| 432b41cede | |||
| e7466175ef | |||
| 5bf7caecc9 | |||
| 4bf389ed09 | |||
| 90acad0d4b | |||
| 6e6b860f04 | |||
| e4c7a3aad9 | |||
| ac4627b69d | |||
| 99660e1c6d | |||
| f91f37ef70 | |||
| 682ec11003 | |||
| 41c0ffbb52 | |||
| be430fc4a4 | |||
| 15f2b106ab | |||
| e310336a42 | |||
| e1585aa4aa | |||
| 6a392542f3 | |||
| 7b3bc598f4 | |||
| 239cc02422 | |||
| 44f12f266e | |||
| 8e8ce8ddd6 | |||
| f2ccf8b21f | |||
| 5d9d21f227 | |||
| 537f492762 | |||
| 6a0a7622fd | |||
| 719867a819 | |||
| 9dfea188bf | |||
| df908b4c11 | |||
| be126afcf8 | |||
| b2243efd3f | |||
| 79c04c71e9 | |||
| ebd2332db4 | |||
| 070ec4c711 | |||
| 6fc79e90ac | |||
| f5ad59317c | |||
| 803df21fc2 | |||
| df47536b8d | |||
| 2049eb7713 | |||
| f42cee8512 | |||
| 8a00f954a9 | |||
| 6d1d626d87 | |||
| 8632072ce0 | |||
| c637b5057b | |||
| 153b788134 | |||
| bc2d934b94 | |||
| 2b1e2e9e20 | |||
| b5b96980e3 | |||
| 127745d13b | |||
| 5ec1e12a50 | |||
| 7c1af0385a | |||
| dde2d25804 | |||
| 7f71fbc3ea | |||
| 7017127a11 | |||
| 00643b5a4b | |||
| e25c279e4b | |||
| df54d8d2bf | |||
| 8ae31aeb13 | |||
| cc86760a26 | |||
| 2e7cfbe1fa | |||
| 9dbe31bfb0 | |||
| 2bf372b41c | |||
| a86990fc58 | |||
| f4c1b264c6 | |||
| 031a600725 | |||
| b385b25d5f | |||
| 49b72bd09c | |||
| 0a3333b961 | |||
| 1638db9c86 | |||
| cd9ad1a7f2 | |||
| 023f1ba575 | |||
| 1a4659b7fc | |||
| 965b0e143c | |||
| 1eca28e588 | |||
| a80421efb6 | |||
| 89efd7d44b | |||
| 41980df6f1 | |||
| baa4449a03 | |||
| 1ee51be420 | |||
| 94931ba59f | |||
| 49ecd806a2 | |||
| 1eaa5c2a81 | |||
| e107c5876e | |||
| 4f7061fd61 | |||
| 7690860ab1 | |||
| b6366e9da5 | |||
| 64122269e9 | |||
| 1bdd515941 | |||
| 8ac0ae72dc | |||
| b2458f9891 | |||
| 2252776a97 | |||
| c9fecd53dc | |||
| 75268e7f43 | |||
| 8ef9b8b215 | |||
| 459b825daa | |||
| 3247773447 | |||
| 013beab861 | |||
| c5230e85a9 |
@@ -15,6 +15,10 @@ build/
|
||||
# at runtime — never baked into the image. Mirrored in .gitignore.
|
||||
secrets.env
|
||||
secrets.env.*
|
||||
secrets.env~
|
||||
.secrets.env.swp
|
||||
.secrets.env.swo
|
||||
**/#secrets.env#
|
||||
!secrets.env.example
|
||||
/data/
|
||||
/logs/
|
||||
|
||||
@@ -19,7 +19,7 @@ jobs:
|
||||
name: Python syntax (compileall)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
|
||||
@@ -32,7 +32,7 @@ jobs:
|
||||
name: JS syntax (node --check)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
@@ -54,7 +54,7 @@ jobs:
|
||||
# ROADMAP "fresh install smoke tests" item; make this required once green.
|
||||
continue-on-error: true
|
||||
steps:
|
||||
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
with:
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
# CodeQL code scanning
|
||||
#
|
||||
# Purpose: GitHub's own static analysis engine reads the application source
|
||||
# (Python backend + the JavaScript frontend) and looks for real
|
||||
# vulnerabilities -- SQL/command injection, path traversal, auth mistakes,
|
||||
# unsafe deserialization. Findings appear in the repo's Security tab. This is
|
||||
# the deepest check in the suite and the most valuable for a high-profile
|
||||
# target.
|
||||
#
|
||||
# It runs on every push to main and on a weekly schedule (to catch newly
|
||||
# disclosed query patterns against unchanged code). It deliberately does NOT
|
||||
# run on pull requests: most PRs here come from forks, whose read-only token
|
||||
# cannot publish results, which would produce confusing failures. To scan pull
|
||||
# requests too, a maintainer can instead enable CodeQL "default setup" in
|
||||
# Settings -> Security -> Code scanning (one toggle, no file needed) -- see
|
||||
# docs/security-ci.md.
|
||||
|
||||
name: CodeQL
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
schedule:
|
||||
# Weekly, Monday 06:00 UTC.
|
||||
- cron: '0 6 * * 1'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions: {}
|
||||
|
||||
concurrency:
|
||||
group: codeql-${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
analyze:
|
||||
name: Analyze (${{ matrix.language }})
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
security-events: write # publish results to the Security tab
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
# Both are interpreted, so CodeQL needs no build step (build-mode none).
|
||||
language: [python, javascript-typescript]
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@8aad20d150bbac5944a9f9d289da16a4b0d87c1e # v4.36.2
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
build-mode: none
|
||||
|
||||
- name: Perform CodeQL analysis
|
||||
uses: github/codeql-action/analyze@8aad20d150bbac5944a9f9d289da16a4b0d87c1e # v4.36.2
|
||||
with:
|
||||
category: "/language:${{ matrix.language }}"
|
||||
@@ -37,7 +37,7 @@ jobs:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
|
||||
@@ -52,7 +52,7 @@ jobs:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
@@ -93,7 +93,7 @@ jobs:
|
||||
security-events: write # upload SARIF to the Security tab
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ jobs:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
@@ -55,7 +55,7 @@ jobs:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
|
||||
@@ -45,7 +45,7 @@ jobs:
|
||||
arch: arm64
|
||||
runner: ubuntu-24.04-arm
|
||||
steps:
|
||||
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Set up Buildx
|
||||
@@ -86,7 +86,7 @@ jobs:
|
||||
contents: read
|
||||
packages: write
|
||||
steps:
|
||||
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Read APP_VERSION + short sha
|
||||
|
||||
@@ -14,7 +14,7 @@ jobs:
|
||||
# Skip bots (Dependabot, release-drafter, etc.)
|
||||
if: ${{ github.event.issue.user.type != 'Bot' }}
|
||||
steps:
|
||||
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
with:
|
||||
sparse-checkout: .github/scripts
|
||||
persist-credentials: false
|
||||
|
||||
@@ -23,7 +23,7 @@ jobs:
|
||||
# Skip bots: they open PRs programmatically and have their own process.
|
||||
if: github.event.pull_request.user.type != 'Bot'
|
||||
steps:
|
||||
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
with:
|
||||
ref: ${{ github.base_ref }}
|
||||
sparse-checkout: .github/scripts
|
||||
|
||||
@@ -35,7 +35,7 @@ jobs:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
with:
|
||||
# Full history so a secret committed in an earlier commit (and later
|
||||
# deleted) is still caught -- deletion does not remove it from Git.
|
||||
|
||||
@@ -36,7 +36,7 @@ jobs:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
@@ -61,7 +61,7 @@ jobs:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ Manual development uses Python 3.11+:
|
||||
python3 -m venv venv
|
||||
source venv/bin/activate
|
||||
pip install -r requirements.txt
|
||||
python -m uvicorn app:app --host 0.0.0.0 --port 7000
|
||||
python -m uvicorn app:app --host 127.0.0.1 --port 7000
|
||||
```
|
||||
|
||||
Windows is not actively tested. Docker on Linux or a Linux/macOS manual install is the safer path for now.
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
# -*- mode: python ; coding: utf-8 -*-
|
||||
|
||||
|
||||
a = Analysis(
|
||||
['launcher.py'],
|
||||
pathex=[],
|
||||
binaries=[],
|
||||
datas=[('static', 'static'), ('scripts', 'scripts'), ('mcp_servers', 'mcp_servers'), ('services/hwfit/data', 'services/hwfit/data'), ('config', 'config'), ('.env.example', '.env.example')],
|
||||
hiddenimports=[],
|
||||
hookspath=[],
|
||||
hooksconfig={},
|
||||
runtime_hooks=[],
|
||||
excludes=[],
|
||||
noarchive=False,
|
||||
optimize=0,
|
||||
)
|
||||
pyz = PYZ(a.pure)
|
||||
|
||||
exe = EXE(
|
||||
pyz,
|
||||
a.scripts,
|
||||
[],
|
||||
exclude_binaries=True,
|
||||
name='Odysseus',
|
||||
debug=False,
|
||||
bootloader_ignore_signals=False,
|
||||
strip=False,
|
||||
upx=True,
|
||||
console=False,
|
||||
disable_windowed_traceback=False,
|
||||
argv_emulation=False,
|
||||
target_arch=None,
|
||||
codesign_identity=None,
|
||||
entitlements_file=None,
|
||||
icon=['static\\icon.ico'],
|
||||
)
|
||||
coll = COLLECT(
|
||||
exe,
|
||||
a.binaries,
|
||||
a.datas,
|
||||
strip=False,
|
||||
upx=True,
|
||||
upx_exclude=[],
|
||||
name='Odysseus',
|
||||
)
|
||||
@@ -1,476 +1,65 @@
|
||||
# Odysseus
|
||||
<p align="center">
|
||||
<img src="docs/odysseus-wordmark.png" alt="Odysseus" width="280">
|
||||
</p>
|
||||
|
||||
> **Branch note:** `dev` is the default branch and contains the latest development changes, but it may be unstable. For the more stable curated branch, use [`main`](https://github.com/pewdiepie-archdaemon/odysseus/tree/main).
|
||||
<p align="center">
|
||||
A self-hosted AI workspace for chat, agents, research, documents, email, notes, calendar, and local model workflows.
|
||||
</p>
|
||||
|
||||
```
|
||||
───────────────────────────────────────────────
|
||||
⊹ ࣪ ˖ ૮( ˶ᵔ ᵕ ᵔ˶ )っ Odysseus vers. 1.0
|
||||
───────────────────────────────────────────────
|
||||
```
|
||||
<p align="center">
|
||||
<a href="#quick-start">Quick Start</a> ·
|
||||
<a href="docs/setup.md">Setup Guide</a> ·
|
||||
<a href="CONTRIBUTING.md">Contributing</a> ·
|
||||
<a href="ROADMAP.md">Roadmap</a>
|
||||
</p>
|
||||
|
||||

|
||||
<p align="center">
|
||||
<a href="https://repology.org/project/odysseus-ai/versions"><img src="https://repology.org/badge/vertical-allrepos/odysseus-ai.svg" alt="Packaging status"></a>
|
||||
</p>
|
||||
|
||||
A self-hosted AI workspace -- meant to be the self-hosted version of the UI experience you get from ChatGPT and Claude. But with more jank and fun. Running on your own hardware, with your own data -- local-first, privacy-first, and no trojan.
|
||||
<p align="center">
|
||||
<img src="docs/odysseus.jpg" alt="Odysseus interface">
|
||||
</p>
|
||||
|
||||
[](https://repology.org/project/odysseus-ai/versions)
|
||||
|
||||
## Features
|
||||
- **Chat** -- chat with any local model or API; adding them is super simple.<br> <sub>vLLM · llama.cpp · Ollama · OpenRouter · OpenAI · GitHub Copilot</sub>
|
||||
- **Agent** -- hand it tools and let it run the whole task itself.<br> <sub>built on [opencode](https://github.com/anomalyco/opencode) · MCP · web · files · shell · skills · memory</sub>
|
||||
- **Cookbook** -- Scans your hardware, recommends models, click to download and serve.. easy!<br> <sub>built on [llmfit](https://github.com/AlexsJones/llmfit) · VRAM-aware · GGUF / FP8 / AWQ · fit scoring · vLLM / llama.cpp serving</sub>
|
||||
- **Deep Research** -- multi-step runs that gather, read, and synthesize sources into a nice visual report.<br> <sub>adapted from [Tongyi DeepResearch](https://github.com/Alibaba-NLP/DeepResearch)</sub>
|
||||
- **Compare** -- a fun tool to compare models side by side. Test completely blind, no bias!<br> <sub>multi-model · blind test · synthesis</sub>
|
||||
- **Documents** -- YOU write the text, AI is there to assist, not the opposite.<br> <sub>multi-tab editor · markdown · HTML · CSV · syntax highlighting · AI edits · suggestions</sub>
|
||||
- **Memory / Skills** -- Persistent memory and skills, your agent evolves over time as it better understands you and your tasks!<br> <sub>ChromaDB · fastembed (ONNX) · vector + keyword retrieval · import/export</sub>
|
||||
- **Email** -- IMAP/SMTP inbox with AI triage built in: urgency reminders, auto-tag, auto-summary, auto-reply drafts, auto-spam.<br> <sub>IMAP · SMTP · per-account routing · CalDAV-aware</sub>
|
||||
- **Notes & Tasks** -- Quick notes with reminders, a todo list, and scheduled tasks the agent can act on.<br> <sub>note pings · checklist · cron-style tasks · ntfy / browser / email channels</sub>
|
||||
- **Calendar** -- Local-first calendar with CalDAV sync to Radicale / Nextcloud / Apple / Fastmail.<br> <sub>CalDAV pull · .ics import/export · per-calendar colors · agent-aware</sub>
|
||||
- **Works on mobile** -- looks and runs great on your phone, not just desktop.<br> <sub>responsive · installable (PWA) · touch gestures</sub>
|
||||
- **Extras** -- more to explore, happy if you give it a go!<br> <sub>image editor · theme editor · file uploads (vision + PDF) · web search · presets · sessions · 2FA</sub>
|
||||
|
||||
## Demo
|
||||
A full, hover-to-play tour lives on the landing page (`docs/index.html`).
|
||||
|
||||
<details>
|
||||
<summary>Screenshots / clips</summary>
|
||||
|
||||
### Chat & Agents
|
||||

|
||||
### Deep Research
|
||||

|
||||
### Compare
|
||||

|
||||
### Documents
|
||||

|
||||
### Notes & Tasks
|
||||

|
||||
|
||||
</details>
|
||||
---
|
||||
|
||||
## Quick Start
|
||||
|
||||
Defaults work out of the box: clone, run, then configure models/search/email
|
||||
inside **Settings**. Only edit `.env` for deployment-level overrides like
|
||||
`APP_BIND`, `APP_PORT`, `AUTH_ENABLED`, `DATABASE_URL`, or a pre-seeded admin password.
|
||||
> `dev` is the default branch and gets the newest changes first. Use [`main`](https://github.com/pewdiepie-archdaemon/odysseus/tree/main) if you want the more curated branch.
|
||||
|
||||
On first setup, Odysseus creates an admin account (`admin` unless
|
||||
`ODYSSEUS_ADMIN_USER` is set) and prints a temporary password in the terminal.
|
||||
For Docker installs, the same line is in `docker compose logs odysseus`.
|
||||
Use that for the first login, then change it in **Settings**.
|
||||
|
||||
Contributing? See [CONTRIBUTING.md](CONTRIBUTING.md) for setup, testing, and
|
||||
pull request guidelines.
|
||||
|
||||
### Docker (recommended)
|
||||
```bash
|
||||
git clone https://github.com/pewdiepie-archdaemon/odysseus.git
|
||||
cd odysseus
|
||||
cp .env.example .env # optional, but recommended for explicit defaults
|
||||
cp .env.example .env
|
||||
docker compose up -d --build
|
||||
```
|
||||
To include optional extras in the image (PDF viewer, Office extraction; includes AGPL PyMuPDF), build with `docker compose build --build-arg INSTALL_OPTIONAL=true` before `up`.
|
||||
|
||||
Open `http://localhost:7000` when the containers are healthy. Docker Compose
|
||||
binds the web UI to `127.0.0.1` by default. If the port is taken, set
|
||||
`APP_PORT=7001` in `.env` and recreate the container. Set `APP_BIND=0.0.0.0`
|
||||
only when you intentionally want LAN/reverse-proxy access.
|
||||
Open `http://localhost:7000` when the containers are healthy. The first admin password is printed in `docker compose logs odysseus`.
|
||||
|
||||
> **On Apple Silicon (M-series) Macs:** Docker can't reach the Metal GPU, so
|
||||
> Cookbook serves local models on CPU only. For GPU-accelerated model serving,
|
||||
> run natively instead — see [Apple Silicon](#apple-silicon) below.
|
||||
Native installs, GPU notes, Windows/macOS instructions, HTTPS, and configuration live in the [setup guide](docs/setup.md).
|
||||
|
||||
### Native Linux / macOS
|
||||
```bash
|
||||
git clone https://github.com/pewdiepie-archdaemon/odysseus.git
|
||||
cd odysseus
|
||||
python3 -m venv venv
|
||||
source venv/bin/activate
|
||||
pip install -r requirements.txt
|
||||
python setup.py
|
||||
python -m uvicorn app:app --host 127.0.0.1 --port 7000
|
||||
```
|
||||
Requirements: Python 3.11+. Cookbook also needs `tmux` for background model
|
||||
downloads and serves. The app itself is lightweight; local model serving is the
|
||||
heavy part and depends on the model, runtime, GPU, and VRAM, so small hosts can
|
||||
connect to API or remote model servers instead. Use `--host 0.0.0.0` only when you intentionally want LAN/reverse-proxy access.
|
||||
## Features
|
||||
|
||||
### Apple Silicon
|
||||
Docker on macOS cannot use the Metal GPU. For GPU-accelerated Cookbook on an
|
||||
M-series Mac, run Odysseus natively:
|
||||
- **Chat + Agents** — local/API models, tools, MCP, files, shell, skills, and memory.
|
||||
- **Cookbook** — hardware-aware model recommendations, downloads, and serving.
|
||||
- **Deep Research** — multi-step web research with source reading and report generation.
|
||||
- **Compare** — blind side-by-side model testing and synthesis.
|
||||
- **Documents** — writing-first editor with AI edits, suggestions, Markdown, HTML, CSV, and syntax highlighting.
|
||||
- **Email** — IMAP/SMTP inbox with triage, tags, summaries, reminders, and reply drafts.
|
||||
- **Notes, Tasks + Calendar** — reminders, todos, scheduled agent tasks, and CalDAV sync.
|
||||
- **Extras** — gallery/image editor, themes, uploads, web search, presets, sessions, and 2FA.
|
||||
|
||||
```bash
|
||||
git clone https://github.com/pewdiepie-archdaemon/odysseus.git
|
||||
cd odysseus
|
||||
./start-macos.sh
|
||||
```
|
||||
## Demo
|
||||
|
||||
It launches at `http://127.0.0.1:7860`. To expose it to your phone over a trusted LAN/VPN such as Tailscale, bind all interfaces:
|
||||
|
||||
```bash
|
||||
ODYSSEUS_HOST=0.0.0.0 ./start-macos.sh
|
||||
# then open http://<tailscale-ip>:7860
|
||||
```
|
||||
|
||||
The script also reads `.env` at startup, so `APP_BIND=0.0.0.0` and `APP_PORT`
|
||||
set there are picked up automatically without a command-line override each run.
|
||||
|
||||
Keep `AUTH_ENABLED=true` (the default) before binding outside loopback. Do not
|
||||
expose this port directly to the public internet. To build a clickable app wrapper:
|
||||
|
||||
```bash
|
||||
./build-macos-app.sh
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Cookbook, GPU, Ollama, and troubleshooting notes</summary>
|
||||
|
||||
**Docker bundled services.** Compose starts Odysseus, ChromaDB, SearXNG, and
|
||||
ntfy. Odysseus and the bundled service ports bind to `127.0.0.1` by default, so
|
||||
they are reachable from the host but not exposed to your LAN/public internet
|
||||
unless you opt in.
|
||||
|
||||
**Cookbook storage in Docker.** Downloads live in `./data/huggingface`
|
||||
(`~/.cache/huggingface` in the container). Cookbook-installed Python CLIs and
|
||||
serve engines live in `./data/local` (`~/.local` in the container), so they
|
||||
survive container recreation.
|
||||
|
||||
**Remote servers.** In **Cookbook -> Settings -> Servers**, generate the
|
||||
Odysseus SSH key and add the public key to the remote server's
|
||||
`~/.ssh/authorized_keys`. From the host you can also run:
|
||||
|
||||
```bash
|
||||
ssh-copy-id -i data/ssh/id_ed25519.pub user@server
|
||||
```
|
||||
|
||||
**Docker GPU overlays.** CPU-only users can skip this section. Cookbook can
|
||||
only detect GPUs that Docker exposes to the container — if the host runtime or
|
||||
device passthrough is not configured, Cookbook sees the iGPU, another card, or
|
||||
CPU instead of your intended GPU.
|
||||
|
||||
For NVIDIA, `scripts/check-docker-gpu.sh` diagnoses GPU passthrough and can
|
||||
optionally install the host runtime or update `.env`.
|
||||
|
||||
```bash
|
||||
# Read-only diagnostic (default — installs nothing, never edits .env):
|
||||
scripts/check-docker-gpu.sh
|
||||
|
||||
# Print OS-specific install commands without running them:
|
||||
scripts/check-docker-gpu.sh --print-install-commands
|
||||
|
||||
# Install NVIDIA Container Toolkit on Ubuntu/Debian (requires sudo):
|
||||
scripts/check-docker-gpu.sh --install-nvidia-toolkit
|
||||
|
||||
# Write COMPOSE_FILE to .env (only when GPU passthrough is confirmed working):
|
||||
scripts/check-docker-gpu.sh --enable-nvidia-overlay
|
||||
|
||||
# Full assisted setup — install toolkit, then enable overlay if passthrough works:
|
||||
scripts/check-docker-gpu.sh --install-nvidia-toolkit --enable-nvidia-overlay
|
||||
```
|
||||
|
||||
Safety notes:
|
||||
- The app never installs host GPU runtime automatically.
|
||||
- The app never edits `.env` automatically.
|
||||
- `.env` is only modified when `--enable-nvidia-overlay` is explicitly passed,
|
||||
and only after GPU passthrough succeeds. `--yes` skips prompts but does not
|
||||
bypass the passthrough gate.
|
||||
- `.env.bak.*` backups created by `--enable-nvidia-overlay` are ignored by
|
||||
Git and the Docker build context.
|
||||
|
||||
To enable manually without the script, add this to `.env`:
|
||||
|
||||
```bash
|
||||
COMPOSE_FILE=docker-compose.yml:docker/gpu.nvidia.yml
|
||||
```
|
||||
|
||||
**AMD / ROCm.** AMD setup is read-only diagnostic plus manual `.env` edit. Run:
|
||||
|
||||
```bash
|
||||
scripts/check-docker-amd-gpu.sh
|
||||
```
|
||||
|
||||
Then add the reported values to `.env`, replacing `RENDER_GID` with your host's
|
||||
numeric render group id:
|
||||
|
||||
```bash
|
||||
COMPOSE_FILE=docker-compose.yml:docker/gpu.amd.yml
|
||||
RENDER_GID=989
|
||||
```
|
||||
|
||||
For NVIDIA/AMD GPU support, also read the comments in the selected overlay file: docker/gpu.nvidia.yml or docker/gpu.amd.yml.
|
||||
|
||||
**Stack-management UIs (Portainer, Coolify, Dockhand, etc.).** These tools
|
||||
often accept only a single Compose file and do not reliably honor `COMPOSE_FILE`
|
||||
or multiple `-f` overlays. CLI users should keep using the `COMPOSE_FILE`
|
||||
overlay workflow above. For stack UIs, point the stack at one of the standalone
|
||||
files instead, which bundle the base stack plus the GPU settings:
|
||||
|
||||
- `docker-compose.gpu-nvidia.yml` — still requires the NVIDIA Container Toolkit
|
||||
on the host.
|
||||
- `docker-compose.gpu-amd.yml` — still requires host ROCm/kfd/DRI setup, the
|
||||
`video`/`render` group membership, and `RENDER_GID` when needed.
|
||||
|
||||
The base `docker-compose.yml` plus the `docker/gpu.*.yml` overlays remain the
|
||||
source of truth; the standalone files mirror them for single-file deployments.
|
||||
|
||||
Verify after enabling either overlay:
|
||||
|
||||
```bash
|
||||
docker compose exec odysseus nvidia-smi -L # NVIDIA
|
||||
docker compose exec odysseus sh -lc 'test -e /dev/kfd && test -d /dev/dri && ls -l /dev/kfd /dev/dri/renderD*' # AMD
|
||||
```
|
||||
|
||||
> **GPU passthrough ≠ llama.cpp CUDA.** `nvidia-smi` passing inside the
|
||||
> container confirms Docker GPU access, but llama.cpp also needs `cudart` and
|
||||
> the CUDA Toolkit at runtime. If Cookbook logs show `Unable to find cudart
|
||||
> library`, `Could NOT find CUDAToolkit`, `CUDA Toolkit not found`, or
|
||||
> tensors/layers assigned to CPU, that is a Cookbook/llama.cpp build issue —
|
||||
> not a Docker passthrough failure. Reinstall the serve engine via
|
||||
> **Cookbook → Dependencies** to get a CUDA-enabled build.
|
||||
>
|
||||
> The same split applies to AMD/ROCm: seeing `/dev/kfd` and `/dev/dri` inside
|
||||
> the container confirms device passthrough, not ROCm userspace or a
|
||||
> ROCm-enabled vLLM/llama.cpp build. `rocm-smi` and `rocminfo` are not expected
|
||||
> inside the slim Odysseus image.
|
||||
|
||||
**Ollama with Docker.** If Ollama runs on the host, add this endpoint in
|
||||
Settings:
|
||||
|
||||
```text
|
||||
http://host.docker.internal:11434/v1
|
||||
```
|
||||
|
||||
Ollama must listen outside its own loopback interface:
|
||||
|
||||
```bash
|
||||
OLLAMA_HOST=0.0.0.0:11434 ollama serve
|
||||
```
|
||||
|
||||
This connects Odysseus in Docker to an Ollama server that is already running on
|
||||
your host machine; it does not start Ollama inside the container.
|
||||
`host.docker.internal` is Docker's hostname for the host machine from inside the
|
||||
container. Cookbook **Serve** is a separate workflow for serving downloaded
|
||||
models through Odysseus/llama.cpp, so Windows users with an existing Ollama
|
||||
install usually only need to add the endpoint in Settings.
|
||||
|
||||
**Useful checks.**
|
||||
|
||||
```bash
|
||||
docker compose ps
|
||||
docker compose logs --tail=120 odysseus
|
||||
docker compose logs odysseus | grep -E 'ChromaDB|MemoryVectorStore|DEGRADED'
|
||||
```
|
||||
|
||||
**macOS details.** `start-macos.sh` installs Homebrew deps, creates the venv,
|
||||
runs setup, and starts uvicorn on port `7860` because AirPlay often holds
|
||||
`7000`. It uses llama.cpp/Ollama for Metal. vLLM/SGLang are CUDA/ROCm-only and
|
||||
do not run on macOS. MLX-only models are not served by Odysseus.
|
||||
|
||||
</details>
|
||||
|
||||
### Native Windows
|
||||
|
||||
**One-command launcher** (creates the venv, installs deps, runs setup, starts the
|
||||
server; safe to re-run):
|
||||
|
||||
```powershell
|
||||
git clone https://github.com/pewdiepie-archdaemon/odysseus.git
|
||||
cd odysseus
|
||||
powershell -ExecutionPolicy Bypass -File .\launch-windows.ps1
|
||||
```
|
||||
|
||||
Or do it by hand:
|
||||
|
||||
```powershell
|
||||
git clone https://github.com/pewdiepie-archdaemon/odysseus.git
|
||||
cd odysseus
|
||||
py -3.11 -m venv venv
|
||||
venv\Scripts\Activate.ps1
|
||||
pip install -r requirements.txt
|
||||
python setup.py
|
||||
python -m uvicorn app:app --host 127.0.0.1 --port 7000
|
||||
```
|
||||
|
||||
If `python` points at an older interpreter, use `py -3.12` (or another installed
|
||||
3.11+ version) for the venv step.
|
||||
|
||||
**Requirements:** Python 3.11+. The core app (chat, agent, memory, documents,
|
||||
email, calendar, deep research) runs fully native. For full **Cookbook** background
|
||||
model downloads and the agent shell tool, also install
|
||||
[Git for Windows](https://git-scm.com/download/win) (provides `bash.exe`).
|
||||
Local GPU *serving* of vLLM/SGLang needs Linux/WSL2; for a local model on Windows,
|
||||
[Ollama](https://ollama.com/download) is the easiest path — point Odysseus at
|
||||
`http://localhost:11434/v1` in Settings.
|
||||
|
||||
Open `http://localhost:7000`, log in with the generated admin password,
|
||||
and configure everything else inside **Settings**.
|
||||
|
||||
## Troubleshooting & Advanced Setup
|
||||
|
||||
### `chromadb-client` conflicts with embedded ChromaDB
|
||||
If `chromadb-client` (the lightweight HTTP-only package) is installed alongside the full `chromadb` package, Odysseus starts but ChromaDB silently falls back to HTTP-only mode and fails.
|
||||
|
||||
**Fix:** uninstall `chromadb-client` and force-reinstall the full package:
|
||||
```bash
|
||||
./venv/bin/pip uninstall chromadb-client -y
|
||||
./venv/bin/pip install --force-reinstall chromadb
|
||||
```
|
||||
|
||||
### HTTPS + LAN/Tailscale exposure
|
||||
To expose Odysseus on a local network or Tailscale with HTTPS:
|
||||
1. Change the bind address to `0.0.0.0` in `.env` (`APP_BIND=0.0.0.0` or `ODYSSEUS_HOST=0.0.0.0`).
|
||||
2. Generate a locally-trusted cert for your LAN/Tailscale IPs using [mkcert](https://github.com/FiloSottile/mkcert):
|
||||
```bash
|
||||
mkcert -install
|
||||
mkcert -cert-file cert.pem -key-file key.pem 192.168.1.100 tailscale-ip
|
||||
```
|
||||
3. Run `uvicorn` with the generated certs:
|
||||
```bash
|
||||
python -m uvicorn app:app --host 0.0.0.0 --port 7000 --ssl-certfile=cert.pem --ssl-keyfile=key.pem
|
||||
```
|
||||
4. Install the `mkcert` CA on any other device you want to access Odysseus from (e.g., for iOS, email the `rootCA.pem` to yourself, install the profile, and trust it in Certificate Trust Settings).
|
||||
|
||||
### Optional Dependencies
|
||||
`requirements-optional.txt` contains packages that unlock extra features. It is not installed by default.
|
||||
|
||||
| Package | Feature unlocked |
|
||||
|---------|-----------------|
|
||||
| `faster-whisper` | Local speech-to-text (microphone -> text) via the "local" STT provider. |
|
||||
| `ddgs` | DuckDuckGo as a search provider option. |
|
||||
| `PyMuPDF` | PDF page rendering in the side viewer panel and form-filling. (Note: AGPL-3.0) |
|
||||
| `markitdown` | Office/EPUB document text extraction (converts .docx/.xlsx/.pptx/.xls/.epub to Markdown). |
|
||||
|
||||
### Faster, reproducible installs with uv (optional)
|
||||
[uv](https://docs.astral.sh/uv/) works as a drop-in replacement for the
|
||||
venv + pip steps in the native install guides, no project changes are needed but this change results in faster installs along with a lockfile for reproducible environments. After [installing `uv`](https://docs.astral.sh/uv/getting-started/installation/), use:
|
||||
|
||||
```bash
|
||||
uv venv venv --python 3.13
|
||||
uv pip install -r requirements.txt
|
||||
# then continue as usual: python setup.py, uvicorn, ...
|
||||
```
|
||||
|
||||
`requirements.txt` is intentionally unpinned, so two installs at different times can produce different package versions. If you want a reproducible environment (e.g. across your own machines, or to roll back after a bad upgrade), snapshot and restore exact versions with:
|
||||
|
||||
```bash
|
||||
uv pip compile requirements.txt -o requirements.lock # snapshot current resolution
|
||||
uv pip sync requirements.lock # reproduce it exactly later
|
||||
```
|
||||
|
||||
`requirements.lock` is gitignored and platform-specific (compile it on the OS you deploy to). Regenerate it deliberately when you want to take upgrades. The plain `uv pip install -r requirements.txt` keeps following the unpinned requirements like pip does.
|
||||
|
||||
### Outlook / Office 365 email
|
||||
Odysseus email accounts currently use IMAP/SMTP username-password auth. Outlook
|
||||
and Microsoft 365 generally require OAuth instead, so normal Microsoft mailbox
|
||||
passwords will fail. See [docs/email-outlook.md](docs/email-outlook.md) for the
|
||||
current limitation and the planned integration direction.
|
||||
|
||||
## Security Notes
|
||||
Odysseus is a self-hosted workspace with powerful local tools: shell access, file uploads, model downloads, web research, email/calendar integrations, and API tokens. Treat it like an admin console.
|
||||
|
||||
- Keep `AUTH_ENABLED=true` for any network-accessible deployment.
|
||||
- Keep `LOCALHOST_BYPASS=false` outside local development.
|
||||
- Use `SECURE_COOKIES=true` when Odysseus is served through HTTPS by a trusted reverse proxy or private access gateway.
|
||||
- Do not expose it directly to the public internet without HTTPS and a trusted reverse proxy or private access layer.
|
||||
- Keep `.env`, `data/`, `logs/`, databases, uploads, generated media, backups, auth/session files, API keys, and model/provider tokens out of Git and private shares. They are ignored by default.
|
||||
- Review `data/auth.json` after first boot: disable open signup unless you intentionally want it, make only your own account admin, and keep demo/test accounts non-admin.
|
||||
- Non-admin users do not get shell/Python/file read/write by default, and admin-only routes/tools such as MCP management, API tokens, webhooks, model/cookbook serving, backup/vault, and app settings are admin-gated. Other features are controlled by per-user privileges, so review each user's privileges before exposing a deployment.
|
||||
- Rotate any API keys or tokens that were ever pasted into a shared chat, demo, screenshot, or log.
|
||||
- If you enable API tokens or webhooks, create separate tokens per integration and delete unused ones.
|
||||
- Prefer binding manual development runs to `127.0.0.1`; bind to `0.0.0.0` only when you intentionally want LAN/reverse-proxy access.
|
||||
- Keep ChromaDB, SearXNG, ntfy, Ollama, vLLM, llama.cpp, databases, and raw model/provider APIs internal-only. Expose only the authenticated Odysseus web/API entrypoint through your trusted proxy or private access layer.
|
||||
- Before publishing a fork, run `git status --short` and confirm no private files from `.env`, `data/`, `logs/`, uploads, backups, or local databases are staged.
|
||||
|
||||
### Private or proxied deployments
|
||||
Odysseus serves plain HTTP on its app port. Docker Compose binds Odysseus and the bundled services to `127.0.0.1` by default, so a typical production/private setup is:
|
||||
|
||||
1. Keep Odysseus on localhost, for example `127.0.0.1:7000`.
|
||||
2. Terminate HTTPS at a trusted reverse proxy or private access gateway.
|
||||
3. Put the authenticated Odysseus web/API entrypoint behind that layer.
|
||||
4. Keep raw service and model ports internal-only.
|
||||
|
||||
Cloudflare Access, Tailscale, Caddy, nginx, and Traefik can all fit this pattern; none are required by Odysseus. If your access layer reaches Odysseus on the same host, proxy to `http://127.0.0.1:7000` and keep `AUTH_ENABLED=true`, `LOCALHOST_BYPASS=false`, and `SECURE_COOKIES=true`.
|
||||
`ALLOWED_ORIGINS` lists exact permitted origins for cross-origin browser/API clients; ordinary same-origin reverse-proxy access usually does not need a special CORS entry.
|
||||
|
||||
Common internal-only ports from the default docs/compose setup:
|
||||
|
||||
| Port | Service |
|
||||
|---|---|
|
||||
| `7000` | Odysseus raw app port |
|
||||
| `8080` | SearXNG |
|
||||
| `8091` | ntfy |
|
||||
| `8100` | ChromaDB host port for manual/compose access |
|
||||
| `11434` | Ollama |
|
||||
| `8000-8020` | Common local model/provider APIs |
|
||||
A full hover-to-play tour lives on the landing page: [`docs/index.html`](docs/index.html).
|
||||
|
||||
## Contributing
|
||||
Help is welcome. The best entry points are fresh-install testing, provider setup
|
||||
bugs, mobile/editor polish, docs, and small focused refactors. See
|
||||
[ROADMAP.md](ROADMAP.md) for the current help-wanted list.
|
||||
|
||||
## Configuration
|
||||
Most setup is done inside the app with `/setup` or **Settings**. Use `.env`
|
||||
for deployment-level defaults and secrets you want present before first boot.
|
||||
Key settings:
|
||||
Help is welcome. The best entry points are fresh-install testing, provider setup bugs, mobile/editor polish, docs, and small focused refactors. See [CONTRIBUTING.md](CONTRIBUTING.md) and [ROADMAP.md](ROADMAP.md).
|
||||
|
||||
| Variable | Default | Description |
|
||||
|---|---|---|
|
||||
| `LLM_HOST` | `localhost` | Your LLM server (e.g. `llm-host.local:8000`) |
|
||||
| `LLM_HOSTS` | -- | Comma-separated list for model discovery |
|
||||
| `OPENAI_API_KEY` | -- | Optional OpenAI key. Prefer adding providers in the app unless pre-seeding. |
|
||||
| `SEARXNG_INSTANCE` | `http://localhost:8080` | SearXNG URL. Docker overrides this to `http://searxng:8080`. |
|
||||
| `SEARXNG_SECRET` | generated on first Docker boot | Optional SearXNG cookie/CSRF secret. Leave blank unless you need to pin it. |
|
||||
| `APP_BIND` | `127.0.0.1` | Docker Compose host bind address for the web UI. Use `0.0.0.0` only for intentional LAN/reverse-proxy access. |
|
||||
| `APP_PORT` | `7000` | Docker Compose host port for the web UI. |
|
||||
| `APP_DATA_DIR` | `./data` | Docker Compose host directory for application data volumes. |
|
||||
| `APP_LOGS_DIR` | `./logs` | Docker Compose host directory for application logs. |
|
||||
| `AUTH_ENABLED` | `true` | Enable/disable login |
|
||||
| `LOCALHOST_BYPASS` | `false` | Development-only auth bypass for loopback requests. Keep false for shared/network deployments. |
|
||||
| `ALLOWED_ORIGINS` | `http://localhost,http://127.0.0.1` | Comma-separated exact permitted origins for cross-origin browser/API clients. |
|
||||
| `SECURE_COOKIES` | `false` | Set true when serving Odysseus through HTTPS at a trusted proxy or private access gateway. |
|
||||
| `DATABASE_URL` | `sqlite:///./data/app.db` | Database connection string |
|
||||
| `CHROMADB_HOST` | `localhost` | ChromaDB host for vector memory. Docker overrides this to `chromadb`. |
|
||||
| `CHROMADB_PORT` | `8100` | ChromaDB port for manual host runs. Docker overrides this to `8000`. |
|
||||
| `EMBEDDING_URL` | -- | OpenAI-compatible embeddings endpoint |
|
||||
| `ODYSSEUS_CHAT_UPLOAD_MAX_BYTES` | `10485760` | Chat/agent attachment cap in bytes. Raise for larger local PDFs or text documents. |
|
||||
| `ODYSSEUS_GALLERY_UPLOAD_MAX_BYTES` | `104857600` | Gallery image upload cap in bytes (100 MB). |
|
||||
| `ODYSSEUS_GALLERY_TRANSFORM_UPLOAD_MAX_BYTES` | `26214400` | Gallery transform input cap in bytes (25 MB). |
|
||||
| `ODYSSEUS_MEMORY_IMPORT_MAX_BYTES` | `10485760` | Memory import file cap in bytes (10 MB). |
|
||||
| `ODYSSEUS_PERSONAL_UPLOAD_MAX_BYTES` | `26214400` | Personal document upload cap in bytes (25 MB). |
|
||||
| `ODYSSEUS_EMAIL_COMPOSE_UPLOAD_MAX_BYTES` | `26214400` | Email compose attachment cap in bytes (25 MB). |
|
||||
| `ODYSSEUS_STT_MAX_AUDIO_BYTES` | `26214400` | Speech-to-text audio cap in bytes (25 MB). |
|
||||
| `ODYSSEUS_ICS_MAX_BYTES` | `10485760` | Calendar `.ics` import cap in bytes (10 MB). |
|
||||
## Security
|
||||
|
||||
All upload-limit vars are validated (must be a positive integer) and optional; an invalid value fails fast at startup.
|
||||
|
||||
### Built-in MCP servers (optional setup)
|
||||
|
||||
Odysseus auto-registers a few built-in MCP servers at startup. The npx-based ones (currently the browser server, `@playwright/mcp`) only start when their npm package is already in the local npx cache. If a package isn't cached, that server is skipped with a startup log message explaining what to do, so a fresh install does not block on a multi-minute npm download or hang if Playwright system deps are missing.
|
||||
|
||||
To enable the browser MCP (page navigation, screenshots, vision), run once:
|
||||
|
||||
```bash
|
||||
npx -y @playwright/mcp@latest --version
|
||||
```
|
||||
|
||||
That installs `@playwright/mcp` plus Playwright (~300MB total). Restart Odysseus and the server will register at startup.
|
||||
|
||||
## Architecture
|
||||
```
|
||||
app.py # FastAPI entry point
|
||||
core/ auth, database, middleware, constants
|
||||
src/ llm_core, agent_loop, agent_tools, chat_processor, search/
|
||||
routes/ chat, session, document, memory, model … endpoints
|
||||
services/ docs, memory, search, hwfit (Cookbook) …
|
||||
static/ index.html + app.js + style.css + js/ (modular front-end)
|
||||
docs/ landing page (index.html) + preview clips
|
||||
```
|
||||
|
||||
## Data
|
||||
All user data lives in `data/` (gitignored): `app.db` (sessions, messages, documents),
|
||||
`memory.json`, `presets.json`, `uploads/`, `personal_docs/`, `chroma/`, `settings.json`.
|
||||
|
||||
To back up or restore everything in `data/`, see the
|
||||
[Backup & Restore guide](docs/backup-restore.md).
|
||||
Odysseus is a self-hosted workspace with powerful local tools. Keep auth enabled, keep private data out of Git, and do not expose raw model/service ports publicly. Deployment details are in the [setup guide](docs/setup.md#security-notes).
|
||||
|
||||
## Star History
|
||||
|
||||
@@ -483,19 +72,5 @@ To back up or restore everything in `data/`, see the
|
||||
</a>
|
||||
|
||||
## License
|
||||
AGPL-3.0-or-later -- see [LICENSE](LICENSE) and [ACKNOWLEDGMENTS.md](ACKNOWLEDGMENTS.md).
|
||||
|
||||
```
|
||||
|
|
||||
|||
|
||||
|||||
|
||||
| | | |||||||
|
||||
)_) )_) )_) ~|~
|
||||
)___))___))___)\ |
|
||||
)____)____)_____)\\|
|
||||
_____|____|____|_____\\\__
|
||||
\ /
|
||||
~^~^~~^~^~~^~^~~^~^~~^~^~~^~^~~^~^~~^~^~
|
||||
~^~ all aboard! ~^~
|
||||
~^~^~~^~^~~^~^~~^~^~~^~^~~^~^~~^~^~~^~^~
|
||||
```
|
||||
AGPL-3.0-or-later -- see [LICENSE](LICENSE) and [ACKNOWLEDGMENTS.md](ACKNOWLEDGMENTS.md).
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
# app.py — slim orchestrator
|
||||
import mimetypes
|
||||
import os
|
||||
import sys
|
||||
|
||||
|
||||
def register_static_mime_types() -> None:
|
||||
@@ -38,7 +39,7 @@ load_dotenv(encoding="utf-8-sig")
|
||||
import asyncio
|
||||
import logging
|
||||
import secrets
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from typing import Dict
|
||||
|
||||
from contextlib import asynccontextmanager
|
||||
@@ -113,12 +114,13 @@ app = FastAPI(
|
||||
)
|
||||
|
||||
# ========= CORS =========
|
||||
CORS_ALLOW_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"]
|
||||
allowed_origins = os.getenv("ALLOWED_ORIGINS", "http://localhost,http://127.0.0.1").split(",")
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=allowed_origins,
|
||||
allow_credentials=True,
|
||||
allow_methods=["GET", "POST", "PUT", "DELETE"],
|
||||
allow_methods=CORS_ALLOW_METHODS,
|
||||
allow_headers=[
|
||||
"Accept",
|
||||
"Authorization",
|
||||
@@ -316,7 +318,7 @@ if AUTH_ENABLED:
|
||||
# (no admin cookie available in that context). Restricted to
|
||||
# loopback clients + matching token to keep it locked down.
|
||||
try:
|
||||
from core.middleware import INTERNAL_TOOL_HEADER, INTERNAL_TOOL_TOKEN as _ITT
|
||||
from core.middleware import INTERNAL_TOOL_HEADER, INTERNAL_TOOL_TOKEN as _ITT, INTERNAL_TOOL_USER
|
||||
_hdr = request.headers.get(INTERNAL_TOOL_HEADER)
|
||||
if _hdr and secrets.compare_digest(_hdr, _ITT) and _is_trusted_loopback(request):
|
||||
# Impersonation: when the agent's loopback call sets
|
||||
@@ -328,11 +330,11 @@ if AUTH_ENABLED:
|
||||
if _impersonate and _impersonate in getattr(_auth_mgr, "users", {}):
|
||||
request.state.current_user = _impersonate
|
||||
else:
|
||||
request.state.current_user = "internal-tool"
|
||||
request.state.current_user = INTERNAL_TOOL_USER
|
||||
request.state.api_token = False
|
||||
return await call_next(request)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as _e:
|
||||
logger.warning("Internal tool auth header check failed", exc_info=_e)
|
||||
# Allow DIRECT localhost requests (internal service calls from
|
||||
# heartbeats etc.). Tunnel/proxy-forwarded requests are excluded by
|
||||
# _is_trusted_loopback so LOCALHOST_BYPASS can't be abused over a
|
||||
@@ -385,11 +387,10 @@ if AUTH_ENABLED:
|
||||
_db.close()
|
||||
try:
|
||||
await _asyncio.to_thread(_do)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as _e:
|
||||
logger.debug("Failed to update token last_used_at", exc_info=_e)
|
||||
_asyncio.create_task(_touch_last_used(matched_id))
|
||||
# Keep bearer-token callers out of normal cookie/user
|
||||
# routes. API-aware routes can read api_token_owner.
|
||||
request.state.current_user = "api"
|
||||
request.state.api_token = True
|
||||
request.state.api_token_id = matched_id
|
||||
@@ -438,7 +439,7 @@ class _RevalidatingStatic(StaticFiles):
|
||||
return resp
|
||||
|
||||
|
||||
app.mount("/static", _RevalidatingStatic(directory="static"), name="static")
|
||||
app.mount("/static", _RevalidatingStatic(directory=STATIC_DIR), name="static")
|
||||
|
||||
# ========= GENERATED IMAGES =========
|
||||
@app.get("/api/generated-image/{filename}")
|
||||
@@ -464,8 +465,8 @@ async def serve_generated_image(filename: str, request: Request):
|
||||
_db.close()
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as _e:
|
||||
logger.warning("Image ownership verification failed for %r", filename, exc_info=_e)
|
||||
ext = filename.rsplit('.', 1)[-1].lower()
|
||||
mime = {
|
||||
"png": "image/png", "jpg": "image/jpeg", "jpeg": "image/jpeg",
|
||||
@@ -528,6 +529,7 @@ memory_vector = components.get("memory_vector")
|
||||
upload_handler = components["upload_handler"]
|
||||
app.state.upload_handler = upload_handler
|
||||
personal_docs_mgr = components["personal_docs_manager"]
|
||||
app.state.personal_docs_manager = personal_docs_mgr
|
||||
api_key_manager = components["api_key_manager"]
|
||||
preset_manager = components["preset_manager"]
|
||||
chat_processor = components["chat_processor"]
|
||||
@@ -861,7 +863,7 @@ async def get_version():
|
||||
|
||||
@app.get("/api/health")
|
||||
async def health_check() -> Dict[str, str]:
|
||||
return {"status": "healthy", "timestamp": datetime.utcnow().isoformat()}
|
||||
return {"status": "healthy", "timestamp": datetime.now(timezone.utc).isoformat()}
|
||||
|
||||
@app.get("/api/ready")
|
||||
async def readiness_check() -> JSONResponse:
|
||||
@@ -1171,3 +1173,12 @@ async def _shutdown_event():
|
||||
except Exception as e:
|
||||
logger.warning(f"MCP shutdown error: {e}")
|
||||
logger.info("Application shutdown complete")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
|
||||
bind_host = os.getenv("APP_BIND", "127.0.0.1")
|
||||
bind_port = int(os.getenv("APP_PORT", "7000"))
|
||||
|
||||
uvicorn.run(app, host=bind_host, port=bind_port, log_level="info")
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
#Requires -Version 5.1
|
||||
<#
|
||||
Build a portable Windows distribution for Odysseus.
|
||||
|
||||
Output layout:
|
||||
dist\Odysseus\Odysseus.exe
|
||||
dist\Odysseus\static\...
|
||||
dist\Odysseus\scripts\...
|
||||
dist\Odysseus\mcp_servers\...
|
||||
dist\Odysseus\services\hwfit\data\...
|
||||
|
||||
The app then keeps using its normal filesystem layout when frozen.
|
||||
|
||||
Usage:
|
||||
powershell -ExecutionPolicy Bypass -File .\build-windows-portable.ps1
|
||||
#>
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
Set-Location -Path $PSScriptRoot
|
||||
|
||||
function Write-Step($msg) { Write-Host ""; Write-Host ("==> " + $msg) -ForegroundColor Cyan }
|
||||
function Fail($msg) {
|
||||
Write-Host ""
|
||||
Write-Host ("ERROR: " + $msg) -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
|
||||
Write-Step "Checking for Python"
|
||||
$pyExe = $null
|
||||
if (Test-Path ".\.venv\Scripts\python.exe") {
|
||||
$pyExe = (Resolve-Path ".\.venv\Scripts\python.exe").Path
|
||||
} else {
|
||||
foreach ($c in @("py", "python")) {
|
||||
$cmd = Get-Command $c -ErrorAction SilentlyContinue
|
||||
if ($cmd) { $pyExe = $cmd.Source; break }
|
||||
}
|
||||
if ($pyExe -like "*WindowsApps*python.exe") {
|
||||
$pyCmd = Get-Command py -ErrorAction SilentlyContinue
|
||||
if ($pyCmd) {
|
||||
$pyExe = $pyCmd.Source
|
||||
}
|
||||
}
|
||||
}
|
||||
if (-not $pyExe) {
|
||||
Fail "Python not found on PATH. Install Python 3.11+ first."
|
||||
}
|
||||
Write-Host ("Using Python: " + $pyExe)
|
||||
|
||||
Write-Step "Installing build dependencies"
|
||||
& $pyExe -m pip install --upgrade pip --quiet
|
||||
& $pyExe -m pip install -r requirements.txt pyinstaller pystray Pillow
|
||||
if ($LASTEXITCODE -ne 0) { Fail "Dependency install failed." }
|
||||
|
||||
Write-Step "Building portable exe bundle"
|
||||
Remove-Item -Recurse -Force build, dist -ErrorAction SilentlyContinue
|
||||
|
||||
$dataArgs = @(
|
||||
"--add-data", "static;static",
|
||||
"--add-data", "scripts;scripts",
|
||||
"--add-data", "mcp_servers;mcp_servers",
|
||||
"--add-data", "services/hwfit/data;services/hwfit/data",
|
||||
"--add-data", "config;config",
|
||||
"--add-data", ".env.example;.env.example"
|
||||
)
|
||||
|
||||
& $pyExe -m PyInstaller --noconfirm --clean --onedir --noconsole --icon=static/icon.ico --name Odysseus @dataArgs launcher.py
|
||||
if ($LASTEXITCODE -ne 0) { Fail "PyInstaller build failed." }
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "Build complete." -ForegroundColor Green
|
||||
Write-Host "Portable app folder: $PSScriptRoot\dist\Odysseus" -ForegroundColor Green
|
||||
Write-Host "Distribute the whole folder (or zip it) so static assets and scripts stay with the exe." -ForegroundColor Green
|
||||
@@ -5,8 +5,9 @@ offers and pair to it, without duplicating any LLM logic.
|
||||
|
||||
Auth is enforced globally by AuthMiddleware (app.py), so reaching a handler here
|
||||
means the caller is authenticated by either a cookie session or a Bearer `ody_`
|
||||
API token. The read endpoints (ping/info/models) accept either; the pairing
|
||||
endpoints are admin-cookie only.
|
||||
API token. Ping/info accept either credential type, models requires a chat-
|
||||
scoped API token for bearer callers, and the pairing endpoints are admin-cookie
|
||||
only.
|
||||
|
||||
Pairing CSRF posture: minting happens ONLY on POST. The session cookie is
|
||||
SameSite=Lax (routes/auth_routes.py), which a browser does not send on a
|
||||
@@ -18,7 +19,7 @@ on a GET would be unsafe (Lax cookies ride top-level GET navigations), so GET
|
||||
|
||||
import html
|
||||
|
||||
from fastapi import APIRouter, Request
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from fastapi.responses import HTMLResponse
|
||||
|
||||
from core.middleware import require_admin
|
||||
@@ -52,6 +53,18 @@ def owner_can_see(row_owner, owner) -> bool:
|
||||
return row_owner is None or row_owner == owner
|
||||
|
||||
|
||||
def require_models_scope(request: Request) -> None:
|
||||
"""Require the companion chat scope for bearer-token model inventory."""
|
||||
if not getattr(request.state, "api_token", False):
|
||||
return
|
||||
scopes = getattr(request.state, "api_token_scopes", None) or []
|
||||
if isinstance(scopes, str):
|
||||
scopes = [scope.strip() for scope in scopes.split(",")]
|
||||
scope_set = {str(scope).strip() for scope in scopes if str(scope).strip()}
|
||||
if _pairing.COMPANION_SCOPE not in scope_set:
|
||||
raise HTTPException(403, "API token requires chat scope")
|
||||
|
||||
|
||||
def mint_pairing_token(owner: str, invalidate=None) -> tuple[str, str]:
|
||||
"""Mint a pairing token AND invalidate the auth middleware's in-memory token
|
||||
cache, so the new token is accepted on the very next request without a server
|
||||
@@ -103,6 +116,7 @@ def setup_companion_routes() -> APIRouter:
|
||||
rows -- the same rule as owner_filter. Read-only; never returns api_key
|
||||
material.
|
||||
"""
|
||||
require_models_scope(request)
|
||||
import json as _json
|
||||
|
||||
from core.database import SessionLocal, ModelEndpoint
|
||||
|
||||
@@ -20,6 +20,7 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
from core.atomic_io import atomic_write_json as _atomic_write_json # noqa: E402
|
||||
from core.middleware import INTERNAL_TOOL_USER # noqa: E402
|
||||
|
||||
DEFAULT_PRIVILEGES = {
|
||||
"can_use_agent": True,
|
||||
@@ -47,7 +48,7 @@ ADMIN_PRIVILEGES["allowed_models_restricted"] = False
|
||||
# backwards for this sentinel.
|
||||
ADMIN_PRIVILEGES["block_all_models"] = False
|
||||
|
||||
from src.constants import AUTH_FILE
|
||||
from src.constants import AUTH_FILE, PASSWORD_MIN_LENGTH
|
||||
DEFAULT_AUTH_PATH = AUTH_FILE
|
||||
TOKEN_TTL = 60 * 60 * 24 * 7 # 7 days
|
||||
|
||||
@@ -65,7 +66,7 @@ TOKEN_TTL = 60 * 60 * 24 * 7 # 7 days
|
||||
# of those names would be denied an assistant and inconsistently owner-scoped.
|
||||
# Refuse to create or rename into any of them so the sentinels can't be
|
||||
# impersonated. (Keep this in sync with that synthetic-owner set.)
|
||||
RESERVED_USERNAMES = frozenset({"internal-tool", "api", "demo", "system"})
|
||||
RESERVED_USERNAMES = frozenset({INTERNAL_TOOL_USER, "api", "demo", "system"})
|
||||
|
||||
|
||||
def normalize_known_username(users: Dict[str, Any], username: str | None) -> Optional[str]:
|
||||
@@ -243,6 +244,15 @@ class AuthManager:
|
||||
def is_configured(self) -> bool:
|
||||
return len(self.users) > 0
|
||||
|
||||
def policy(self) -> dict:
|
||||
"""Return public auth policy constants for the frontend."""
|
||||
return {
|
||||
"password_min_length": PASSWORD_MIN_LENGTH,
|
||||
"reserved_usernames": sorted(RESERVED_USERNAMES),
|
||||
"signup_enabled": self.signup_enabled,
|
||||
"session_days": TOKEN_TTL // 86400,
|
||||
}
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Account management
|
||||
# ------------------------------------------------------------------
|
||||
@@ -573,16 +583,20 @@ class AuthManager:
|
||||
return None
|
||||
return self.create_session_trusted(username)
|
||||
|
||||
def create_session_trusted(self, username: str) -> str:
|
||||
def create_session_trusted(self, username: str) -> Optional[str]:
|
||||
"""Issue a session token for an already-verified user.
|
||||
Call only after verify_password (and TOTP if enabled) have passed."""
|
||||
username = username.strip().lower()
|
||||
token = secrets.token_hex(32)
|
||||
with self._sessions_lock:
|
||||
self._sessions[token] = {
|
||||
"username": username,
|
||||
"expiry": time.time() + TOKEN_TTL,
|
||||
}
|
||||
with self._config_lock:
|
||||
if username not in self.users:
|
||||
logger.warning("Refused to issue session for missing user '%s'", username)
|
||||
return None
|
||||
with self._sessions_lock:
|
||||
self._sessions[token] = {
|
||||
"username": username,
|
||||
"expiry": time.time() + TOKEN_TTL,
|
||||
}
|
||||
self._save_sessions()
|
||||
return token
|
||||
|
||||
|
||||
@@ -2,12 +2,15 @@ import os
|
||||
import logging
|
||||
import sqlite3
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from sqlalchemy import event, create_engine, Column, String, Text, Boolean, DateTime, Integer, ForeignKey, JSON, Index, func, text
|
||||
from sqlalchemy.engine import Engine
|
||||
from sqlalchemy.types import TypeDecorator
|
||||
from sqlalchemy.ext.declarative import declarative_base, declared_attr
|
||||
from sqlalchemy.orm import relationship, sessionmaker, backref
|
||||
|
||||
from src.runtime_paths import get_app_root
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Create base class for declarative models
|
||||
@@ -29,9 +32,26 @@ class TimestampMixin:
|
||||
def updated_at(cls):
|
||||
return Column(DateTime, default=utcnow_naive, onupdate=utcnow_naive, nullable=False)
|
||||
|
||||
# Get database URL from environment, default to SQLite in DATA_DIR
|
||||
# Ensure the writable data directory exists before SQLite connects.
|
||||
from src.constants import DATA_DIR, AUTH_FILE, MEMORY_FILE, USER_PREFS_FILE, SETTINGS_FILE
|
||||
DATABASE_URL = os.getenv("DATABASE_URL", f"sqlite:///{DATA_DIR}/app.db")
|
||||
Path(DATA_DIR).mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
||||
def _default_database_url() -> str:
|
||||
return f"sqlite:///{Path(DATA_DIR) / 'app.db'}"
|
||||
|
||||
|
||||
def _normalize_sqlite_url(url: str) -> str:
|
||||
if not url.startswith("sqlite:///"):
|
||||
return url
|
||||
db_path = url.replace("sqlite:///", "", 1)
|
||||
if db_path == ":memory:" or os.path.isabs(db_path):
|
||||
return url
|
||||
return f"sqlite:///{(Path(get_app_root()) / db_path).resolve().as_posix()}"
|
||||
|
||||
|
||||
# Get database URL from environment, default to SQLite in DATA_DIR
|
||||
DATABASE_URL = _normalize_sqlite_url(os.getenv("DATABASE_URL", _default_database_url()))
|
||||
|
||||
# Create engine
|
||||
engine = create_engine(
|
||||
@@ -324,6 +344,13 @@ class EmailAccount(TimestampMixin, Base):
|
||||
smtp_password = Column(String, default="")
|
||||
|
||||
from_address = Column(String, default="")
|
||||
display_name = Column(String, nullable=True) # "Hriday Ranka" — used in From: header
|
||||
|
||||
# OAuth2 (Google / Google Workspace). Tokens stored encrypted via secret_storage.
|
||||
oauth_provider = Column(String, nullable=True) # "google" or None
|
||||
oauth_access_token = Column(String, nullable=True) # encrypted
|
||||
oauth_refresh_token = Column(String, nullable=True) # encrypted
|
||||
oauth_token_expiry = Column(String, nullable=True) # unix timestamp string
|
||||
|
||||
__table_args__ = (
|
||||
Index('ix_email_accounts_owner_default', 'owner', 'is_default'),
|
||||
@@ -1427,6 +1454,25 @@ def _migrate_add_task_automation_columns():
|
||||
except Exception as e:
|
||||
logging.getLogger(__name__).warning(f"task automation migration: {e}")
|
||||
|
||||
def _migrate_add_email_oauth_columns():
|
||||
"""Add Google OAuth and display_name columns to email_accounts if missing."""
|
||||
try:
|
||||
with engine.connect() as conn:
|
||||
cols = [r[1] for r in conn.execute(text("PRAGMA table_info(email_accounts)"))]
|
||||
for col, typedef in [
|
||||
("oauth_provider", "TEXT"),
|
||||
("oauth_access_token", "TEXT"),
|
||||
("oauth_refresh_token", "TEXT"),
|
||||
("oauth_token_expiry", "TEXT"),
|
||||
("display_name", "TEXT"),
|
||||
]:
|
||||
if col not in cols:
|
||||
conn.execute(text(f"ALTER TABLE email_accounts ADD COLUMN {col} {typedef}"))
|
||||
conn.commit()
|
||||
except Exception as e:
|
||||
logging.getLogger(__name__).warning(f"email oauth columns migration: {e}")
|
||||
|
||||
|
||||
def _migrate_add_oauth_config():
|
||||
"""Add oauth_config column to mcp_servers table if missing."""
|
||||
try:
|
||||
@@ -1771,6 +1817,7 @@ def init_db():
|
||||
_migrate_add_tidy_verdict()
|
||||
_migrate_add_doc_source_email_cols()
|
||||
_migrate_add_oauth_config()
|
||||
_migrate_add_email_oauth_columns()
|
||||
_migrate_add_task_automation_columns()
|
||||
_migrate_add_disabled_tools()
|
||||
_migrate_add_mcp_oauth_tokens_column()
|
||||
|
||||
@@ -15,6 +15,8 @@ from starlette.responses import Response
|
||||
# same value from this module. Never persisted or exposed externally.
|
||||
INTERNAL_TOOL_TOKEN = os.environ.get("ODYSSEUS_INTERNAL_TOKEN") or secrets.token_hex(32)
|
||||
INTERNAL_TOOL_HEADER = "X-Odysseus-Internal-Token"
|
||||
# Pseudo-username on in-process tool-loopback requests; require_admin trusts it and it is reserved.
|
||||
INTERNAL_TOOL_USER = "internal-tool"
|
||||
|
||||
|
||||
def is_cors_preflight(method: str, headers) -> bool:
|
||||
@@ -39,7 +41,7 @@ def require_admin(request: Request):
|
||||
hdr = request.headers.get(INTERNAL_TOOL_HEADER)
|
||||
if hdr and secrets.compare_digest(hdr, INTERNAL_TOOL_TOKEN):
|
||||
return
|
||||
if getattr(request.state, "current_user", None) == "internal-tool":
|
||||
if getattr(request.state, "current_user", None) == INTERNAL_TOOL_USER:
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
@@ -65,10 +67,9 @@ class SecurityHeadersMiddleware(BaseHTTPMiddleware):
|
||||
response = await call_next(request)
|
||||
path = request.url.path
|
||||
|
||||
# Tool render endpoints are served inside iframes — allow framing by self
|
||||
# Tool render endpoints
|
||||
is_tool_render = path.startswith("/api/tools/") and path.endswith("/render")
|
||||
# PDF previews are embedded by the in-app document library. Keep the
|
||||
# exception route-scoped so normal app pages remain unframeable.
|
||||
# Document library PDF preview endpoint
|
||||
is_document_pdf_preview = path.startswith("/api/document/") and path.endswith("/render-pdf")
|
||||
# Visual report pages are self-contained HTML — need inline scripts + external images
|
||||
is_report = path.startswith("/api/research/report/")
|
||||
@@ -95,9 +96,7 @@ class SecurityHeadersMiddleware(BaseHTTPMiddleware):
|
||||
"frame-ancestors 'none'"
|
||||
)
|
||||
elif is_tool_render:
|
||||
# Tool iframe content: skip all framing headers — the iframe's
|
||||
# sandbox="allow-scripts" attribute provides isolation.
|
||||
# Don't overwrite the route's own restrictive CSP either.
|
||||
# Skip framing headers for tools.
|
||||
pass
|
||||
elif is_document_pdf_preview:
|
||||
response.headers["X-Frame-Options"] = "SAMEORIGIN"
|
||||
|
||||
@@ -60,6 +60,13 @@ services:
|
||||
- ODYSSEUS_INPROCESS_TASKS=${ODYSSEUS_INPROCESS_TASKS:-1}
|
||||
- ODYSSEUS_SCRIPT_HOST=${ODYSSEUS_SCRIPT_HOST:-localhost}
|
||||
- ODYSSEUS_CHAT_UPLOAD_MAX_BYTES=${ODYSSEUS_CHAT_UPLOAD_MAX_BYTES:-10485760}
|
||||
- ODYSSEUS_GALLERY_UPLOAD_MAX_BYTES=${ODYSSEUS_GALLERY_UPLOAD_MAX_BYTES:-104857600}
|
||||
- ODYSSEUS_GALLERY_TRANSFORM_UPLOAD_MAX_BYTES=${ODYSSEUS_GALLERY_TRANSFORM_UPLOAD_MAX_BYTES:-26214400}
|
||||
- ODYSSEUS_MEMORY_IMPORT_MAX_BYTES=${ODYSSEUS_MEMORY_IMPORT_MAX_BYTES:-10485760}
|
||||
- ODYSSEUS_PERSONAL_UPLOAD_MAX_BYTES=${ODYSSEUS_PERSONAL_UPLOAD_MAX_BYTES:-26214400}
|
||||
- ODYSSEUS_EMAIL_COMPOSE_UPLOAD_MAX_BYTES=${ODYSSEUS_EMAIL_COMPOSE_UPLOAD_MAX_BYTES:-26214400}
|
||||
- ODYSSEUS_STT_MAX_AUDIO_BYTES=${ODYSSEUS_STT_MAX_AUDIO_BYTES:-26214400}
|
||||
- ODYSSEUS_ICS_MAX_BYTES=${ODYSSEUS_ICS_MAX_BYTES:-10485760}
|
||||
- DATA_BRAVE_API_KEY=${DATA_BRAVE_API_KEY:-}
|
||||
- GOOGLE_API_KEY=${GOOGLE_API_KEY:-}
|
||||
- GOOGLE_PSE_CX=${GOOGLE_PSE_CX:-}
|
||||
|
||||
@@ -59,6 +59,13 @@ services:
|
||||
- ODYSSEUS_INPROCESS_TASKS=${ODYSSEUS_INPROCESS_TASKS:-1}
|
||||
- ODYSSEUS_SCRIPT_HOST=${ODYSSEUS_SCRIPT_HOST:-localhost}
|
||||
- ODYSSEUS_CHAT_UPLOAD_MAX_BYTES=${ODYSSEUS_CHAT_UPLOAD_MAX_BYTES:-10485760}
|
||||
- ODYSSEUS_GALLERY_UPLOAD_MAX_BYTES=${ODYSSEUS_GALLERY_UPLOAD_MAX_BYTES:-104857600}
|
||||
- ODYSSEUS_GALLERY_TRANSFORM_UPLOAD_MAX_BYTES=${ODYSSEUS_GALLERY_TRANSFORM_UPLOAD_MAX_BYTES:-26214400}
|
||||
- ODYSSEUS_MEMORY_IMPORT_MAX_BYTES=${ODYSSEUS_MEMORY_IMPORT_MAX_BYTES:-10485760}
|
||||
- ODYSSEUS_PERSONAL_UPLOAD_MAX_BYTES=${ODYSSEUS_PERSONAL_UPLOAD_MAX_BYTES:-26214400}
|
||||
- ODYSSEUS_EMAIL_COMPOSE_UPLOAD_MAX_BYTES=${ODYSSEUS_EMAIL_COMPOSE_UPLOAD_MAX_BYTES:-26214400}
|
||||
- ODYSSEUS_STT_MAX_AUDIO_BYTES=${ODYSSEUS_STT_MAX_AUDIO_BYTES:-26214400}
|
||||
- ODYSSEUS_ICS_MAX_BYTES=${ODYSSEUS_ICS_MAX_BYTES:-10485760}
|
||||
- DATA_BRAVE_API_KEY=${DATA_BRAVE_API_KEY:-}
|
||||
- GOOGLE_API_KEY=${GOOGLE_API_KEY:-}
|
||||
- GOOGLE_PSE_CX=${GOOGLE_PSE_CX:-}
|
||||
|
||||
@@ -48,6 +48,13 @@ services:
|
||||
- ODYSSEUS_INPROCESS_TASKS=${ODYSSEUS_INPROCESS_TASKS:-1}
|
||||
- ODYSSEUS_SCRIPT_HOST=${ODYSSEUS_SCRIPT_HOST:-localhost}
|
||||
- ODYSSEUS_CHAT_UPLOAD_MAX_BYTES=${ODYSSEUS_CHAT_UPLOAD_MAX_BYTES:-10485760}
|
||||
- ODYSSEUS_GALLERY_UPLOAD_MAX_BYTES=${ODYSSEUS_GALLERY_UPLOAD_MAX_BYTES:-104857600}
|
||||
- ODYSSEUS_GALLERY_TRANSFORM_UPLOAD_MAX_BYTES=${ODYSSEUS_GALLERY_TRANSFORM_UPLOAD_MAX_BYTES:-26214400}
|
||||
- ODYSSEUS_MEMORY_IMPORT_MAX_BYTES=${ODYSSEUS_MEMORY_IMPORT_MAX_BYTES:-10485760}
|
||||
- ODYSSEUS_PERSONAL_UPLOAD_MAX_BYTES=${ODYSSEUS_PERSONAL_UPLOAD_MAX_BYTES:-26214400}
|
||||
- ODYSSEUS_EMAIL_COMPOSE_UPLOAD_MAX_BYTES=${ODYSSEUS_EMAIL_COMPOSE_UPLOAD_MAX_BYTES:-26214400}
|
||||
- ODYSSEUS_STT_MAX_AUDIO_BYTES=${ODYSSEUS_STT_MAX_AUDIO_BYTES:-26214400}
|
||||
- ODYSSEUS_ICS_MAX_BYTES=${ODYSSEUS_ICS_MAX_BYTES:-10485760}
|
||||
- DATA_BRAVE_API_KEY=${DATA_BRAVE_API_KEY:-}
|
||||
- GOOGLE_API_KEY=${GOOGLE_API_KEY:-}
|
||||
- GOOGLE_PSE_CX=${GOOGLE_PSE_CX:-}
|
||||
|
||||
@@ -13,6 +13,8 @@ set -e
|
||||
|
||||
PUID="${PUID:-1000}"
|
||||
PGID="${PGID:-1000}"
|
||||
GOSU_BIN="$(command -v gosu)"
|
||||
PYTHON_BIN="$(command -v python)"
|
||||
|
||||
# Reuse an existing matching group/user if the host's UID/GID already
|
||||
# corresponds to one in /etc/passwd (e.g. when the image is rebuilt
|
||||
@@ -24,26 +26,57 @@ if ! getent passwd "$PUID" >/dev/null 2>&1; then
|
||||
useradd -u "$PUID" -g "$PGID" -M -s /bin/sh -d /app odysseus
|
||||
fi
|
||||
|
||||
# Repair ownership on every writable path the app touches at runtime.
|
||||
#
|
||||
# Bind-mounted dirs (/app/data, /app/logs) are the obvious ones, but
|
||||
# the app ALSO writes inside the image's own source tree at runtime:
|
||||
# - services/cache/{search,content}/* (search cache LRU)
|
||||
# - services/search_analytics.json
|
||||
# - services/search_engine_error.log
|
||||
# - services/tts cache, etc.
|
||||
# These dirs were created as root during `docker build`, so dropping
|
||||
# to PUID:PGID would otherwise crash on the first import that tries
|
||||
# to mkdir them. Chown the whole /app tree — fast (<1s on this size)
|
||||
# and idempotent via the `-not -uid` filter so we only touch files
|
||||
# that need fixing.
|
||||
for dir in /app /app/data /app/logs; do
|
||||
mount_root_for() {
|
||||
awk -v target="$1" '$5 == target { print $4; exit }' /proc/self/mountinfo 2>/dev/null || true
|
||||
}
|
||||
|
||||
is_broad_mount_root() {
|
||||
case "$1" in
|
||||
/|/home|/srv|/var|/usr|/opt|/tmp|/mnt|/media)
|
||||
return 0
|
||||
;;
|
||||
esac
|
||||
return 1
|
||||
}
|
||||
|
||||
repair_tree_ownership() {
|
||||
dir="$1"
|
||||
if [ -d "$dir" ]; then
|
||||
# `find ... -not -uid` keeps this O(touched-files), not
|
||||
# O(everything), so terabyte-sized maildirs don't slow startup.
|
||||
find "$dir" -not -uid "$PUID" -print0 2>/dev/null \
|
||||
find "$dir" -xdev -not -uid "$PUID" -print0 2>/dev/null \
|
||||
| xargs -0 -r chown "$PUID:$PGID" 2>/dev/null || true
|
||||
fi
|
||||
}
|
||||
|
||||
repair_app_tree_ownership() {
|
||||
if [ -d /app ]; then
|
||||
find /app -xdev \
|
||||
\( -path /app/data -o -path /app/logs -o -path /app/.ssh -o -path /app/.cache -o -path /app/.local \) -prune \
|
||||
-o -not -uid "$PUID" -print0 2>/dev/null \
|
||||
| xargs -0 -r chown "$PUID:$PGID" 2>/dev/null || true
|
||||
fi
|
||||
}
|
||||
|
||||
repair_bind_mount_ownership() {
|
||||
dir="$1"
|
||||
if [ ! -d "$dir" ]; then
|
||||
return
|
||||
fi
|
||||
|
||||
mount_root="$(mount_root_for "$dir")"
|
||||
if is_broad_mount_root "$mount_root"; then
|
||||
echo "Skipping recursive ownership repair for $dir because it maps to broad host path $mount_root" >&2
|
||||
chown "$PUID:$PGID" "$dir" 2>/dev/null || true
|
||||
return
|
||||
fi
|
||||
|
||||
repair_tree_ownership "$dir"
|
||||
}
|
||||
|
||||
# Repair image-owned writable paths without walking into bind-mounted host
|
||||
# trees, then repair the app-owned mount roots separately.
|
||||
repair_app_tree_ownership
|
||||
for dir in /app/data /app/logs /app/.ssh /app/.cache/huggingface /app/.local; do
|
||||
repair_bind_mount_ownership "$dir"
|
||||
done
|
||||
|
||||
# Cookbook installs vllm/etc. via `pip install --user`, which pulls
|
||||
@@ -83,9 +116,9 @@ export PATH="/app/.local/bin:$PATH"
|
||||
# Run first-time setup as the app user so data/ files get the right ownership.
|
||||
# setup.py is idempotent — skips auth.json / .env if they already exist.
|
||||
# || true so a setup failure never prevents the container from starting.
|
||||
gosu "$PUID:$PGID" python /app/setup.py || true
|
||||
"$GOSU_BIN" "$PUID:$PGID" "$PYTHON_BIN" /app/setup.py || true
|
||||
|
||||
# Drop root and run the actual app. `gosu` is preferred over `su` /
|
||||
# `sudo` because it cleans up the process tree (no extra shell layer)
|
||||
# so signals (SIGTERM from `docker stop`) reach uvicorn directly.
|
||||
exec gosu "$PUID:$PGID" "$@"
|
||||
exec "$GOSU_BIN" "$PUID:$PGID" "$@"
|
||||
|
||||
|
Before Width: | Height: | Size: 3.0 MiB |
|
Before Width: | Height: | Size: 3.4 MiB |
|
Before Width: | Height: | Size: 1.1 MiB |
|
Before Width: | Height: | Size: 1003 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
Before Width: | Height: | Size: 45 KiB After Width: | Height: | Size: 52 KiB |
|
Before Width: | Height: | Size: 2.5 MiB |
@@ -1,14 +1,16 @@
|
||||
# Security CI guide
|
||||
|
||||
This project runs a set of automated security checks on every pull request and
|
||||
on every push to `main`. This page explains what each one does, whether it can
|
||||
This project runs a set of automated security checks on pull requests and
|
||||
selected branch pushes. This page explains what each one does, whether it can
|
||||
block a merge, and the few one-time settings you should turn on to get the full
|
||||
benefit.
|
||||
|
||||
## What runs, and why
|
||||
|
||||
Each check lives in its own file under `.github/workflows/`. They run
|
||||
automatically; you do not start them.
|
||||
Most checks live in files under `.github/workflows/`. CodeQL is configured
|
||||
through GitHub's code scanning default setup, so it appears as a dynamic GitHub
|
||||
workflow instead of a checked-in workflow file. They run automatically; you do
|
||||
not start them.
|
||||
|
||||
| Check | What it protects against | Blocks a merge? |
|
||||
|---|---|---|
|
||||
@@ -88,11 +90,14 @@ let the workflows run on one pull request first, then add them here.
|
||||
2. Turn on **Dependency graph** (usually on by default for public repos) -- this
|
||||
powers Dependency review and Dependabot.
|
||||
3. Turn on **Dependabot alerts** and **Dependabot security updates**.
|
||||
4. Under **Code scanning**, you have two ways to scan the app code with CodeQL:
|
||||
- The included `codeql.yml` workflow already scans `main` and runs weekly.
|
||||
- To also scan **pull requests** (recommended, since most contributions come
|
||||
from forks), click **Set up -> Default** under Code scanning. GitHub then
|
||||
runs CodeQL on pull requests for you, with no token limitations.
|
||||
4. Under **Code scanning**, use **Set up -> Default** for CodeQL. GitHub then
|
||||
runs CodeQL as a dynamic workflow without the fork-token limitations that
|
||||
affect checked-in advanced workflows.
|
||||
|
||||
Do not also add a checked-in CodeQL workflow while default setup is enabled:
|
||||
GitHub rejects advanced CodeQL uploads when default setup is active. If the
|
||||
project later needs an advanced CodeQL workflow, disable default setup first
|
||||
and keep only one CodeQL publishing path active.
|
||||
|
||||
## Keeping it current
|
||||
|
||||
|
||||
@@ -0,0 +1,425 @@
|
||||
# Odysseus Setup Guide
|
||||
|
||||
This page keeps the detailed install, deployment, troubleshooting, and configuration notes out of the front README.
|
||||
|
||||
## Quick Start
|
||||
|
||||
> **Branch note:** `dev` is the default branch and contains the latest development changes, but it may be unstable. For the more stable curated branch, use [`main`](https://github.com/pewdiepie-archdaemon/odysseus/tree/main).
|
||||
|
||||
Defaults work out of the box: clone, run, then configure models/search/email
|
||||
inside **Settings**. Only edit `.env` for deployment-level overrides like
|
||||
`APP_BIND`, `APP_PORT`, `AUTH_ENABLED`, `DATABASE_URL`, or a pre-seeded admin password.
|
||||
|
||||
On first setup, Odysseus creates an admin account (`admin` unless
|
||||
`ODYSSEUS_ADMIN_USER` is set) and prints a temporary password in the terminal.
|
||||
For Docker installs, the same line is in `docker compose logs odysseus`.
|
||||
Use that for the first login, then change it in **Settings**.
|
||||
|
||||
Contributing? See [CONTRIBUTING.md](CONTRIBUTING.md) for setup, testing, and
|
||||
pull request guidelines.
|
||||
|
||||
### Docker (recommended)
|
||||
```bash
|
||||
git clone https://github.com/pewdiepie-archdaemon/odysseus.git
|
||||
cd odysseus
|
||||
cp .env.example .env # optional, but recommended for explicit defaults
|
||||
docker compose up -d --build
|
||||
```
|
||||
To include optional extras in the image (PDF viewer, Office extraction; includes AGPL PyMuPDF), build with `docker compose build --build-arg INSTALL_OPTIONAL=true` before `up`.
|
||||
|
||||
Open `http://localhost:7000` when the containers are healthy. Docker Compose
|
||||
binds the web UI to `127.0.0.1` by default. If the port is taken, set
|
||||
`APP_PORT=7001` in `.env` and recreate the container. Set `APP_BIND=0.0.0.0`
|
||||
only when you intentionally want LAN/reverse-proxy access.
|
||||
|
||||
> **On Apple Silicon (M-series) Macs:** Docker can't reach the Metal GPU, so
|
||||
> Cookbook serves local models on CPU only. For GPU-accelerated model serving,
|
||||
> run natively instead — see [Apple Silicon](#apple-silicon) below.
|
||||
|
||||
### Native Linux / macOS
|
||||
```bash
|
||||
git clone https://github.com/pewdiepie-archdaemon/odysseus.git
|
||||
cd odysseus
|
||||
python3 -m venv venv
|
||||
source venv/bin/activate
|
||||
pip install -r requirements.txt
|
||||
python setup.py
|
||||
python -m uvicorn app:app --host 127.0.0.1 --port 7000
|
||||
```
|
||||
Requirements: Python 3.11+. Cookbook also needs `tmux` for background model
|
||||
downloads and serves. The app itself is lightweight; local model serving is the
|
||||
heavy part and depends on the model, runtime, GPU, and VRAM, so small hosts can
|
||||
connect to API or remote model servers instead. Use `--host 0.0.0.0` only when you intentionally want LAN/reverse-proxy access.
|
||||
|
||||
### Apple Silicon
|
||||
Docker on macOS cannot use the Metal GPU. For GPU-accelerated Cookbook on an
|
||||
M-series Mac, run Odysseus natively:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/pewdiepie-archdaemon/odysseus.git
|
||||
cd odysseus
|
||||
./start-macos.sh
|
||||
```
|
||||
|
||||
It launches at `http://127.0.0.1:7860`. To expose it to your phone over a trusted LAN/VPN such as Tailscale, bind all interfaces:
|
||||
|
||||
```bash
|
||||
ODYSSEUS_HOST=0.0.0.0 ./start-macos.sh
|
||||
# then open http://<tailscale-ip>:7860
|
||||
```
|
||||
|
||||
The script also reads `.env` at startup, so `APP_BIND=0.0.0.0` and `APP_PORT`
|
||||
set there are picked up automatically without a command-line override each run.
|
||||
|
||||
Keep `AUTH_ENABLED=true` (the default) before binding outside loopback. Do not
|
||||
expose this port directly to the public internet. To build a clickable app wrapper:
|
||||
|
||||
```bash
|
||||
./build-macos-app.sh
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Cookbook, GPU, Ollama, and troubleshooting notes</summary>
|
||||
|
||||
**Docker bundled services.** Compose starts Odysseus, ChromaDB, SearXNG, and
|
||||
ntfy. Odysseus and the bundled service ports bind to `127.0.0.1` by default, so
|
||||
they are reachable from the host but not exposed to your LAN/public internet
|
||||
unless you opt in.
|
||||
|
||||
**Cookbook storage in Docker.** Downloads live in `./data/huggingface`
|
||||
(`~/.cache/huggingface` in the container). Cookbook-installed Python CLIs and
|
||||
serve engines live in `./data/local` (`~/.local` in the container), so they
|
||||
survive container recreation.
|
||||
|
||||
**Remote servers.** In **Cookbook -> Settings -> Servers**, generate the
|
||||
Odysseus SSH key and add the public key to the remote server's
|
||||
`~/.ssh/authorized_keys`. From the host you can also run:
|
||||
|
||||
```bash
|
||||
ssh-copy-id -i data/ssh/id_ed25519.pub user@server
|
||||
```
|
||||
|
||||
**Docker GPU overlays.** CPU-only users can skip this section. Cookbook can
|
||||
only detect GPUs that Docker exposes to the container — if the host runtime or
|
||||
device passthrough is not configured, Cookbook sees the iGPU, another card, or
|
||||
CPU instead of your intended GPU.
|
||||
|
||||
For NVIDIA, `scripts/check-docker-gpu.sh` diagnoses GPU passthrough and can
|
||||
optionally install the host runtime or update `.env`.
|
||||
|
||||
```bash
|
||||
# Read-only diagnostic (default — installs nothing, never edits .env):
|
||||
scripts/check-docker-gpu.sh
|
||||
|
||||
# Print OS-specific install commands without running them:
|
||||
scripts/check-docker-gpu.sh --print-install-commands
|
||||
|
||||
# Install NVIDIA Container Toolkit on Ubuntu/Debian (requires sudo):
|
||||
scripts/check-docker-gpu.sh --install-nvidia-toolkit
|
||||
|
||||
# Write COMPOSE_FILE to .env (only when GPU passthrough is confirmed working):
|
||||
scripts/check-docker-gpu.sh --enable-nvidia-overlay
|
||||
|
||||
# Full assisted setup — install toolkit, then enable overlay if passthrough works:
|
||||
scripts/check-docker-gpu.sh --install-nvidia-toolkit --enable-nvidia-overlay
|
||||
```
|
||||
|
||||
Safety notes:
|
||||
- The app never installs host GPU runtime automatically.
|
||||
- The app never edits `.env` automatically.
|
||||
- `.env` is only modified when `--enable-nvidia-overlay` is explicitly passed,
|
||||
and only after GPU passthrough succeeds. `--yes` skips prompts but does not
|
||||
bypass the passthrough gate.
|
||||
- `.env.bak.*` backups created by `--enable-nvidia-overlay` are ignored by
|
||||
Git and the Docker build context.
|
||||
|
||||
To enable manually without the script, add this to `.env`:
|
||||
|
||||
```bash
|
||||
COMPOSE_FILE=docker-compose.yml:docker/gpu.nvidia.yml
|
||||
```
|
||||
|
||||
**AMD / ROCm.** AMD setup is read-only diagnostic plus manual `.env` edit. Run:
|
||||
|
||||
```bash
|
||||
scripts/check-docker-amd-gpu.sh
|
||||
```
|
||||
|
||||
Then add the reported values to `.env`, replacing `RENDER_GID` with your host's
|
||||
numeric render group id:
|
||||
|
||||
```bash
|
||||
COMPOSE_FILE=docker-compose.yml:docker/gpu.amd.yml
|
||||
RENDER_GID=989
|
||||
```
|
||||
|
||||
For NVIDIA/AMD GPU support, also read the comments in the selected overlay file: docker/gpu.nvidia.yml or docker/gpu.amd.yml.
|
||||
|
||||
**Stack-management UIs (Portainer, Coolify, Dockhand, etc.).** These tools
|
||||
often accept only a single Compose file and do not reliably honor `COMPOSE_FILE`
|
||||
or multiple `-f` overlays. CLI users should keep using the `COMPOSE_FILE`
|
||||
overlay workflow above. For stack UIs, point the stack at one of the standalone
|
||||
files instead, which bundle the base stack plus the GPU settings:
|
||||
|
||||
- `docker-compose.gpu-nvidia.yml` — still requires the NVIDIA Container Toolkit
|
||||
on the host.
|
||||
- `docker-compose.gpu-amd.yml` — still requires host ROCm/kfd/DRI setup, the
|
||||
`video`/`render` group membership, and `RENDER_GID` when needed.
|
||||
|
||||
The base `docker-compose.yml` plus the `docker/gpu.*.yml` overlays remain the
|
||||
source of truth; the standalone files mirror them for single-file deployments.
|
||||
|
||||
Verify after enabling either overlay:
|
||||
|
||||
```bash
|
||||
docker compose exec odysseus nvidia-smi -L # NVIDIA
|
||||
docker compose exec odysseus sh -lc 'test -e /dev/kfd && test -d /dev/dri && ls -l /dev/kfd /dev/dri/renderD*' # AMD
|
||||
```
|
||||
|
||||
> **GPU passthrough ≠ llama.cpp CUDA.** `nvidia-smi` passing inside the
|
||||
> container confirms Docker GPU access, but llama.cpp also needs `cudart` and
|
||||
> the CUDA Toolkit at runtime. If Cookbook logs show `Unable to find cudart
|
||||
> library`, `Could NOT find CUDAToolkit`, `CUDA Toolkit not found`, or
|
||||
> tensors/layers assigned to CPU, that is a Cookbook/llama.cpp build issue —
|
||||
> not a Docker passthrough failure. Reinstall the serve engine via
|
||||
> **Cookbook → Dependencies** to get a CUDA-enabled build.
|
||||
>
|
||||
> The same split applies to AMD/ROCm: seeing `/dev/kfd` and `/dev/dri` inside
|
||||
> the container confirms device passthrough, not ROCm userspace or a
|
||||
> ROCm-enabled vLLM/llama.cpp build. `rocm-smi` and `rocminfo` are not expected
|
||||
> inside the slim Odysseus image.
|
||||
|
||||
**Ollama with Docker.** If Ollama runs on the host, add this endpoint in
|
||||
Settings:
|
||||
|
||||
```text
|
||||
http://host.docker.internal:11434/v1
|
||||
```
|
||||
|
||||
Ollama must listen outside its own loopback interface:
|
||||
|
||||
```bash
|
||||
OLLAMA_HOST=0.0.0.0:11434 ollama serve
|
||||
```
|
||||
|
||||
This connects Odysseus in Docker to an Ollama server that is already running on
|
||||
your host machine; it does not start Ollama inside the container.
|
||||
`host.docker.internal` is Docker's hostname for the host machine from inside the
|
||||
container. Cookbook **Serve** is a separate workflow for serving downloaded
|
||||
models through Odysseus/llama.cpp, so Windows users with an existing Ollama
|
||||
install usually only need to add the endpoint in Settings.
|
||||
|
||||
**Useful checks.**
|
||||
|
||||
```bash
|
||||
docker compose ps
|
||||
docker compose logs --tail=120 odysseus
|
||||
docker compose logs odysseus | grep -E 'ChromaDB|MemoryVectorStore|DEGRADED'
|
||||
```
|
||||
|
||||
**macOS details.** `start-macos.sh` installs Homebrew deps, creates the venv,
|
||||
runs setup, and starts uvicorn on port `7860` because AirPlay often holds
|
||||
`7000`. It uses llama.cpp/Ollama for Metal. vLLM/SGLang are CUDA/ROCm-only and
|
||||
do not run on macOS. MLX-only models are not served by Odysseus.
|
||||
|
||||
</details>
|
||||
|
||||
### Native Windows
|
||||
|
||||
**One-command launcher** (creates the venv, installs deps, runs setup, starts the
|
||||
server; safe to re-run):
|
||||
|
||||
```powershell
|
||||
git clone https://github.com/pewdiepie-archdaemon/odysseus.git
|
||||
cd odysseus
|
||||
powershell -ExecutionPolicy Bypass -File .\launch-windows.ps1
|
||||
```
|
||||
|
||||
Or do it by hand:
|
||||
|
||||
```powershell
|
||||
git clone https://github.com/pewdiepie-archdaemon/odysseus.git
|
||||
cd odysseus
|
||||
py -3.11 -m venv venv
|
||||
venv\Scripts\Activate.ps1
|
||||
pip install -r requirements.txt
|
||||
python setup.py
|
||||
python -m uvicorn app:app --host 127.0.0.1 --port 7000
|
||||
```
|
||||
|
||||
If `python` points at an older interpreter, use `py -3.12` (or another installed
|
||||
3.11+ version) for the venv step.
|
||||
|
||||
**Requirements:** Python 3.11+. The core app (chat, agent, memory, documents,
|
||||
email, calendar, deep research) runs fully native. For full **Cookbook** background
|
||||
model downloads and the agent shell tool, also install
|
||||
[Git for Windows](https://git-scm.com/download/win) (provides `bash.exe`).
|
||||
Local GPU *serving* of vLLM/SGLang needs Linux/WSL2; for a local model on Windows,
|
||||
[Ollama](https://ollama.com/download) is the easiest path — point Odysseus at
|
||||
`http://localhost:11434/v1` in Settings.
|
||||
|
||||
Open `http://localhost:7000`, log in with the generated admin password,
|
||||
and configure everything else inside **Settings**.
|
||||
|
||||
## Troubleshooting & Advanced Setup
|
||||
|
||||
### `chromadb-client` conflicts with embedded ChromaDB
|
||||
If `chromadb-client` (the lightweight HTTP-only package) is installed alongside the full `chromadb` package, Odysseus starts but ChromaDB silently falls back to HTTP-only mode and fails.
|
||||
|
||||
**Fix:** uninstall `chromadb-client` and force-reinstall the full package:
|
||||
```bash
|
||||
./venv/bin/pip uninstall chromadb-client -y
|
||||
./venv/bin/pip install --force-reinstall chromadb
|
||||
```
|
||||
|
||||
### HTTPS + LAN/Tailscale exposure
|
||||
To expose Odysseus on a local network or Tailscale with HTTPS:
|
||||
1. Change the bind address to `0.0.0.0` in `.env` (`APP_BIND=0.0.0.0` or `ODYSSEUS_HOST=0.0.0.0`).
|
||||
2. Generate a locally-trusted cert for your LAN/Tailscale IPs using [mkcert](https://github.com/FiloSottile/mkcert):
|
||||
```bash
|
||||
mkcert -install
|
||||
mkcert -cert-file cert.pem -key-file key.pem 192.168.1.100 tailscale-ip
|
||||
```
|
||||
3. Run `uvicorn` with the generated certs:
|
||||
```bash
|
||||
python -m uvicorn app:app --host 0.0.0.0 --port 7000 --ssl-certfile=cert.pem --ssl-keyfile=key.pem
|
||||
```
|
||||
4. Install the `mkcert` CA on any other device you want to access Odysseus from (e.g., for iOS, email the `rootCA.pem` to yourself, install the profile, and trust it in Certificate Trust Settings).
|
||||
|
||||
### Optional Dependencies
|
||||
`requirements-optional.txt` contains packages that unlock extra features. It is not installed by default.
|
||||
|
||||
| Package | Feature unlocked |
|
||||
|---------|-----------------|
|
||||
| `faster-whisper` | Local speech-to-text (microphone -> text) via the "local" STT provider. |
|
||||
| `ddgs` | DuckDuckGo as a search provider option. |
|
||||
| `PyMuPDF` | PDF page rendering in the side viewer panel and form-filling. (Note: AGPL-3.0) |
|
||||
| `markitdown` | Office/EPUB document text extraction (converts .docx/.xlsx/.pptx/.xls/.epub to Markdown). |
|
||||
|
||||
### Faster, reproducible installs with uv (optional)
|
||||
[uv](https://docs.astral.sh/uv/) works as a drop-in replacement for the
|
||||
venv + pip steps in the native install guides, no project changes are needed but this change results in faster installs along with a lockfile for reproducible environments. After [installing `uv`](https://docs.astral.sh/uv/getting-started/installation/), use:
|
||||
|
||||
```bash
|
||||
uv venv venv --python 3.13
|
||||
uv pip install -r requirements.txt
|
||||
# then continue as usual: python setup.py, uvicorn, ...
|
||||
```
|
||||
|
||||
`requirements.txt` is intentionally unpinned, so two installs at different times can produce different package versions. If you want a reproducible environment (e.g. across your own machines, or to roll back after a bad upgrade), snapshot and restore exact versions with:
|
||||
|
||||
```bash
|
||||
uv pip compile requirements.txt -o requirements.lock # snapshot current resolution
|
||||
uv pip sync requirements.lock # reproduce it exactly later
|
||||
```
|
||||
|
||||
`requirements.lock` is gitignored and platform-specific (compile it on the OS you deploy to). Regenerate it deliberately when you want to take upgrades. The plain `uv pip install -r requirements.txt` keeps following the unpinned requirements like pip does.
|
||||
|
||||
### Outlook / Office 365 email
|
||||
Odysseus email accounts currently use IMAP/SMTP username-password auth. Outlook
|
||||
and Microsoft 365 generally require OAuth instead, so normal Microsoft mailbox
|
||||
passwords will fail. See [docs/email-outlook.md](docs/email-outlook.md) for the
|
||||
current limitation and the planned integration direction.
|
||||
|
||||
## Security Notes
|
||||
Odysseus is a self-hosted workspace with powerful local tools: shell access, file uploads, model downloads, web research, email/calendar integrations, and API tokens. Treat it like an admin console.
|
||||
|
||||
- Keep `AUTH_ENABLED=true` for any network-accessible deployment.
|
||||
- Keep `LOCALHOST_BYPASS=false` outside local development.
|
||||
- Use `SECURE_COOKIES=true` when Odysseus is served through HTTPS by a trusted reverse proxy or private access gateway.
|
||||
- Do not expose it directly to the public internet without HTTPS and a trusted reverse proxy or private access layer.
|
||||
- Keep `.env`, `data/`, `logs/`, databases, uploads, generated media, backups, auth/session files, API keys, and model/provider tokens out of Git and private shares. They are ignored by default.
|
||||
- Review `data/auth.json` after first boot: disable open signup unless you intentionally want it, make only your own account admin, and keep demo/test accounts non-admin.
|
||||
- Non-admin users do not get shell/Python/file read/write by default, and admin-only routes/tools such as MCP management, API tokens, webhooks, model/cookbook serving, backup/vault, and app settings are admin-gated. Other features are controlled by per-user privileges, so review each user's privileges before exposing a deployment.
|
||||
- Rotate any API keys or tokens that were ever pasted into a shared chat, demo, screenshot, or log.
|
||||
- If you enable API tokens or webhooks, create separate tokens per integration and delete unused ones.
|
||||
- Prefer binding manual development runs to `127.0.0.1`; bind to `0.0.0.0` only when you intentionally want LAN/reverse-proxy access.
|
||||
- Keep ChromaDB, SearXNG, ntfy, Ollama, vLLM, llama.cpp, databases, and raw model/provider APIs internal-only. Expose only the authenticated Odysseus web/API entrypoint through your trusted proxy or private access layer.
|
||||
- Before publishing a fork, run `git status --short` and confirm no private files from `.env`, `data/`, `logs/`, uploads, backups, or local databases are staged.
|
||||
|
||||
### Private or proxied deployments
|
||||
Odysseus serves plain HTTP on its app port. Docker Compose binds Odysseus and the bundled services to `127.0.0.1` by default, so a typical production/private setup is:
|
||||
|
||||
1. Keep Odysseus on localhost, for example `127.0.0.1:7000`.
|
||||
2. Terminate HTTPS at a trusted reverse proxy or private access gateway.
|
||||
3. Put the authenticated Odysseus web/API entrypoint behind that layer.
|
||||
4. Keep raw service and model ports internal-only.
|
||||
|
||||
Cloudflare Access, Tailscale, Caddy, nginx, and Traefik can all fit this pattern; none are required by Odysseus. If your access layer reaches Odysseus on the same host, proxy to `http://127.0.0.1:7000` and keep `AUTH_ENABLED=true`, `LOCALHOST_BYPASS=false`, and `SECURE_COOKIES=true`.
|
||||
`ALLOWED_ORIGINS` lists exact permitted origins for cross-origin browser/API clients; ordinary same-origin reverse-proxy access usually does not need a special CORS entry.
|
||||
|
||||
Common internal-only ports from the default docs/compose setup:
|
||||
|
||||
| Port | Service |
|
||||
|---|---|
|
||||
| `7000` | Odysseus raw app port |
|
||||
| `8080` | SearXNG |
|
||||
| `8091` | ntfy |
|
||||
| `8100` | ChromaDB host port for manual/compose access |
|
||||
| `11434` | Ollama |
|
||||
| `8000-8020` | Common local model/provider APIs |
|
||||
|
||||
## Configuration
|
||||
Most setup is done inside the app with `/setup` or **Settings**. Use `.env`
|
||||
for deployment-level defaults and secrets you want present before first boot.
|
||||
Key settings:
|
||||
|
||||
| Variable | Default | Description |
|
||||
|---|---|---|
|
||||
| `LLM_HOST` | `localhost` | Your LLM server (e.g. `llm-host.local:8000`) |
|
||||
| `LLM_HOSTS` | -- | Comma-separated list for model discovery |
|
||||
| `OPENAI_API_KEY` | -- | Optional OpenAI key. Prefer adding providers in the app unless pre-seeding. |
|
||||
| `SEARXNG_INSTANCE` | `http://localhost:8080` | SearXNG URL. Docker overrides this to `http://searxng:8080`. |
|
||||
| `SEARXNG_SECRET` | generated on first Docker boot | Optional SearXNG cookie/CSRF secret. Leave blank unless you need to pin it. |
|
||||
| `APP_BIND` | `127.0.0.1` | Docker Compose host bind address for the web UI. Use `0.0.0.0` only for intentional LAN/reverse-proxy access. |
|
||||
| `APP_PORT` | `7000` | Docker Compose host port for the web UI. |
|
||||
| `APP_DATA_DIR` | `./data` | Docker Compose host directory for application data volumes. |
|
||||
| `APP_LOGS_DIR` | `./logs` | Docker Compose host directory for application logs. |
|
||||
| `AUTH_ENABLED` | `true` | Enable/disable login |
|
||||
| `LOCALHOST_BYPASS` | `false` | Development-only auth bypass for loopback requests. Keep false for shared/network deployments. |
|
||||
| `ALLOWED_ORIGINS` | `http://localhost,http://127.0.0.1` | Comma-separated exact permitted origins for cross-origin browser/API clients. |
|
||||
| `SECURE_COOKIES` | `false` | Set true when serving Odysseus through HTTPS at a trusted proxy or private access gateway. |
|
||||
| `DATABASE_URL` | `sqlite:///./data/app.db` | Database connection string |
|
||||
| `CHROMADB_HOST` | `localhost` | ChromaDB host for vector memory. Docker overrides this to `chromadb`. |
|
||||
| `CHROMADB_PORT` | `8100` | ChromaDB port for manual host runs. Docker overrides this to `8000`. |
|
||||
| `EMBEDDING_URL` | -- | OpenAI-compatible embeddings endpoint |
|
||||
| `ODYSSEUS_CHAT_UPLOAD_MAX_BYTES` | `10485760` | Chat/agent attachment cap in bytes. Raise for larger local PDFs or text documents. |
|
||||
| `ODYSSEUS_GALLERY_UPLOAD_MAX_BYTES` | `104857600` | Gallery image upload cap in bytes (100 MB). |
|
||||
| `ODYSSEUS_GALLERY_TRANSFORM_UPLOAD_MAX_BYTES` | `26214400` | Gallery transform input cap in bytes (25 MB). |
|
||||
| `ODYSSEUS_MEMORY_IMPORT_MAX_BYTES` | `10485760` | Memory import file cap in bytes (10 MB). |
|
||||
| `ODYSSEUS_PERSONAL_UPLOAD_MAX_BYTES` | `26214400` | Personal document upload cap in bytes (25 MB). |
|
||||
| `ODYSSEUS_EMAIL_COMPOSE_UPLOAD_MAX_BYTES` | `26214400` | Email compose attachment cap in bytes (25 MB). |
|
||||
| `ODYSSEUS_STT_MAX_AUDIO_BYTES` | `26214400` | Speech-to-text audio cap in bytes (25 MB). |
|
||||
| `ODYSSEUS_ICS_MAX_BYTES` | `10485760` | Calendar `.ics` import cap in bytes (10 MB). |
|
||||
|
||||
All upload-limit vars are validated (must be a positive integer) and optional; an invalid value fails fast at startup.
|
||||
|
||||
### Built-in MCP servers (optional setup)
|
||||
|
||||
Odysseus auto-registers a few built-in MCP servers at startup. The npx-based ones (currently the browser server, `@playwright/mcp`) only start when their npm package is already in the local npx cache. If a package isn't cached, that server is skipped with a startup log message explaining what to do, so a fresh install does not block on a multi-minute npm download or hang if Playwright system deps are missing.
|
||||
|
||||
To enable the browser MCP (page navigation, screenshots, vision), run once:
|
||||
|
||||
```bash
|
||||
npx -y @playwright/mcp@latest --version
|
||||
```
|
||||
|
||||
That installs `@playwright/mcp` plus Playwright (~300MB total). Restart Odysseus and the server will register at startup.
|
||||
|
||||
## Architecture
|
||||
```
|
||||
app.py # FastAPI entry point
|
||||
core/ auth, database, middleware, constants
|
||||
src/ llm_core, agent_loop, agent_tools, chat_processor, search/
|
||||
routes/ chat, session, document, memory, model … endpoints
|
||||
services/ docs, memory, search, hwfit (Cookbook) …
|
||||
static/ index.html + app.js + style.css + js/ (modular front-end)
|
||||
docs/ landing page (index.html) + preview clips
|
||||
```
|
||||
|
||||
## Data
|
||||
All user data lives in `data/` (gitignored): `app.db` (sessions, messages, documents),
|
||||
`memory.json`, `presets.json`, `uploads/`, `personal_docs/`, `chroma/`, `settings.json`.
|
||||
|
||||
To back up or restore everything in `data/`, see the
|
||||
[Backup & Restore guide](docs/backup-restore.md).
|
||||
@@ -102,6 +102,7 @@ python3 ~/.claude/skills/odysseus/scripts/odysseus_api.py POST /api/codex/memory
|
||||
|
||||
## Email draft + send
|
||||
|
||||
- Prefer `POST /api/codex/emails/draft-document` for agent-written email replies. It creates an editable Odysseus Document with `language: "email"` and does not touch IMAP/send.
|
||||
- `POST /api/codex/emails/draft` — body matches `SendEmailRequest` (`to`, `cc`, `bcc`, `subject`, `body`, `body_html`, `attachments`, `account_id`, `in_reply_to`, `references`). Requires `email:draft` (or `email:send`).
|
||||
- `POST /api/codex/emails/send` — same body. Requires `email:send`. Never send without explicit user instruction.
|
||||
|
||||
|
||||
@@ -17,6 +17,11 @@ def _usage() -> int:
|
||||
print(" odysseus_api.py todos add TITLE", file=sys.stderr)
|
||||
print(" odysseus_api.py emails list [limit]", file=sys.stderr)
|
||||
print(" odysseus_api.py emails read UID", file=sys.stderr)
|
||||
print(" odysseus_api.py emails draft-doc JSON_PAYLOAD", file=sys.stderr)
|
||||
print(" odysseus_api.py documents list [limit]", file=sys.stderr)
|
||||
print(" odysseus_api.py documents read DOC_ID", file=sys.stderr)
|
||||
print(" odysseus_api.py documents create JSON_PAYLOAD", file=sys.stderr)
|
||||
print(" odysseus_api.py documents delete DOC_ID", file=sys.stderr)
|
||||
print(" odysseus_api.py cookbook tasks", file=sys.stderr)
|
||||
print(" odysseus_api.py cookbook servers", file=sys.stderr)
|
||||
print(" odysseus_api.py cookbook cached [HOST]", file=sys.stderr)
|
||||
@@ -79,6 +84,33 @@ def main() -> int:
|
||||
method = "GET"
|
||||
path = f"/api/codex/emails/{sys.argv[3]}"
|
||||
body = None
|
||||
elif action in ("draft-doc", "draft_document") and len(sys.argv) >= 4:
|
||||
method = "POST"
|
||||
path = "/api/codex/emails/draft-document"
|
||||
body = " ".join(sys.argv[3:])
|
||||
else:
|
||||
return _usage()
|
||||
elif command in ("documents", "docs"):
|
||||
if len(sys.argv) < 3:
|
||||
return _usage()
|
||||
action = sys.argv[2].lower()
|
||||
if action == "list":
|
||||
method = "GET"
|
||||
limit = sys.argv[3] if len(sys.argv) >= 4 else "50"
|
||||
path = f"/api/codex/documents?limit={limit}"
|
||||
body = None
|
||||
elif action == "read" and len(sys.argv) >= 4:
|
||||
method = "GET"
|
||||
path = f"/api/codex/documents/{sys.argv[3]}"
|
||||
body = None
|
||||
elif action == "create" and len(sys.argv) >= 4:
|
||||
method = "POST"
|
||||
path = "/api/codex/documents"
|
||||
body = " ".join(sys.argv[3:])
|
||||
elif action == "delete" and len(sys.argv) >= 4:
|
||||
method = "DELETE"
|
||||
path = f"/api/codex/documents/{sys.argv[3]}"
|
||||
body = None
|
||||
else:
|
||||
return _usage()
|
||||
elif command == "cookbook":
|
||||
|
||||
@@ -17,6 +17,11 @@ def _usage() -> int:
|
||||
print(" odysseus_api.py todos add TITLE", file=sys.stderr)
|
||||
print(" odysseus_api.py emails list [limit]", file=sys.stderr)
|
||||
print(" odysseus_api.py emails read UID", file=sys.stderr)
|
||||
print(" odysseus_api.py emails draft-doc JSON_PAYLOAD", file=sys.stderr)
|
||||
print(" odysseus_api.py documents list [limit]", file=sys.stderr)
|
||||
print(" odysseus_api.py documents read DOC_ID", file=sys.stderr)
|
||||
print(" odysseus_api.py documents create JSON_PAYLOAD", file=sys.stderr)
|
||||
print(" odysseus_api.py documents delete DOC_ID", file=sys.stderr)
|
||||
print(" odysseus_api.py cookbook tasks", file=sys.stderr)
|
||||
print(" odysseus_api.py cookbook servers", file=sys.stderr)
|
||||
print(" odysseus_api.py cookbook cached [HOST]", file=sys.stderr)
|
||||
@@ -79,6 +84,33 @@ def main() -> int:
|
||||
method = "GET"
|
||||
path = f"/api/codex/emails/{sys.argv[3]}"
|
||||
body = None
|
||||
elif action in ("draft-doc", "draft_document") and len(sys.argv) >= 4:
|
||||
method = "POST"
|
||||
path = "/api/codex/emails/draft-document"
|
||||
body = " ".join(sys.argv[3:])
|
||||
else:
|
||||
return _usage()
|
||||
elif command in ("documents", "docs"):
|
||||
if len(sys.argv) < 3:
|
||||
return _usage()
|
||||
action = sys.argv[2].lower()
|
||||
if action == "list":
|
||||
method = "GET"
|
||||
limit = sys.argv[3] if len(sys.argv) >= 4 else "50"
|
||||
path = f"/api/codex/documents?limit={limit}"
|
||||
body = None
|
||||
elif action == "read" and len(sys.argv) >= 4:
|
||||
method = "GET"
|
||||
path = f"/api/codex/documents/{sys.argv[3]}"
|
||||
body = None
|
||||
elif action == "create" and len(sys.argv) >= 4:
|
||||
method = "POST"
|
||||
path = "/api/codex/documents"
|
||||
body = " ".join(sys.argv[3:])
|
||||
elif action == "delete" and len(sys.argv) >= 4:
|
||||
method = "DELETE"
|
||||
path = f"/api/codex/documents/{sys.argv[3]}"
|
||||
body = None
|
||||
else:
|
||||
return _usage()
|
||||
elif command == "cookbook":
|
||||
|
||||
@@ -102,6 +102,7 @@ python3 integrations/codex/scripts/odysseus_api.py POST /api/codex/memory '{"tex
|
||||
|
||||
## Email draft + send
|
||||
|
||||
- Prefer `POST /api/codex/emails/draft-document` for Codex-written email replies. It creates an editable Odysseus Document with `language: "email"` and does not touch IMAP/send.
|
||||
- `POST /api/codex/emails/draft` — body matches `SendEmailRequest` (`to`, `cc`, `bcc`, `subject`, `body`, `body_html`, `attachments`, `account_id`, `in_reply_to`, `references`). Requires `email:draft` (or `email:send`).
|
||||
- `POST /api/codex/emails/send` — same body. Requires `email:send`. Never send without explicit user instruction.
|
||||
|
||||
|
||||
@@ -105,6 +105,14 @@ if (-not $pyExe) {
|
||||
}
|
||||
}
|
||||
|
||||
if ($pyExe -like "*WindowsApps*python.exe") {
|
||||
$pyCmd = Get-Command py -ErrorAction SilentlyContinue
|
||||
if ($pyCmd) {
|
||||
$pyExe = $pyCmd.Source
|
||||
$pyArgs = @("-3.11")
|
||||
}
|
||||
}
|
||||
|
||||
if (-not $pyExe) {
|
||||
Fail "Couldn't find Python 3.11+ for Windows setup. Install Python 3.11+ (or open the Python launcher with 'py -3.11') from https://www.python.org/downloads/, then re-run this script."
|
||||
}
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
# launcher.py
|
||||
"""Dedicated entrypoint for the standalone Windows portable launcher.
|
||||
|
||||
Handles:
|
||||
- Immediate GUI splash screen creation using tkinter.
|
||||
- Suppressing console stream crashes in windowed GUI mode via NullWriter.
|
||||
- Spawning system tray icon via pystray and Pillow (lazy-loaded).
|
||||
- Auto-opening default browser pointing to the running backend.
|
||||
- Launching the FastAPI server (importing and running app.py).
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import webbrowser
|
||||
|
||||
# Define a dummy NullWriter to suppress standard stream crashes (isatty etc.) in GUI mode
|
||||
class NullWriter:
|
||||
def write(self, text):
|
||||
pass
|
||||
def flush(self):
|
||||
pass
|
||||
def isatty(self):
|
||||
return False
|
||||
|
||||
if sys.stdout is None:
|
||||
sys.stdout = NullWriter()
|
||||
if sys.stderr is None:
|
||||
sys.stderr = NullWriter()
|
||||
|
||||
|
||||
splash_root = None
|
||||
|
||||
# If running from a frozen PyInstaller bundle, launch the splash screen IMMEDIATELY
|
||||
if getattr(sys, 'frozen', False):
|
||||
import tkinter as tk
|
||||
|
||||
def show_splash_instantly():
|
||||
global splash_root
|
||||
try:
|
||||
splash_root = tk.Tk()
|
||||
splash_root.title("Odysseus")
|
||||
splash_root.overrideredirect(True)
|
||||
splash_root.configure(bg="#1a1c23")
|
||||
|
||||
# Accented borders
|
||||
splash_root.config(highlightbackground="#e06c75", highlightcolor="#e06c75", highlightthickness=1)
|
||||
|
||||
w, h = 360, 160
|
||||
ws = splash_root.winfo_screenwidth()
|
||||
hs = splash_root.winfo_screenheight()
|
||||
x = (ws - w) // 2
|
||||
y = (hs - h) // 2
|
||||
splash_root.geometry(f"{w}x{h}+{x}+{y}")
|
||||
|
||||
tk.Label(splash_root, text="⛵ Odysseus", font=("Segoe UI", 22, "bold"), bg="#1a1c23", fg="#e06c75").pack(pady=(22, 2))
|
||||
tk.Label(splash_root, text="Launching background services...", font=("Segoe UI", 10), bg="#1a1c23", fg="#d1d4e0").pack(pady=2)
|
||||
tk.Label(splash_root, text="Please wait, this will take a few seconds.", font=("Segoe UI", 8, "italic"), bg="#1a1c23", fg="#5c6370").pack(pady=(12, 0))
|
||||
|
||||
splash_root.attributes("-topmost", True)
|
||||
splash_root.mainloop()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Launch the GUI splash screen immediately on a background thread
|
||||
threading.Thread(target=show_splash_instantly, daemon=True).start()
|
||||
|
||||
|
||||
def create_tray_image():
|
||||
# Generate a beautiful 64x64 icon matching Odysseus brand red accent (#e06c75)
|
||||
from PIL import Image, ImageDraw
|
||||
image = Image.new('RGBA', (64, 64), (0, 0, 0, 0))
|
||||
dc = ImageDraw.Draw(image)
|
||||
accent_red = (224, 108, 117, 255)
|
||||
light_red = (224, 108, 117, 150)
|
||||
|
||||
# Draw premium sailing boat
|
||||
dc.polygon([(32, 10), (32, 45), (12, 45)], fill=accent_red)
|
||||
dc.polygon([(32, 18), (32, 45), (48, 45)], fill=light_red)
|
||||
dc.polygon([(8, 48), (56, 48), (44, 56), (20, 56)], fill=accent_red)
|
||||
return image
|
||||
|
||||
|
||||
def on_open_browser(icon, item, url):
|
||||
webbrowser.open(url)
|
||||
|
||||
|
||||
def on_exit(icon, item):
|
||||
icon.stop()
|
||||
os._exit(0)
|
||||
|
||||
|
||||
def setup_system_tray(url):
|
||||
try:
|
||||
import pystray
|
||||
icon_img = create_tray_image()
|
||||
menu = (
|
||||
pystray.MenuItem('Open Odysseus', lambda icon, item: on_open_browser(icon, item, url), default=True),
|
||||
pystray.MenuItem('Exit', on_exit)
|
||||
)
|
||||
tray_icon = pystray.Icon(
|
||||
"Odysseus",
|
||||
icon_img,
|
||||
"Odysseus",
|
||||
menu
|
||||
)
|
||||
tray_icon.run()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def open_browser(url):
|
||||
# Allow uvicorn and app lifecycles to complete warmups
|
||||
time.sleep(3.5)
|
||||
|
||||
# Safely close the splash screen
|
||||
try:
|
||||
global splash_root
|
||||
if splash_root:
|
||||
splash_root.after(0, splash_root.destroy)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
webbrowser.open(url)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
# Import the FastAPI app from app.py
|
||||
from app import app
|
||||
|
||||
bind_host = os.getenv("APP_BIND", "127.0.0.1")
|
||||
bind_port = int(os.getenv("APP_PORT", "7000"))
|
||||
url = f"http://{bind_host}:{bind_port}"
|
||||
|
||||
if getattr(sys, 'frozen', False):
|
||||
# Start browser manager thread
|
||||
threading.Thread(target=open_browser, args=(url,), daemon=True).start()
|
||||
# Start system tray manager thread
|
||||
threading.Thread(target=setup_system_tray, args=(url,), daemon=True).start()
|
||||
|
||||
uvicorn.run(app, host=bind_host, port=bind_port, log_level="info")
|
||||
@@ -23,6 +23,7 @@ import os.path
|
||||
from pathlib import Path
|
||||
from datetime import datetime, timedelta
|
||||
import uuid
|
||||
from contextvars import ContextVar
|
||||
|
||||
from mcp.server import Server
|
||||
from mcp.server.stdio import stdio_server
|
||||
@@ -55,6 +56,8 @@ def _uid_fetch_rows(data) -> list:
|
||||
# flat keys when no DB row matches (legacy single-account behaviour).
|
||||
|
||||
_ACCOUNT_CACHE: dict = {} # key = normalized account selector -> config dict
|
||||
_MCP_OWNER_ARG = "_odysseus_owner"
|
||||
_CURRENT_OWNER: ContextVar[str | None] = ContextVar("email_mcp_owner", default=None)
|
||||
|
||||
|
||||
def _clean_header_value(value) -> str:
|
||||
@@ -68,6 +71,45 @@ def _db_path() -> Path:
|
||||
return Path(APP_DB)
|
||||
|
||||
|
||||
def _current_owner() -> str:
|
||||
owner = _CURRENT_OWNER.get()
|
||||
return str(owner or "").strip()
|
||||
|
||||
|
||||
def _account_visible_to_owner(row: dict, owner: str) -> bool:
|
||||
row_owner = str(row.get("owner") or "").strip()
|
||||
if row_owner == owner:
|
||||
return True
|
||||
if row_owner:
|
||||
return False
|
||||
# Legacy ownerless accounts are only visible to a scoped caller when the
|
||||
# mailbox itself matches the owner, mirroring the HTTP email route fallback.
|
||||
owner_l = owner.lower()
|
||||
return owner_l in {
|
||||
str(row.get("imap_user") or "").strip().lower(),
|
||||
str(row.get("from_address") or "").strip().lower(),
|
||||
}
|
||||
|
||||
|
||||
def _filter_accounts_for_owner(rows: list[dict]) -> list[dict]:
|
||||
owner = _current_owner()
|
||||
if owner:
|
||||
return [r for r in rows if _account_visible_to_owner(r, owner)]
|
||||
|
||||
owners = {str(r.get("owner") or "").strip() for r in rows if str(r.get("owner") or "").strip()}
|
||||
if len(owners) > 1:
|
||||
return []
|
||||
return rows
|
||||
|
||||
|
||||
def _mcp_owner_required(rows: list[dict] | None = None) -> bool:
|
||||
if _current_owner():
|
||||
return False
|
||||
rows = rows if rows is not None else _read_accounts_from_db()
|
||||
owners = {str(r.get("owner") or "").strip() for r in rows if str(r.get("owner") or "").strip()}
|
||||
return len(owners) > 1
|
||||
|
||||
|
||||
def _load_email_writing_style() -> str:
|
||||
"""Return the existing Settings > Email > Writing Style value."""
|
||||
try:
|
||||
@@ -121,9 +163,8 @@ def _default_document_owner() -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
def _list_accounts_raw() -> list:
|
||||
"""Return list of dicts from the email_accounts table. Empty list if table
|
||||
missing or empty. Never raises."""
|
||||
def _read_accounts_from_db() -> list:
|
||||
"""Return all enabled email account rows. Empty list if missing. Never raises."""
|
||||
path = _db_path()
|
||||
if not path.exists():
|
||||
return []
|
||||
@@ -131,9 +172,10 @@ def _list_accounts_raw() -> list:
|
||||
conn = sqlite3.connect(str(path))
|
||||
conn.row_factory = sqlite3.Row
|
||||
columns = {r[1] for r in conn.execute("PRAGMA table_info(email_accounts)").fetchall()}
|
||||
owner_select = "owner" if "owner" in columns else "NULL AS owner"
|
||||
smtp_security_select = "smtp_security" if "smtp_security" in columns else "'' AS smtp_security"
|
||||
rows = conn.execute(f"""
|
||||
SELECT id, name, is_default, enabled,
|
||||
SELECT id, {owner_select}, name, is_default, enabled,
|
||||
imap_host, imap_port, imap_user, imap_password, imap_starttls,
|
||||
smtp_host, smtp_port, {smtp_security_select}, smtp_user, smtp_password, from_address
|
||||
FROM email_accounts WHERE enabled = 1
|
||||
@@ -147,11 +189,15 @@ def _list_accounts_raw() -> list:
|
||||
return []
|
||||
|
||||
|
||||
def _resolve_account(selector: str | None) -> dict | None:
|
||||
def _list_accounts_raw() -> list:
|
||||
"""Return owner-visible email account rows for the active MCP call."""
|
||||
return _filter_accounts_for_owner(_read_accounts_from_db())
|
||||
|
||||
|
||||
def _resolve_account_from_rows(rows: list[dict], selector: str | None) -> dict | None:
|
||||
"""Given a selector (None = default, or a name/user/id string), return the
|
||||
matching row or None. Matching is case-insensitive substring on name +
|
||||
imap_user + from_address, plus exact id match."""
|
||||
rows = _list_accounts_raw()
|
||||
if not rows:
|
||||
return None
|
||||
if not selector:
|
||||
@@ -186,6 +232,10 @@ def _resolve_account(selector: str | None) -> dict | None:
|
||||
return None
|
||||
|
||||
|
||||
def _resolve_account(selector: str | None) -> dict | None:
|
||||
return _resolve_account_from_rows(_list_accounts_raw(), selector)
|
||||
|
||||
|
||||
def _load_config(account: str | None = None) -> dict:
|
||||
"""Return the full config dict for the requested account (or default).
|
||||
|
||||
@@ -194,7 +244,7 @@ def _load_config(account: str | None = None) -> dict:
|
||||
2. env vars + settings.json flat keys (legacy)
|
||||
3. hardcoded fallbacks (localhost:31143 etc.)
|
||||
"""
|
||||
cache_key = (account or "").strip().lower() or "__default__"
|
||||
cache_key = (_current_owner(), (account or "").strip().lower() or "__default__")
|
||||
if cache_key in _ACCOUNT_CACHE:
|
||||
return _ACCOUNT_CACHE[cache_key]
|
||||
|
||||
@@ -223,8 +273,11 @@ def _load_config(account: str | None = None) -> dict:
|
||||
"account_name": None,
|
||||
}
|
||||
|
||||
rows = _list_accounts_raw()
|
||||
row = _resolve_account(account)
|
||||
raw_rows = _read_accounts_from_db()
|
||||
rows = _filter_accounts_for_owner(raw_rows)
|
||||
row = _resolve_account_from_rows(rows, account)
|
||||
if _current_owner() and raw_rows and not rows:
|
||||
raise ValueError("No email account is configured for the authenticated owner")
|
||||
if account and rows and not row:
|
||||
available = ", ".join(
|
||||
f"{r.get('name') or r.get('imap_user')} <{r.get('imap_user') or r.get('from_address') or '?'}>"
|
||||
@@ -885,8 +938,109 @@ def _smtp_connect(account=None, cfg=None):
|
||||
return conn
|
||||
|
||||
|
||||
def _read_agent_email_confirm_setting() -> bool:
|
||||
"""True if the user wants agent send_email/reply_to_email calls to be
|
||||
queued for manual approval instead of SMTPed immediately. Defaults to
|
||||
True so a fresh install is safe — agents have been observed inventing
|
||||
signatures and sending to real recipients without the user's review."""
|
||||
try:
|
||||
from src.settings import get_setting
|
||||
return bool(get_setting("agent_email_confirm", True))
|
||||
except Exception:
|
||||
return True
|
||||
|
||||
|
||||
def _stash_agent_draft(*, to, subject, body, in_reply_to=None, references=None,
|
||||
cc=None, bcc=None, account=None) -> dict:
|
||||
"""Insert the composed email into scheduled_emails with status
|
||||
'agent_draft' and a far-future send_at so the scheduled-send poller
|
||||
never picks it up. Returns the pending payload the model surfaces to
|
||||
the user (and that the chat UI can render as an approval card)."""
|
||||
try:
|
||||
from src.constants import SCHEDULED_EMAILS_DB
|
||||
except Exception:
|
||||
return {"success": False, "error": "Pending-email storage unavailable"}
|
||||
pending_id = uuid.uuid4().hex[:16]
|
||||
far_future = "9999-12-31T00:00:00"
|
||||
now = datetime.utcnow().isoformat()
|
||||
try:
|
||||
conn = sqlite3.connect(SCHEDULED_EMAILS_DB)
|
||||
# Touch the schema in case the email-routes init hasn't run yet
|
||||
# (MCP server can boot independently).
|
||||
conn.execute("""
|
||||
CREATE TABLE IF NOT EXISTS scheduled_emails (
|
||||
id TEXT PRIMARY KEY,
|
||||
to_addr TEXT NOT NULL,
|
||||
cc TEXT,
|
||||
bcc TEXT,
|
||||
subject TEXT,
|
||||
body TEXT NOT NULL,
|
||||
in_reply_to TEXT,
|
||||
references_hdr TEXT,
|
||||
attachments TEXT,
|
||||
send_at TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'pending',
|
||||
error TEXT,
|
||||
owner TEXT DEFAULT '',
|
||||
account_id TEXT,
|
||||
odysseus_kind TEXT
|
||||
)
|
||||
""")
|
||||
conn.execute("""
|
||||
INSERT INTO scheduled_emails
|
||||
(id, to_addr, cc, bcc, subject, body, in_reply_to, references_hdr,
|
||||
attachments, send_at, created_at, status, account_id, odysseus_kind, owner)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'agent_draft', ?, ?, ?)
|
||||
""", (
|
||||
pending_id,
|
||||
to if isinstance(to, str) else ", ".join(to),
|
||||
cc if isinstance(cc, str) else (", ".join(cc) if cc else None),
|
||||
bcc if isinstance(bcc, str) else (", ".join(bcc) if bcc else None),
|
||||
subject or "",
|
||||
body or "",
|
||||
in_reply_to or None,
|
||||
references if isinstance(references, str) else (" ".join(references) if references else None),
|
||||
"[]",
|
||||
far_future,
|
||||
now,
|
||||
account or None,
|
||||
"agent_draft",
|
||||
_current_owner(),
|
||||
))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
except Exception as e:
|
||||
return {"success": False, "error": f"Failed to stash draft: {e}"}
|
||||
return {
|
||||
"success": True,
|
||||
"pending": True,
|
||||
"pending_id": pending_id,
|
||||
"to": to if isinstance(to, str) else ", ".join(to),
|
||||
"subject": subject or "",
|
||||
"body": body or "",
|
||||
"message": (
|
||||
"✋ Draft staged for your approval — nothing has been sent yet.\n"
|
||||
"Review the To/Subject/Body above. Reply 'send' to deliver, or "
|
||||
"'cancel' to discard."
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _send_email(to, subject, body, in_reply_to=None, references=None, cc=None, bcc=None, account=None):
|
||||
"""Send an email via SMTP. Returns dict with status."""
|
||||
"""Send an email via SMTP. Returns dict with status.
|
||||
|
||||
When the `agent_email_confirm` setting is on (the default), the email
|
||||
is NOT SMTPed — instead it lands in scheduled_emails as an
|
||||
`agent_draft` row and the user reviews + approves it from the chat
|
||||
UI. This closes the auto-send hole that let earlier models invent
|
||||
signatures and ship them to real recipients without confirmation."""
|
||||
if _read_agent_email_confirm_setting():
|
||||
return _stash_agent_draft(
|
||||
to=to, subject=subject, body=body,
|
||||
in_reply_to=in_reply_to, references=references,
|
||||
cc=cc, bcc=bcc, account=account,
|
||||
)
|
||||
send_account, cfg = _resolve_send_config(account)
|
||||
msg = EmailMessage()
|
||||
msg["From"] = _clean_header_value(cfg["from_address"])
|
||||
@@ -1038,7 +1192,7 @@ def _create_email_draft_document(
|
||||
doc_id = str(uuid.uuid4())
|
||||
ver_id = str(uuid.uuid4())
|
||||
doc_title = (title or subject or "Email draft").strip() or "Email draft"
|
||||
doc_owner = _default_document_owner()
|
||||
doc_owner = _current_owner() or _default_document_owner()
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
@@ -1824,10 +1978,22 @@ async def list_tools() -> list[Tool]:
|
||||
|
||||
@server.call_tool()
|
||||
async def call_tool(name: str, arguments: dict) -> list[TextContent]:
|
||||
arguments = dict(arguments) if isinstance(arguments, dict) else {}
|
||||
owner = str(arguments.pop(_MCP_OWNER_ARG, "") or "").strip()
|
||||
owner_token = _CURRENT_OWNER.set(owner or None)
|
||||
try:
|
||||
all_db_accounts = _read_accounts_from_db()
|
||||
if _mcp_owner_required(all_db_accounts):
|
||||
return [TextContent(
|
||||
type="text",
|
||||
text="Error: email MCP requires an authenticated owner when multiple email account owners are configured.",
|
||||
)]
|
||||
|
||||
if name == "list_email_accounts":
|
||||
rows = _list_accounts_raw()
|
||||
rows = _filter_accounts_for_owner(all_db_accounts)
|
||||
if not rows:
|
||||
if all_db_accounts and owner:
|
||||
return [TextContent(type="text", text="No email accounts configured for this owner.")]
|
||||
return [TextContent(type="text", text="No email accounts configured. Legacy single-account mode active.")]
|
||||
lines = [f"Found {len(rows)} email account(s):\n"]
|
||||
for r in rows:
|
||||
@@ -2007,6 +2173,16 @@ async def call_tool(name: str, arguments: dict) -> list[TextContent]:
|
||||
bcc=arguments.get("bcc"),
|
||||
account=acct,
|
||||
)
|
||||
if "error" in result:
|
||||
return [TextContent(type="text", text=f"Error: {result['error']}")]
|
||||
if result.get("pending"):
|
||||
return [TextContent(
|
||||
type="text",
|
||||
text=(
|
||||
f"Draft staged for approval (pending id: {result.get('pending_id')}). "
|
||||
"Nothing has been sent yet. Review and approve it in Odysseus before delivery."
|
||||
),
|
||||
)]
|
||||
acct_note = f" (from {result['account']})" if result.get("account") else ""
|
||||
return [TextContent(type="text", text=f"Sent email to {result['to']} with subject '{result['subject']}'{acct_note}.")]
|
||||
|
||||
@@ -2182,6 +2358,8 @@ async def call_tool(name: str, arguments: dict) -> list[TextContent]:
|
||||
|
||||
except Exception as e:
|
||||
return [TextContent(type="text", text=f"Error: {e}")]
|
||||
finally:
|
||||
_CURRENT_OWNER.reset(owner_token)
|
||||
|
||||
|
||||
# ── Main ──
|
||||
|
||||
@@ -6,6 +6,7 @@ Imports MemoryManager and MemoryVectorStore from the Odysseus codebase.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
@@ -23,6 +24,55 @@ _memory_manager = None
|
||||
_memory_vector = None
|
||||
_initialized = False
|
||||
|
||||
_OWNER_ENV_KEYS = ("ODYSSEUS_MCP_MEMORY_OWNER", "ODYSSEUS_MEMORY_OWNER")
|
||||
_OWNER_SCOPE_ERROR = (
|
||||
"Error: Memory MCP owner is not configured for an owner-scoped memory store. "
|
||||
"Set ODYSSEUS_MCP_MEMORY_OWNER for this server or use the owner-aware native memory tool."
|
||||
)
|
||||
|
||||
|
||||
def _configured_owner() -> str | None:
|
||||
for key in _OWNER_ENV_KEYS:
|
||||
owner = os.environ.get(key, "").strip()
|
||||
if owner:
|
||||
return owner
|
||||
return None
|
||||
|
||||
|
||||
def _entry_owner(entry: dict) -> str | None:
|
||||
owner = entry.get("owner")
|
||||
if owner is None:
|
||||
return None
|
||||
owner_text = str(owner).strip()
|
||||
return owner_text or None
|
||||
|
||||
|
||||
def _owner_scoped_store(entries: list[dict]) -> bool:
|
||||
return any(_entry_owner(entry) for entry in entries if isinstance(entry, dict))
|
||||
|
||||
|
||||
def _scope_entries() -> tuple[str | None, list[dict], list[dict], str | None]:
|
||||
"""Return configured owner, all entries, visible entries, and optional error."""
|
||||
entries = _memory_manager.load_all()
|
||||
owner = _configured_owner()
|
||||
if owner is None and _owner_scoped_store(entries):
|
||||
return None, entries, [], _OWNER_SCOPE_ERROR
|
||||
if owner is None:
|
||||
visible = [
|
||||
entry for entry in entries
|
||||
if isinstance(entry, dict) and _entry_owner(entry) is None
|
||||
]
|
||||
else:
|
||||
visible = [
|
||||
entry for entry in entries
|
||||
if isinstance(entry, dict) and _entry_owner(entry) == owner
|
||||
]
|
||||
return owner, entries, visible, None
|
||||
|
||||
|
||||
def _text_result(text: str) -> list[TextContent]:
|
||||
return [TextContent(type="text", text=text)]
|
||||
|
||||
|
||||
def _ensure_init():
|
||||
"""Lazy-init memory managers on first use."""
|
||||
@@ -75,24 +125,26 @@ async def list_tools() -> list[Tool]:
|
||||
@server.call_tool()
|
||||
async def call_tool(name: str, arguments: dict) -> list[TextContent]:
|
||||
if name != "manage_memory":
|
||||
return [TextContent(type="text", text=f"Unknown tool: {name}")]
|
||||
return _text_result(f"Unknown tool: {name}")
|
||||
|
||||
_ensure_init()
|
||||
if not _memory_manager:
|
||||
return [TextContent(type="text", text="Error: Memory manager not available")]
|
||||
return _text_result("Error: Memory manager not available")
|
||||
|
||||
action = arguments.get("action", "")
|
||||
|
||||
if action == "list":
|
||||
category_filter = arguments.get("category", "")
|
||||
memories = _memory_manager.load()
|
||||
_owner, _all_memories, memories, scope_error = _scope_entries()
|
||||
if scope_error:
|
||||
return _text_result(scope_error)
|
||||
if category_filter:
|
||||
memories = [m for m in memories if m.get("category", "").lower() == category_filter.lower()]
|
||||
if not memories:
|
||||
msg = "No memories found"
|
||||
if category_filter:
|
||||
msg += f" in category '{category_filter}'"
|
||||
return [TextContent(type="text", text=msg + ".")]
|
||||
return _text_result(msg + ".")
|
||||
|
||||
lines = [f"Found {len(memories)} memory entries:\n"]
|
||||
for m in memories:
|
||||
@@ -102,15 +154,17 @@ async def call_tool(name: str, arguments: dict) -> list[TextContent]:
|
||||
if len(text) > 150:
|
||||
text = text[:150] + "..."
|
||||
lines.append(f"- [{cat}] `{mid}` — {text}")
|
||||
return [TextContent(type="text", text="\n".join(lines))]
|
||||
return _text_result("\n".join(lines))
|
||||
|
||||
elif action == "add":
|
||||
text = arguments.get("text", "")
|
||||
category = arguments.get("category", "fact")
|
||||
if not text:
|
||||
return [TextContent(type="text", text="Error: Memory text cannot be empty")]
|
||||
entry = _memory_manager.add_entry(text, source="ai_agent", category=category)
|
||||
memories = _memory_manager.load_all()
|
||||
return _text_result("Error: Memory text cannot be empty")
|
||||
owner, memories, _visible, scope_error = _scope_entries()
|
||||
if scope_error:
|
||||
return _text_result(scope_error)
|
||||
entry = _memory_manager.add_entry(text, source="ai_agent", category=category, owner=owner)
|
||||
memories.append(entry)
|
||||
_memory_manager.save(memories)
|
||||
if _memory_vector and _memory_vector.healthy:
|
||||
@@ -118,25 +172,28 @@ async def call_tool(name: str, arguments: dict) -> list[TextContent]:
|
||||
_memory_vector.add(entry["id"], text)
|
||||
except Exception:
|
||||
pass
|
||||
return [TextContent(type="text", text=f"Memory added: [{category}] {text} (id: {entry['id'][:8]})")]
|
||||
return _text_result(f"Memory added: [{category}] {text} (id: {entry['id'][:8]})")
|
||||
|
||||
elif action == "edit":
|
||||
memory_id = arguments.get("memory_id", "")
|
||||
new_text = arguments.get("text", "")
|
||||
if not memory_id or not new_text:
|
||||
return [TextContent(type="text", text="Error: edit needs memory_id and text")]
|
||||
memories = _memory_manager.load_all()
|
||||
found = False
|
||||
return _text_result("Error: edit needs memory_id and text")
|
||||
_owner, memories, visible, scope_error = _scope_entries()
|
||||
if scope_error:
|
||||
return _text_result(scope_error)
|
||||
full_id = None
|
||||
for m in memories:
|
||||
for m in visible:
|
||||
if m.get("id", "").startswith(memory_id):
|
||||
m["text"] = new_text
|
||||
m["timestamp"] = int(time.time())
|
||||
found = True
|
||||
full_id = m["id"]
|
||||
break
|
||||
if not found:
|
||||
return [TextContent(type="text", text=f"Error: Memory '{memory_id}' not found")]
|
||||
if not full_id:
|
||||
return _text_result(f"Error: Memory '{memory_id}' not found")
|
||||
for m in memories:
|
||||
if m.get("id") == full_id:
|
||||
m["text"] = new_text
|
||||
m["timestamp"] = int(time.time())
|
||||
break
|
||||
_memory_manager.save(memories)
|
||||
if _memory_vector and _memory_vector.healthy and full_id:
|
||||
try:
|
||||
@@ -144,24 +201,26 @@ async def call_tool(name: str, arguments: dict) -> list[TextContent]:
|
||||
_memory_vector.add(full_id, new_text)
|
||||
except Exception:
|
||||
pass
|
||||
return [TextContent(type="text", text=f"Memory updated: {new_text}")]
|
||||
return _text_result(f"Memory updated: {new_text}")
|
||||
|
||||
elif action == "delete":
|
||||
memory_id = arguments.get("memory_id", "")
|
||||
if not memory_id:
|
||||
return [TextContent(type="text", text="Error: delete needs memory_id")]
|
||||
memories = _memory_manager.load_all()
|
||||
return _text_result("Error: delete needs memory_id")
|
||||
_owner, memories, visible, scope_error = _scope_entries()
|
||||
if scope_error:
|
||||
return _text_result(scope_error)
|
||||
full_id = None
|
||||
deleted_text = ""
|
||||
deleted_category = ""
|
||||
for m in memories:
|
||||
for m in visible:
|
||||
if m.get("id", "").startswith(memory_id):
|
||||
full_id = m["id"]
|
||||
deleted_text = m.get("text", "")
|
||||
deleted_category = m.get("category", "")
|
||||
break
|
||||
if not full_id:
|
||||
return [TextContent(type="text", text=f"Error: Memory '{memory_id}' not found")]
|
||||
return _text_result(f"Error: Memory '{memory_id}' not found")
|
||||
memories = [m for m in memories if m.get("id") != full_id]
|
||||
_memory_manager.save(memories)
|
||||
if _memory_vector and _memory_vector.healthy and full_id:
|
||||
@@ -171,30 +230,32 @@ async def call_tool(name: str, arguments: dict) -> list[TextContent]:
|
||||
pass
|
||||
cat = f"[{deleted_category}] " if deleted_category else ""
|
||||
snippet = deleted_text if len(deleted_text) <= 120 else deleted_text[:117] + "..."
|
||||
return [TextContent(type="text", text=f"Memory deleted: {cat}{snippet} (id: {memory_id})")]
|
||||
return _text_result(f"Memory deleted: {cat}{snippet} (id: {memory_id})")
|
||||
|
||||
elif action == "search":
|
||||
query = arguments.get("text", "")
|
||||
if not query:
|
||||
return [TextContent(type="text", text="Error: search needs text (query)")]
|
||||
memories = _memory_manager.load()
|
||||
return _text_result("Error: search needs text (query)")
|
||||
_owner, _all_memories, memories, scope_error = _scope_entries()
|
||||
if scope_error:
|
||||
return _text_result(scope_error)
|
||||
if hasattr(_memory_manager, 'get_relevant_memories'):
|
||||
results = _memory_manager.get_relevant_memories(query, memories, threshold=0.05, max_items=20)
|
||||
else:
|
||||
query_lower = query.lower()
|
||||
results = [m for m in memories if query_lower in m.get("text", "").lower()][:20]
|
||||
if not results:
|
||||
return [TextContent(type="text", text=f"No memories found matching '{query}'.")]
|
||||
return _text_result(f"No memories found matching '{query}'.")
|
||||
lines = [f"Found {len(results)} matching memories:\n"]
|
||||
for m in results:
|
||||
cat = m.get("category", "fact")
|
||||
mid = m.get("id", "?")[:8]
|
||||
text = m.get("text", "")
|
||||
lines.append(f"- [{cat}] `{mid}` — {text}")
|
||||
return [TextContent(type="text", text="\n".join(lines))]
|
||||
return _text_result("\n".join(lines))
|
||||
|
||||
else:
|
||||
return [TextContent(type="text", text=f"Error: Unknown action '{action}'. Use: list, add, edit, delete, search")]
|
||||
return _text_result(f"Error: Unknown action '{action}'. Use: list, add, edit, delete, search")
|
||||
|
||||
|
||||
async def run():
|
||||
|
||||
@@ -4,93 +4,19 @@
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sdk": "^0.104.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@antithesishq/bombadil": "^0.5.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@anthropic-ai/sdk": {
|
||||
"version": "0.104.1",
|
||||
"resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.104.1.tgz",
|
||||
"integrity": "sha512-gGACa/+IaiXzRRmF96aOhamoBgapKRBiFWbmmTFP8aMkpaEcuStF+Q61bjo4vPxBM7gqWJNZqsngslRdnLHv0Q==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"json-schema-to-ts": "^3.1.1",
|
||||
"standardwebhooks": "^1.0.0"
|
||||
},
|
||||
"bin": {
|
||||
"anthropic-ai-sdk": "bin/cli"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"zod": "^3.25.0 || ^4.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"zod": {
|
||||
"optional": true
|
||||
}
|
||||
"@antithesishq/bombadil": "^0.6.1"
|
||||
}
|
||||
},
|
||||
"node_modules/@antithesishq/bombadil": {
|
||||
"version": "0.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@antithesishq/bombadil/-/bombadil-0.5.0.tgz",
|
||||
"integrity": "sha512-s0zImmr0iyvSP6QcVLvf40CUiZYIdWBAxiq20uhzujwvfitYa3PGJN652k/pLtVccHM/JrGQxZdvLnihZpltHA==",
|
||||
"version": "0.6.1",
|
||||
"resolved": "https://registry.npmjs.org/@antithesishq/bombadil/-/bombadil-0.6.1.tgz",
|
||||
"integrity": "sha512-d1iufG3MI7gSMSiSmMeNdcMW+qR0yQXL2zdkVynC3n3DYgFJYlYXKUQzygmqU12m4RWlR5iOdQU1hsx5UT6+IA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"bombadil": "bin/bombadil.js"
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/runtime": {
|
||||
"version": "7.29.7",
|
||||
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.7.tgz",
|
||||
"integrity": "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6.9.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@stablelib/base64": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz",
|
||||
"integrity": "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/fast-sha256": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz",
|
||||
"integrity": "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==",
|
||||
"license": "Unlicense"
|
||||
},
|
||||
"node_modules/json-schema-to-ts": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz",
|
||||
"integrity": "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.18.3",
|
||||
"ts-algebra": "^2.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
}
|
||||
},
|
||||
"node_modules/standardwebhooks": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/standardwebhooks/-/standardwebhooks-1.0.0.tgz",
|
||||
"integrity": "sha512-BbHGOQK9olHPMvQNHWul6MYlrRTAOKn03rOe4A8O3CLWhNf4YHBqq2HJKKC+sfqpxiBY52pNeesD6jIiLDz8jg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@stablelib/base64": "^1.0.0",
|
||||
"fast-sha256": "^1.3.0"
|
||||
}
|
||||
},
|
||||
"node_modules/ts-algebra": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz",
|
||||
"integrity": "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==",
|
||||
"license": "MIT"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,9 +4,6 @@
|
||||
"url": "https://github.com/pewdiepie-archdaemon/odysseus.git"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@antithesishq/bombadil": "^0.5.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sdk": "^0.104.1"
|
||||
"@antithesishq/bombadil": "^0.6.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,6 +31,7 @@ ALLOWED_SCOPES = {
|
||||
TOKEN_PROFILES = {
|
||||
"chat": ["chat"],
|
||||
"codex_todos": ["todos:read", "todos:write"],
|
||||
"codex_documents": ["documents:read", "documents:write"],
|
||||
"codex_email_drafts": ["email:read", "email:draft", "documents:read", "documents:write"],
|
||||
}
|
||||
|
||||
@@ -159,6 +160,8 @@ def setup_api_token_routes() -> APIRouter:
|
||||
payload = await request.json()
|
||||
except Exception:
|
||||
payload = {}
|
||||
if not isinstance(payload, dict):
|
||||
payload = {}
|
||||
with get_db_session() as db:
|
||||
token = db.query(ApiToken).filter(ApiToken.id == token_id).first()
|
||||
if not token:
|
||||
|
||||
@@ -16,6 +16,7 @@ from pydantic import BaseModel
|
||||
|
||||
from core.database import SessionLocal, CrewMember, ScheduledTask
|
||||
from src.auth_helpers import get_current_user
|
||||
from core.auth import RESERVED_USERNAMES
|
||||
from src.task_scheduler import compute_next_run
|
||||
|
||||
|
||||
@@ -89,11 +90,11 @@ def setup_assistant_routes(task_scheduler) -> APIRouter:
|
||||
# check-in tasks seeded. Hitting any /assistant route under one of these
|
||||
# used to seed a full CrewMember + Morning/Midday/Evening tasks under that
|
||||
# owner, which then double-fired alongside the real user's check-ins.
|
||||
_SYNTHETIC_OWNERS = frozenset({"internal-tool", "api", "demo", "system", ""})
|
||||
# RESERVED_USERNAMES covers the same set; the `not owner` guard handles "".
|
||||
|
||||
async def _get_or_create(owner: str) -> CrewMember:
|
||||
"""Return the per-owner assistant CrewMember, creating it on demand."""
|
||||
if not owner or owner in _SYNTHETIC_OWNERS:
|
||||
if not owner or owner in RESERVED_USERNAMES:
|
||||
raise HTTPException(status_code=400, detail=f"Cannot seed assistant for {owner!r}")
|
||||
db = SessionLocal()
|
||||
try:
|
||||
|
||||
@@ -12,8 +12,8 @@ import re
|
||||
from pathlib import Path
|
||||
|
||||
from core.atomic_io import atomic_write_json, atomic_write_text
|
||||
from core.auth import AuthManager, SetAdminResult
|
||||
from src.constants import DEEP_RESEARCH_DIR, MEMORY_FILE, SKILLS_DIR
|
||||
from core.auth import AuthManager, RESERVED_USERNAMES, SetAdminResult, TOKEN_TTL
|
||||
from src.constants import DEEP_RESEARCH_DIR, MEMORY_FILE, PASSWORD_MIN_LENGTH, SKILLS_DIR
|
||||
from src.rate_limiter import RateLimiter
|
||||
from src.settings_scrub import scrub_settings
|
||||
from src.settings import (
|
||||
@@ -102,8 +102,12 @@ def setup_auth_routes(auth_manager: AuthManager) -> APIRouter:
|
||||
raise HTTPException(429, "Too many requests — try again later")
|
||||
if auth_manager.is_configured:
|
||||
raise HTTPException(400, "Already configured")
|
||||
if len(body.password) < 8:
|
||||
raise HTTPException(400, "Password must be at least 8 characters")
|
||||
if len(body.password) < PASSWORD_MIN_LENGTH:
|
||||
raise HTTPException(400, f"Password must be at least {PASSWORD_MIN_LENGTH} characters")
|
||||
if len(body.username.strip()) < 1:
|
||||
raise HTTPException(400, "Username is required")
|
||||
if body.username.lower() in RESERVED_USERNAMES:
|
||||
raise HTTPException(403, "Username is reserved")
|
||||
ok = await asyncio.to_thread(auth_manager.setup, body.username, body.password)
|
||||
if not ok:
|
||||
raise HTTPException(500, "Setup failed")
|
||||
@@ -118,10 +122,12 @@ def setup_auth_routes(auth_manager: AuthManager) -> APIRouter:
|
||||
raise HTTPException(400, "Run setup first")
|
||||
if not auth_manager.signup_enabled:
|
||||
raise HTTPException(403, "Registration is disabled. Ask an admin for an account.")
|
||||
if len(body.password) < 8:
|
||||
raise HTTPException(400, "Password must be at least 8 characters")
|
||||
if len(body.password) < PASSWORD_MIN_LENGTH:
|
||||
raise HTTPException(400, f"Password must be at least {PASSWORD_MIN_LENGTH} characters")
|
||||
if len(body.username.strip()) < 1:
|
||||
raise HTTPException(400, "Username is required")
|
||||
if body.username.lower() in RESERVED_USERNAMES:
|
||||
raise HTTPException(403, "Username is reserved")
|
||||
ok = await asyncio.to_thread(auth_manager.create_user, body.username, body.password, is_admin=False)
|
||||
if not ok:
|
||||
raise HTTPException(409, "Username already taken")
|
||||
@@ -144,6 +150,8 @@ def setup_auth_routes(auth_manager: AuthManager) -> APIRouter:
|
||||
raise HTTPException(401, "Invalid 2FA code")
|
||||
# All checks passed — create session (password already verified above)
|
||||
token = await asyncio.to_thread(auth_manager.create_session_trusted, username)
|
||||
if not token:
|
||||
raise HTTPException(401, "Invalid credentials")
|
||||
cookie_kwargs = dict(
|
||||
key=SESSION_COOKIE,
|
||||
value=token,
|
||||
@@ -153,7 +161,7 @@ def setup_auth_routes(auth_manager: AuthManager) -> APIRouter:
|
||||
path="/",
|
||||
)
|
||||
if body.remember:
|
||||
cookie_kwargs["max_age"] = 60 * 60 * 24 * 7 # 7 days
|
||||
cookie_kwargs["max_age"] = TOKEN_TTL
|
||||
response.set_cookie(**cookie_kwargs)
|
||||
return {"ok": True, "username": username}
|
||||
|
||||
@@ -182,13 +190,18 @@ def setup_auth_routes(auth_manager: AuthManager) -> APIRouter:
|
||||
pass
|
||||
return result
|
||||
|
||||
@router.get("/policy")
|
||||
async def auth_policy():
|
||||
"""Return public auth policy constants for the frontend."""
|
||||
return auth_manager.policy()
|
||||
|
||||
@router.post("/change-password")
|
||||
async def change_password(body: ChangePasswordRequest, request: Request):
|
||||
user = _get_current_user(request)
|
||||
if not user:
|
||||
raise HTTPException(401, "Not authenticated")
|
||||
if len(body.new_password) < 8:
|
||||
raise HTTPException(400, "Password must be at least 8 characters")
|
||||
if len(body.new_password) < PASSWORD_MIN_LENGTH:
|
||||
raise HTTPException(400, f"Password must be at least {PASSWORD_MIN_LENGTH} characters")
|
||||
current_token = request.cookies.get(SESSION_COOKIE)
|
||||
ok = await asyncio.to_thread(auth_manager.change_password, user, body.current_password, body.new_password)
|
||||
if not ok:
|
||||
@@ -268,8 +281,12 @@ def setup_auth_routes(auth_manager: AuthManager) -> APIRouter:
|
||||
user = _get_current_user(request)
|
||||
if not user or not auth_manager.is_admin(user):
|
||||
raise HTTPException(403, "Admin only")
|
||||
if len(body.password) < 8:
|
||||
raise HTTPException(400, "Password must be at least 8 characters")
|
||||
if len(body.password) < PASSWORD_MIN_LENGTH:
|
||||
raise HTTPException(400, f"Password must be at least {PASSWORD_MIN_LENGTH} characters")
|
||||
if len(body.username.strip()) < 1:
|
||||
raise HTTPException(400, "Username is required")
|
||||
if body.username.lower() in RESERVED_USERNAMES:
|
||||
raise HTTPException(403, "Username is reserved")
|
||||
ok = auth_manager.create_user(body.username, body.password, body.is_admin)
|
||||
if not ok:
|
||||
raise HTTPException(409, "Username already taken")
|
||||
@@ -432,6 +449,23 @@ def setup_auth_routes(auth_manager: AuthManager) -> APIRouter:
|
||||
except Exception as e:
|
||||
logger.warning("Failed to rename upload owner references %s -> %s: %s", old_username, new_username, e)
|
||||
|
||||
# direct personal RAG uploads live in per-owner directories and the
|
||||
# vector metadata also carries the username used for owner-filtered
|
||||
# search. Keep both in sync with the auth rename.
|
||||
try:
|
||||
from routes.personal_routes import rename_personal_upload_owner
|
||||
personal_docs_manager = getattr(request.app.state, "personal_docs_manager", None)
|
||||
if personal_docs_manager is not None:
|
||||
rag_manager = getattr(personal_docs_manager, "rag_manager", None)
|
||||
rename_personal_upload_owner(
|
||||
old_username,
|
||||
new_username,
|
||||
personal_docs_manager=personal_docs_manager,
|
||||
rag_manager=rag_manager,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning("Failed to rename personal RAG upload owner references %s -> %s: %s", old_username, new_username, e)
|
||||
|
||||
# skills: SKILL.md frontmatter carries owner: <username>; the usage
|
||||
# sidecar (_usage.json) keys entries as owner::skill-name. Both must
|
||||
# be updated or the renamed user's Skills panel goes empty.
|
||||
|
||||
@@ -14,7 +14,7 @@ from core.database import Session as DBSession, ModelEndpoint
|
||||
from src.llm_core import normalize_model_id
|
||||
from src.endpoint_resolver import normalize_base
|
||||
from src.context_compactor import maybe_compact, trim_for_context
|
||||
from src.auth_helpers import get_current_user
|
||||
from src.auth_helpers import effective_user
|
||||
from src.prompt_security import untrusted_context_message
|
||||
from routes.prefs_routes import _load_for_user as load_prefs_for_user
|
||||
|
||||
@@ -23,6 +23,22 @@ from fastapi import HTTPException
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# Strong references to in-flight fire-and-forget tasks scheduled from this
|
||||
# module. asyncio only keeps weak references to tasks created via
|
||||
# create_task, so without this the GC can collect a task mid-execution and
|
||||
# the background work (extraction, auto-naming) silently never runs.
|
||||
# Mirrors WebhookManager._spawn_tracked from src/webhook_manager.py.
|
||||
_BG_TASKS: set[asyncio.Task] = set()
|
||||
|
||||
|
||||
def _spawn_bg(coro) -> asyncio.Task:
|
||||
"""Schedule a background task and hold a strong reference until it finishes."""
|
||||
task = asyncio.create_task(coro)
|
||||
_BG_TASKS.add(task)
|
||||
task.add_done_callback(_BG_TASKS.discard)
|
||||
return task
|
||||
|
||||
|
||||
# ── Data containers ────────────────────────────────────────────────────── #
|
||||
|
||||
@dataclass
|
||||
@@ -78,7 +94,7 @@ def _enforce_chat_privileges(request, sess) -> None:
|
||||
which means unrestricted allowed_models / zero cap -> no-op for them.
|
||||
"""
|
||||
try:
|
||||
user = get_current_user(request)
|
||||
user = effective_user(request)
|
||||
except Exception:
|
||||
user = None
|
||||
if not user:
|
||||
@@ -159,17 +175,9 @@ async def auto_name_session(session_manager, sess):
|
||||
return
|
||||
|
||||
owner = getattr(sess, "owner", None)
|
||||
t_url, t_model, t_headers = resolve_task_endpoint(owner=owner)
|
||||
if not t_model:
|
||||
# If no task/utility model is configured at all, fall back to
|
||||
# the session's own model so auto-naming still works even on
|
||||
# minimal setups.
|
||||
from src.endpoint_resolver import resolve_endpoint
|
||||
_fallback = resolve_endpoint("default", owner=owner)
|
||||
if _fallback and _fallback[1]:
|
||||
t_url, t_model, t_headers = _fallback
|
||||
else:
|
||||
t_url, t_model, t_headers = sess.endpoint_url, sess.model, sess.headers
|
||||
t_url, t_model, t_headers = resolve_task_endpoint(
|
||||
sess.endpoint_url, sess.model, sess.headers, owner=owner
|
||||
)
|
||||
if not t_model:
|
||||
logger.debug("[auto-name] No model provided, skipping")
|
||||
return
|
||||
@@ -346,11 +354,11 @@ def add_user_message(sess, chat_handler, preprocessed: PreprocessedMessage, inco
|
||||
def fire_message_event(request, webhook_manager, session_id: str, sess, message: str, compare_mode: bool = False):
|
||||
"""Fire webhook and event_bus events for a new user message."""
|
||||
if webhook_manager and not compare_mode:
|
||||
asyncio.create_task(webhook_manager.fire("chat.message", {
|
||||
webhook_manager.fire_and_forget("chat.message", {
|
||||
"session_id": session_id, "model": sess.model, "message": message[:2000],
|
||||
}))
|
||||
})
|
||||
from src.event_bus import fire_event
|
||||
user = get_current_user(request)
|
||||
user = effective_user(request)
|
||||
fire_event("message_sent", user)
|
||||
|
||||
|
||||
@@ -576,8 +584,9 @@ async def build_chat_context(
|
||||
if not incognito:
|
||||
fire_message_event(request, webhook_manager, session_id, sess, message, compare_mode)
|
||||
|
||||
# Resolve user prefs
|
||||
user = get_current_user(request)
|
||||
# Resolve owner-scoped prefs/context. Browser requests keep the cookie user;
|
||||
# bearer-token chat requests use the token owner instead of the "api" sentinel.
|
||||
user = effective_user(request)
|
||||
uprefs = load_prefs_for_user(user)
|
||||
|
||||
# Memory enabled?
|
||||
@@ -1112,7 +1121,7 @@ def run_post_response_tasks(
|
||||
)))
|
||||
|
||||
if _extraction_jobs:
|
||||
asyncio.create_task(_run_extraction_jobs_sequentially(session_id, _extraction_jobs))
|
||||
_spawn_bg(_run_extraction_jobs_sequentially(session_id, _extraction_jobs))
|
||||
|
||||
# Token accumulation
|
||||
if last_metrics:
|
||||
@@ -1120,11 +1129,11 @@ def run_post_response_tasks(
|
||||
|
||||
# Webhook
|
||||
if webhook_manager and not compare_mode:
|
||||
asyncio.create_task(webhook_manager.fire("chat.completed", {
|
||||
webhook_manager.fire_and_forget("chat.completed", {
|
||||
"session_id": session_id, "model": sess.model,
|
||||
"user_message": message, "response": full_response[:2000],
|
||||
}))
|
||||
})
|
||||
|
||||
# Auto-name
|
||||
if needs_auto_name(sess.name):
|
||||
asyncio.create_task(auto_name_session(session_manager, sess))
|
||||
_spawn_bg(auto_name_session(session_manager, sess))
|
||||
|
||||
@@ -6,7 +6,7 @@ import os
|
||||
import time
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from typing import Dict, Any, AsyncGenerator, List
|
||||
from typing import Dict, Any, AsyncGenerator, List, Optional
|
||||
|
||||
from fastapi import APIRouter, Request, HTTPException, Form, Query
|
||||
from fastapi.responses import StreamingResponse
|
||||
@@ -23,7 +23,7 @@ from src.endpoint_resolver import normalize_base as _normalize_base, build_chat_
|
||||
from src.session_search import search_session_messages
|
||||
from src.prompt_security import untrusted_context_message
|
||||
from core.exceptions import SessionNotFoundError
|
||||
from src.auth_helpers import get_current_user
|
||||
from src.auth_helpers import effective_user, get_current_user
|
||||
from routes.session_routes import _verify_session_owner
|
||||
from routes.document_helpers import _owner_session_filter
|
||||
from core.database import SessionLocal, get_session_mode, set_session_mode
|
||||
@@ -126,7 +126,8 @@ def _clear_orphaned_session_endpoint(sess, owner: str | None = None) -> bool:
|
||||
sess.model = ""
|
||||
sess.headers = {}
|
||||
return True
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
logger.warning("Failed to clear orphaned session endpoint", exc_info=e)
|
||||
db.rollback()
|
||||
return False
|
||||
finally:
|
||||
@@ -144,7 +145,8 @@ def _endpoint_cache_contains_model(endpoint, model: str) -> bool:
|
||||
return True
|
||||
try:
|
||||
models = json.loads(raw) if isinstance(raw, str) else raw
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
logger.warning("Failed to parse cached models list, treating as containing model", exc_info=e)
|
||||
return True
|
||||
if not isinstance(models, list) or not models:
|
||||
return True
|
||||
@@ -236,7 +238,8 @@ def _recover_empty_session_model(sess, session_id: str, owner: str | None = None
|
||||
is_chatgpt_subscription = False
|
||||
try:
|
||||
cached = json.loads(ep.cached_models) if isinstance(ep.cached_models, str) else (ep.cached_models or [])
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
logger.warning("Failed to parse cached_models for endpoint %r", getattr(ep, "id", "?"), exc_info=e)
|
||||
cached = []
|
||||
if not cached:
|
||||
visible = []
|
||||
@@ -360,7 +363,7 @@ def setup_chat_routes(
|
||||
sess = session_manager.get_session(session)
|
||||
except KeyError:
|
||||
raise HTTPException(404, f"Session '{session}' not found")
|
||||
owner = get_current_user(request)
|
||||
owner = effective_user(request)
|
||||
if _clear_orphaned_session_endpoint(sess, owner=owner):
|
||||
raise HTTPException(400, "Selected model endpoint was removed. Pick another model in Settings.")
|
||||
|
||||
@@ -526,6 +529,66 @@ def setup_chat_routes(
|
||||
active_doc_id = form_data.get("active_doc_id", "").strip()
|
||||
logger.info(f"[doc-inject] chat_mode={chat_mode}, active_doc_id={active_doc_id!r}")
|
||||
|
||||
# Active email reader — when the user has an email open in the UI, the
|
||||
# frontend passes its uid/folder/account so "reply", "summarize this",
|
||||
# etc. resolve to the real email instead of the agent inventing a
|
||||
# fake markdown draft.
|
||||
active_email_uid = form_data.get("active_email_uid", "").strip()
|
||||
active_email_folder = form_data.get("active_email_folder", "INBOX").strip() or "INBOX"
|
||||
active_email_account = form_data.get("active_email_account", "").strip()
|
||||
active_email_ctx: Optional[Dict[str, str]] = None
|
||||
# Always reset between requests so a stale active-email pointer from
|
||||
# a previous turn (different reader closed, different account, etc.)
|
||||
# can't leak in when the user has no email open this turn.
|
||||
try:
|
||||
from src.tool_implementations import clear_active_email
|
||||
clear_active_email()
|
||||
except Exception:
|
||||
pass
|
||||
if active_email_uid:
|
||||
active_email_ctx = {
|
||||
"uid": active_email_uid,
|
||||
"folder": active_email_folder,
|
||||
"account": active_email_account,
|
||||
}
|
||||
# Try to enrich with subject + from so the agent's system prompt
|
||||
# block can quote them. Best-effort: a stale cache is fine, a
|
||||
# missing email just means we pass uid/folder/account only.
|
||||
try:
|
||||
from routes.email_routes import _read_cache_get, _read_cache_key
|
||||
_ck = _read_cache_key(active_email_account or None, active_email_folder, active_email_uid, owner=get_current_user(request))
|
||||
_cached_email = _read_cache_get(_ck)
|
||||
if _cached_email and isinstance(_cached_email, dict):
|
||||
active_email_ctx["subject"] = str(_cached_email.get("subject") or "")
|
||||
active_email_ctx["from"] = str(
|
||||
_cached_email.get("from_address")
|
||||
or _cached_email.get("from")
|
||||
or _cached_email.get("from_name")
|
||||
or ""
|
||||
)
|
||||
_body_preview = (_cached_email.get("body") or "")[:2000]
|
||||
if _body_preview:
|
||||
active_email_ctx["body_preview"] = _body_preview
|
||||
except Exception as _e:
|
||||
logger.debug(f"[email-inject] cache enrich skipped: {_e}")
|
||||
# Stash so email tools can resolve "this email" without UID guessing.
|
||||
try:
|
||||
from src.tool_implementations import set_active_email
|
||||
set_active_email(
|
||||
uid=active_email_uid,
|
||||
folder=active_email_folder,
|
||||
account=active_email_account or None,
|
||||
subject=active_email_ctx.get("subject"),
|
||||
sender=active_email_ctx.get("from"),
|
||||
)
|
||||
except Exception as _e:
|
||||
logger.debug(f"[email-inject] set_active_email failed: {_e}")
|
||||
logger.info(
|
||||
"[email-inject] active_email uid=%s folder=%s account=%s subject=%r",
|
||||
active_email_uid, active_email_folder, active_email_account or "(default)",
|
||||
active_email_ctx.get("subject", ""),
|
||||
)
|
||||
|
||||
try:
|
||||
# Attachment-only sends: skip the message-required check when the
|
||||
# user has attached one or more files (the attachment IS the action).
|
||||
@@ -540,7 +603,7 @@ def setup_chat_routes(
|
||||
# but BEFORE loading. Prevents cross-user session hijack.
|
||||
_verify_session_owner(request, session)
|
||||
sess = session_manager.get_session(session)
|
||||
owner = get_current_user(request)
|
||||
owner = effective_user(request)
|
||||
if _clear_orphaned_session_endpoint(sess, owner=owner):
|
||||
raise HTTPException(400, "Selected model endpoint was removed. Pick another model in Settings.")
|
||||
# Issue #587: picker shows a model from the endpoint cache but
|
||||
@@ -571,7 +634,7 @@ def setup_chat_routes(
|
||||
_enforce_chat_privileges(request, sess)
|
||||
|
||||
# Ensure session has auth headers
|
||||
resolve_session_auth(sess, session, owner=get_current_user(request))
|
||||
resolve_session_auth(sess, session, owner=effective_user(request))
|
||||
|
||||
# Check for research_pending BEFORE mode persist overwrites it
|
||||
do_research = str(use_research).lower() == "true"
|
||||
@@ -586,8 +649,8 @@ def setup_chat_routes(
|
||||
elif attachments:
|
||||
try:
|
||||
att_ids = [str(x) for x in json.loads(attachments)]
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
logger.warning("Failed to parse attachments JSON, ignoring attachments", exc_info=e)
|
||||
|
||||
no_memory = str(form_data.get("no_memory", "")).lower() == "true"
|
||||
pre_context_tool_policy = build_effective_tool_policy(
|
||||
@@ -641,15 +704,27 @@ def setup_chat_routes(
|
||||
active_doc_id,
|
||||
)
|
||||
active_doc = None
|
||||
elif doc_session and doc_session != session:
|
||||
logger.warning(
|
||||
"[doc-inject] ignoring stale active_doc_id %s from session %s while in session %s",
|
||||
active_doc_id,
|
||||
doc_session,
|
||||
session,
|
||||
)
|
||||
active_doc = None
|
||||
else:
|
||||
# NOTE: previously dropped the doc when doc.session_id
|
||||
# != current chat session — but that broke the common
|
||||
# case of "open an email draft from one chat, ask a
|
||||
# different chat to write into it". The frontend only
|
||||
# sends active_doc_id for docs currently visible in
|
||||
# the UI, and we already owner-checked above, so trust
|
||||
# the explicit signal. We just log the mismatch and
|
||||
# re-bind the doc to the current session so future
|
||||
# turns find it via the session-fallback path too.
|
||||
if doc_session and doc_session != session:
|
||||
logger.info(
|
||||
"[doc-inject] cross-session active_doc_id %s (was session %s, now %s) — accepting and rebinding",
|
||||
active_doc_id, doc_session, session,
|
||||
)
|
||||
try:
|
||||
active_doc.session_id = session
|
||||
_doc_db.commit()
|
||||
except Exception as _e:
|
||||
_doc_db.rollback()
|
||||
logger.warning(f"[doc-inject] session rebind failed: {_e}")
|
||||
logger.info(f"[doc-inject] found by ID: title={active_doc.title!r}, lang={active_doc.language!r}, is_active={active_doc.is_active}, content_len={len(active_doc.current_content or '')}")
|
||||
else:
|
||||
logger.warning(f"[doc-inject] NOT FOUND by ID {active_doc_id}")
|
||||
@@ -714,6 +789,21 @@ def setup_chat_routes(
|
||||
"manage_skills", # skill presets tied to user
|
||||
})
|
||||
|
||||
# Active email reader open → strip the tools that let the agent
|
||||
# "drift" to a new compose: create_document (writes a fake email-
|
||||
# shaped .md file) and send_email (sends fresh to a recipient the
|
||||
# agent invented). With those gone, the only paths left for "write
|
||||
# email saying X" are ui_control open_email_reply (draft) and
|
||||
# reply_to_email (immediate send) — both of which use the open
|
||||
# email's UID. Code-level enforcement instead of relying on a
|
||||
# prompt rule the model can ignore.
|
||||
if active_email_ctx and active_email_ctx.get("uid"):
|
||||
disabled_tools.update({
|
||||
"create_document",
|
||||
"send_email",
|
||||
"mcp__email__send_email",
|
||||
})
|
||||
|
||||
# Enforce per-user privileges
|
||||
_privs = {}
|
||||
_user = ctx.user
|
||||
@@ -1181,6 +1271,7 @@ def setup_chat_routes(
|
||||
max_rounds=_max_rounds,
|
||||
context_length=ctx.context_length,
|
||||
active_document=active_doc,
|
||||
active_email=active_email_ctx,
|
||||
session_id=session,
|
||||
disabled_tools=disabled_tools if disabled_tools else None,
|
||||
tool_policy=tool_policy,
|
||||
@@ -1394,7 +1485,7 @@ def setup_chat_routes(
|
||||
if not q or not q.strip():
|
||||
return []
|
||||
|
||||
_user = get_current_user(request)
|
||||
_user = effective_user(request)
|
||||
return [
|
||||
result.to_dict()
|
||||
for result in search_session_messages(
|
||||
|
||||
@@ -46,8 +46,12 @@ def _ssh_prefix_for_task(task: dict) -> tuple[str, str]:
|
||||
shell metacharacters in ``remoteHost`` is rejected with 400 rather than
|
||||
injected.
|
||||
"""
|
||||
host = validate_remote_host((task.get("remoteHost") or "").strip() or None) or ""
|
||||
ssh_port = validate_ssh_port((task.get("sshPort") or "").strip() or None) or ""
|
||||
raw_host = task.get("remoteHost")
|
||||
raw_port = task.get("sshPort")
|
||||
host_value = str(raw_host).strip() if raw_host is not None else None
|
||||
port_value = str(raw_port).strip() if raw_port is not None else None
|
||||
host = validate_remote_host(host_value or None) or ""
|
||||
ssh_port = validate_ssh_port(port_value or None) or ""
|
||||
port_flag = f"-p {ssh_port} " if ssh_port and ssh_port != "22" else ""
|
||||
return host, port_flag
|
||||
|
||||
@@ -91,6 +95,20 @@ def _scope_owner(request: Request, allowed: set[str]) -> str:
|
||||
return require_user(request)
|
||||
|
||||
|
||||
def _scope_owner_all(request: Request, required: set[str]) -> str:
|
||||
"""Return owner only when an API token has every required scope."""
|
||||
if getattr(request.state, "api_token", False):
|
||||
scopes = set(getattr(request.state, "api_token_scopes", []) or [])
|
||||
missing = required - scopes
|
||||
if missing:
|
||||
raise HTTPException(403, f"API token missing required scope: {' and '.join(sorted(missing))}")
|
||||
owner = getattr(request.state, "api_token_owner", None)
|
||||
if not owner:
|
||||
raise HTTPException(403, "API token has no owner")
|
||||
return owner
|
||||
return require_user(request)
|
||||
|
||||
|
||||
def _find_endpoint(router: APIRouter | None, method: str, path: str):
|
||||
if router is None:
|
||||
return None
|
||||
@@ -138,7 +156,7 @@ def setup_codex_routes(
|
||||
"read": scoped(EMAIL_READ_SCOPES),
|
||||
"draft": scoped(EMAIL_DRAFT_SCOPES),
|
||||
"send": scoped(EMAIL_SEND_SCOPES),
|
||||
"actions": ["list", "read", "draft", "send"],
|
||||
"actions": ["list", "read", "draft_document", "draft", "send"],
|
||||
},
|
||||
"memory": {
|
||||
"read": scoped(MEMORY_READ_SCOPES),
|
||||
@@ -262,6 +280,59 @@ def setup_codex_routes(
|
||||
# Both handlers in routes/email_routes.py already accept `owner=` via
|
||||
# FastAPI Depends, so we call them directly without patching state.
|
||||
|
||||
def _email_draft_document_content(body: dict[str, Any]) -> str:
|
||||
def clean(v: Any) -> str:
|
||||
if isinstance(v, list):
|
||||
return ", ".join(str(x).strip() for x in v if str(x).strip())
|
||||
return str(v or "").strip()
|
||||
|
||||
to = clean(body.get("to"))
|
||||
cc = clean(body.get("cc"))
|
||||
bcc = clean(body.get("bcc"))
|
||||
subject = clean(body.get("subject"))
|
||||
in_reply_to = clean(body.get("in_reply_to"))
|
||||
references = clean(body.get("references"))
|
||||
body_text = str(body.get("body") or body.get("body_html") or "").strip()
|
||||
lines = [
|
||||
f"To: {to}",
|
||||
]
|
||||
if cc:
|
||||
lines.append(f"Cc: {cc}")
|
||||
if bcc:
|
||||
lines.append(f"Bcc: {bcc}")
|
||||
lines.append(f"Subject: {subject}")
|
||||
if in_reply_to:
|
||||
lines.append(f"In-Reply-To: {in_reply_to}")
|
||||
if references:
|
||||
lines.append(f"References: {references}")
|
||||
lines.extend(["---", body_text])
|
||||
return "\n".join(lines).rstrip() + "\n"
|
||||
|
||||
@router.post("/emails/draft-document")
|
||||
async def codex_email_draft_document(request: Request, body: dict[str, Any] = Body(default_factory=dict)):
|
||||
owner = _scope_owner(request, EMAIL_DRAFT_SCOPES)
|
||||
docs_owner = _scope_owner_all(request, DOCS_WRITE_SCOPES)
|
||||
if docs_owner != owner:
|
||||
raise HTTPException(403, "API token owner mismatch")
|
||||
if documents_create_endpoint is None:
|
||||
raise HTTPException(503, "Documents integration is not available")
|
||||
from routes.document_routes import DocumentCreate
|
||||
|
||||
subject = str(body.get("subject") or "Email draft").strip() or "Email draft"
|
||||
title = str(body.get("title") or subject).strip() or "Email draft"
|
||||
req = DocumentCreate(
|
||||
session_id=body.get("session_id"),
|
||||
title=title,
|
||||
language="email",
|
||||
content=_email_draft_document_content(body),
|
||||
)
|
||||
result = await _as_owner(request, owner, documents_create_endpoint, request, req)
|
||||
if isinstance(result, dict):
|
||||
result = dict(result)
|
||||
result["draft_type"] = "document"
|
||||
result["send_required_confirmation"] = True
|
||||
return result
|
||||
|
||||
@router.post("/emails/draft")
|
||||
async def codex_email_draft(request: Request, body: dict[str, Any] = Body(default_factory=dict)):
|
||||
owner = _scope_owner(request, EMAIL_DRAFT_SCOPES)
|
||||
@@ -726,7 +797,7 @@ def setup_codex_routes(
|
||||
norm = dict(body or {})
|
||||
sess = (norm.get("tmux_session") or norm.get("session_id") or "").strip()
|
||||
model = (norm.get("model") or norm.get("repo_id") or "").strip()
|
||||
host = (norm.get("host") or norm.get("remote_host") or "").strip()
|
||||
host = validate_remote_host((norm.get("host") or norm.get("remote_host") or "").strip() or None) or ""
|
||||
port = norm.get("port") or 8000
|
||||
import re as _re
|
||||
if not sess or not _re.fullmatch(r"[a-zA-Z0-9_-]+", sess):
|
||||
|
||||
@@ -12,6 +12,7 @@ import json
|
||||
import csv
|
||||
import io
|
||||
import os
|
||||
import inspect
|
||||
import httpx
|
||||
from pathlib import Path
|
||||
from datetime import datetime
|
||||
@@ -90,11 +91,13 @@ def _normalize_contact(contact: Dict) -> Dict:
|
||||
name = str(contact.get("name") or "").strip()
|
||||
if not name and emails:
|
||||
name = emails[0].split("@")[0]
|
||||
address = str(contact.get("address") or "").strip()
|
||||
return {
|
||||
"uid": str(contact.get("uid") or uuid.uuid4()),
|
||||
"name": name,
|
||||
"emails": emails,
|
||||
"phones": phones,
|
||||
"address": address,
|
||||
}
|
||||
|
||||
|
||||
@@ -150,7 +153,7 @@ def _parse_vcards(text: str) -> List[Dict]:
|
||||
for block in re.split(r"BEGIN:VCARD", text):
|
||||
if not block.strip():
|
||||
continue
|
||||
contact = {"name": "", "emails": [], "phones": [], "uid": ""}
|
||||
contact = {"name": "", "emails": [], "phones": [], "uid": "", "address": ""}
|
||||
for line in block.split("\n"):
|
||||
line = line.strip()
|
||||
# Strip an optional RFC 6350 group prefix (e.g. "item1.EMAIL;...")
|
||||
@@ -173,6 +176,15 @@ def _parse_vcards(text: str) -> List[Dict]:
|
||||
phone = _vunesc(name_part.split(":", 1)[1])
|
||||
if phone and phone not in contact["phones"]:
|
||||
contact["phones"].append(phone)
|
||||
elif name_part.startswith("ADR"):
|
||||
# vCard ADR is 7 semicolon-separated components:
|
||||
# post-office-box;extended-address;street;locality;region;postal-code;country.
|
||||
# Recover a human-readable string by joining non-empty
|
||||
# components with ", ".
|
||||
if ":" in name_part:
|
||||
raw = name_part.split(":", 1)[1]
|
||||
parts = [_vunesc(p).strip() for p in raw.split(";")]
|
||||
contact["address"] = ", ".join(p for p in parts if p)
|
||||
elif name_part.startswith("UID:"):
|
||||
contact["uid"] = _vunesc(name_part[4:])
|
||||
if contact["name"] or contact["emails"]:
|
||||
@@ -197,7 +209,8 @@ def _vesc(value: str) -> str:
|
||||
|
||||
def _build_vcard(name: str, email: str, uid: Optional[str] = None,
|
||||
emails: Optional[List[str]] = None,
|
||||
phones: Optional[List[str]] = None) -> str:
|
||||
phones: Optional[List[str]] = None,
|
||||
address: Optional[str] = None) -> str:
|
||||
"""Build a vCard. Accepts either a single `email` (legacy callers) or
|
||||
full `emails`/`phones` lists (edit path). The first email is marked
|
||||
PREF=1. All values are RFC-6350-escaped."""
|
||||
@@ -230,6 +243,12 @@ def _build_vcard(name: str, email: str, uid: Optional[str] = None,
|
||||
lines.append(f"EMAIL;PREF=1:{_vesc(em)}" if i == 0 else f"EMAIL:{_vesc(em)}")
|
||||
for ph in phone_list:
|
||||
lines.append(f"TEL:{_vesc(ph)}")
|
||||
# Address: stuff the whole human-readable string into the street
|
||||
# component of ADR. vCard ADR has 7 semicolon-separated components:
|
||||
# post-office-box;extended-address;street;locality;region;postal-code;country.
|
||||
addr = (address or "").strip()
|
||||
if addr:
|
||||
lines.append(f"ADR:;;{_vesc(addr)};;;;")
|
||||
lines.append("END:VCARD")
|
||||
return "\r\n".join(lines) + "\r\n"
|
||||
|
||||
@@ -366,7 +385,7 @@ def _resolve_resource_url(uid: str) -> str:
|
||||
return _lookup() or _vcard_url(uid)
|
||||
|
||||
|
||||
def _create_contact(name: str, email: str) -> bool:
|
||||
def _create_contact(name: str, email: str, address: str = "") -> bool:
|
||||
"""Add a new contact via CardDAV or local contacts."""
|
||||
cfg = _get_carddav_config()
|
||||
if not _carddav_configured(cfg):
|
||||
@@ -375,12 +394,12 @@ def _create_contact(name: str, email: str) -> bool:
|
||||
for c in contacts:
|
||||
if email_l and email_l in [e.lower() for e in c.get("emails", [])]:
|
||||
return True
|
||||
contacts.append(_normalize_contact({"name": name, "emails": [email]}))
|
||||
contacts.append(_normalize_contact({"name": name, "emails": [email], "address": address}))
|
||||
_save_local_contacts(contacts)
|
||||
return True
|
||||
|
||||
contact_uid = str(uuid.uuid4())
|
||||
vcard = _build_vcard(name, email, contact_uid)
|
||||
vcard = _build_vcard(name, email, contact_uid, address=address)
|
||||
try:
|
||||
url = _carddav_base_url(cfg) + "/" + contact_uid + ".vcf"
|
||||
auth = None
|
||||
@@ -613,7 +632,7 @@ def _contacts_to_csv(contacts: List[Dict]) -> str:
|
||||
return out.getvalue()
|
||||
|
||||
|
||||
def _update_contact(uid: str, name: str, emails: List[str], phones: List[str]) -> bool:
|
||||
def _update_contact(uid: str, name: str, emails: List[str], phones: List[str], address: str = "") -> bool:
|
||||
"""Rewrite an existing contact via CardDAV or local contacts."""
|
||||
cfg = _get_carddav_config()
|
||||
if not _carddav_configured(cfg):
|
||||
@@ -622,16 +641,19 @@ def _update_contact(uid: str, name: str, emails: List[str], phones: List[str]) -
|
||||
out = []
|
||||
for c in contacts:
|
||||
if c.get("uid") == uid:
|
||||
out.append(_normalize_contact({"uid": uid, "name": name, "emails": emails, "phones": phones}))
|
||||
# Preserve existing address when caller passes "" (only
|
||||
# updating name/emails/phones, not touching address).
|
||||
addr = address if address else c.get("address", "")
|
||||
out.append(_normalize_contact({"uid": uid, "name": name, "emails": emails, "phones": phones, "address": addr}))
|
||||
found = True
|
||||
else:
|
||||
out.append(c)
|
||||
if not found:
|
||||
out.append(_normalize_contact({"uid": uid, "name": name, "emails": emails, "phones": phones}))
|
||||
out.append(_normalize_contact({"uid": uid, "name": name, "emails": emails, "phones": phones, "address": address}))
|
||||
_save_local_contacts(out)
|
||||
return True
|
||||
|
||||
vcard = _build_vcard(name, "", uid=uid, emails=emails, phones=phones)
|
||||
vcard = _build_vcard(name, "", uid=uid, emails=emails, phones=phones, address=address)
|
||||
# Use the real resource href (handles externally-created contacts whose
|
||||
# filename != UID); falls back to the <uid>.vcf guess.
|
||||
try:
|
||||
@@ -718,16 +740,39 @@ def setup_contacts_routes():
|
||||
"""Add a new contact."""
|
||||
name = (data.get("name") or "").strip()
|
||||
email = (data.get("email") or "").strip()
|
||||
phone = (data.get("phone") or "").strip()
|
||||
address = (data.get("address") or "").strip()
|
||||
if not email:
|
||||
return {"success": False, "error": "Email required"}
|
||||
# Check if already exists
|
||||
contacts = _fetch_contacts()
|
||||
for c in contacts:
|
||||
if email.lower() in [e.lower() for e in c["emails"]]:
|
||||
return {"success": True, "message": "Already exists", "contact": c}
|
||||
# Check if already exists by email
|
||||
if email:
|
||||
contacts = _fetch_contacts()
|
||||
for c in contacts:
|
||||
if email.lower() in [e.lower() for e in c["emails"]]:
|
||||
return {"success": True, "message": "Already exists", "contact": c}
|
||||
if not name:
|
||||
name = email.split("@")[0]
|
||||
ok = _create_contact(name, email)
|
||||
create_params = inspect.signature(_create_contact).parameters
|
||||
if len(create_params) >= 3:
|
||||
ok = _create_contact(name, email, address)
|
||||
else:
|
||||
ok = _create_contact(name, email)
|
||||
# If a phone was provided, do an immediate update to thread it
|
||||
# through (the simple _create_contact signature only takes name +
|
||||
# email + address; phones happen via update).
|
||||
if ok and phone:
|
||||
try:
|
||||
fresh = _fetch_contacts(force=True)
|
||||
created = next((c for c in fresh if name == c.get("name") and (not email or email in c.get("emails", []))), None)
|
||||
if created:
|
||||
_update_contact(
|
||||
created["uid"], name,
|
||||
created.get("emails", []),
|
||||
[phone],
|
||||
address,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return {"success": ok}
|
||||
|
||||
@router.post("/import")
|
||||
@@ -810,7 +855,7 @@ def setup_contacts_routes():
|
||||
# match PUT /{uid} with uid="config".
|
||||
@router.put("/{uid}")
|
||||
async def edit_contact(uid: str, data: dict, _admin: str = Depends(require_admin)):
|
||||
"""Edit an existing contact — name / emails / phones."""
|
||||
"""Edit an existing contact — name / emails / phones / address."""
|
||||
name = (data.get("name") or "").strip()
|
||||
emails = data.get("emails")
|
||||
phones = data.get("phones")
|
||||
@@ -818,11 +863,12 @@ def setup_contacts_routes():
|
||||
emails = [data["email"]]
|
||||
emails = [e.strip() for e in (emails or []) if e and e.strip()]
|
||||
phones = [p.strip() for p in (phones or []) if p and p.strip()]
|
||||
if not name and not emails:
|
||||
return {"success": False, "error": "Name or email required"}
|
||||
address = (data.get("address") or "").strip()
|
||||
if not name and not emails and not address:
|
||||
return {"success": False, "error": "Name, email, or address required"}
|
||||
if not name and emails:
|
||||
name = emails[0].split("@")[0]
|
||||
ok = _update_contact(uid, name, emails, phones)
|
||||
ok = _update_contact(uid, name, emails, phones, address)
|
||||
return {"success": ok}
|
||||
|
||||
@router.delete("/{uid}")
|
||||
|
||||
@@ -505,6 +505,8 @@ def _cached_model_scan_script(model_dirs: list[str] | None = None, add_hf_cache:
|
||||
" if u.startswith('KB'): return int(n * 1024)",
|
||||
" return int(n)",
|
||||
"def scan_ollama():",
|
||||
" if any(m.get('is_ollama') for m in models): return",
|
||||
" if os.name == 'nt' and not os.environ.get('ODYSSEUS_ALLOW_OLLAMA_CLI_SCAN'): return",
|
||||
" if not shutil.which('ollama'): return",
|
||||
" try:",
|
||||
" p = subprocess.run(['ollama', 'list'], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, timeout=6)",
|
||||
@@ -535,8 +537,8 @@ def _cached_model_scan_script(model_dirs: list[str] | None = None, add_hf_cache:
|
||||
" models.append({'repo_id':name,'size_bytes':size_bytes,'nb_files':1,'has_incomplete':False,'path':'ollama','backend':'ollama','is_ollama':True})",
|
||||
" return",
|
||||
"for _hf_cache in hf_cache_paths(): scan_hf(_hf_cache)",
|
||||
"scan_ollama()",
|
||||
"scan_ollama_api()",
|
||||
"scan_ollama()",
|
||||
]
|
||||
for model_dir in model_dirs or []:
|
||||
lines.append(f"scan_dir(os.path.expanduser({model_dir!r}))")
|
||||
|
||||
@@ -676,7 +676,7 @@ def setup_cookbook_routes() -> APIRouter:
|
||||
_spf = f"-p {_port} " if _port and _port != "22" else ""
|
||||
setup_cmd = (
|
||||
f"scp -O {_pf}-q '{runner_path}' {remote}:{remote_runner} && "
|
||||
f"ssh {_spf}{remote} 'chmod +x {remote_runner} && tmux new-session -d -s {session_id} \"./{remote_runner}\"'"
|
||||
f"ssh {_spf}{remote} 'chmod +x {remote_runner} && tmux set-option -g history-limit 100000 2>/dev/null; tmux new-session -d -s {session_id} \"./{remote_runner}\"'"
|
||||
)
|
||||
else:
|
||||
# Local: run hf download in the background (tmux on POSIX, a detached
|
||||
@@ -708,7 +708,7 @@ def setup_cookbook_routes() -> APIRouter:
|
||||
lines.append('exec "${SHELL:-/bin/bash}"')
|
||||
wrapper_script.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
||||
wrapper_script.chmod(0o755)
|
||||
setup_cmd = None if IS_WINDOWS else f"tmux new-session -d -s {session_id} {shlex.quote(str(wrapper_script))}"
|
||||
setup_cmd = None if IS_WINDOWS else f"tmux set-option -g history-limit 100000 2>/dev/null; tmux new-session -d -s {session_id} {shlex.quote(str(wrapper_script))}"
|
||||
|
||||
logger.info(f"Model download: {req.repo_id} (backend={'ollama' if is_ollama_download else 'hf'}, include={req.include}, session={session_id}, remote={remote})")
|
||||
logger.info(f"Download setup_cmd: {setup_cmd}")
|
||||
@@ -984,9 +984,9 @@ def setup_cookbook_routes() -> APIRouter:
|
||||
ssh_args = ["ssh"]
|
||||
if ssh_port and ssh_port != "22":
|
||||
ssh_args.extend(["-p", str(ssh_port)])
|
||||
capture_cmd = ssh_args + [remote, "tmux", "capture-pane", "-t", session_id, "-p", "-S", "-200"]
|
||||
capture_cmd = ssh_args + [remote, "tmux", "capture-pane", "-t", session_id, "-p", "-S", "-2000"]
|
||||
else:
|
||||
capture_cmd = ["tmux", "capture-pane", "-t", session_id, "-p", "-S", "-200"]
|
||||
capture_cmd = ["tmux", "capture-pane", "-t", session_id, "-p", "-S", "-2000"]
|
||||
|
||||
_exit_re = re.compile(r"=== Process exited with code (-?\d+) ===")
|
||||
for wait_s in _waits:
|
||||
@@ -1284,6 +1284,11 @@ def setup_cookbook_routes() -> APIRouter:
|
||||
# LOCAL execution on a native-Windows host never uses tmux (detached
|
||||
# process path below), regardless of the UI-supplied platform.
|
||||
local_windows = IS_WINDOWS and not remote
|
||||
if is_windows and remote and "diffusion_server.py" in req.cmd:
|
||||
raise HTTPException(
|
||||
400,
|
||||
"Remote Windows Diffusers serving is not supported yet; use local Windows or a Linux remote server.",
|
||||
)
|
||||
|
||||
if not is_windows and not local_windows and not await _binary_available("tmux", remote, req.ssh_port):
|
||||
return {
|
||||
@@ -1577,10 +1582,10 @@ def setup_cookbook_routes() -> APIRouter:
|
||||
setup_cmd = (
|
||||
f"{scp_extras}"
|
||||
f"scp -O {_Pf}-q '{runner_path}' {remote}:{remote_runner} && "
|
||||
f"ssh {_pf}{remote} 'chmod +x {remote_runner} && tmux new-session -d -s {session_id} \"./{remote_runner}\"'"
|
||||
f"ssh {_pf}{remote} 'chmod +x {remote_runner} && tmux set-option -g history-limit 100000 2>/dev/null; tmux new-session -d -s {session_id} \"./{remote_runner}\"'"
|
||||
)
|
||||
else:
|
||||
setup_cmd = f"tmux new-session -d -s {session_id} {shlex.quote(str(runner_path))}"
|
||||
setup_cmd = f"tmux set-option -g history-limit 100000 2>/dev/null; tmux new-session -d -s {session_id} {shlex.quote(str(runner_path))}"
|
||||
|
||||
if setup_cmd is None:
|
||||
# LOCAL Windows: launch the bash runner detached; no tmux setup_cmd.
|
||||
@@ -2625,6 +2630,193 @@ def setup_cookbook_routes() -> APIRouter:
|
||||
"error": _ollama_library_cache["error"],
|
||||
}
|
||||
|
||||
# ── vLLM recipe scraper ─────────────────────────────────────────────
|
||||
# Fetches the official YAML recipe for a model from vllm-project/recipes
|
||||
# and normalizes it into a small JSON the frontend can consume. Cached
|
||||
# per-repo so the GitHub raw endpoint isn't hammered.
|
||||
_vllm_recipe_cache: dict[str, tuple[float, dict | None]] = {}
|
||||
# Manifest of all <org>/<model> ids that have a recipe in the upstream
|
||||
# repo. Cheap to fetch (one Git Tree API call), so we cache the whole
|
||||
# set for ~12h. Per-row "does this model have a recipe?" lookups hit
|
||||
# this set instead of doing 912 individual recipe fetches.
|
||||
_vllm_recipe_manifest: dict = {"fetched_at": 0.0, "models": set(), "error": ""}
|
||||
|
||||
@router.get("/api/cookbook/vllm-recipe-manifest")
|
||||
async def vllm_recipe_manifest(refresh: int = 0):
|
||||
"""Return the set of <org>/<model> ids known to have a vLLM recipe.
|
||||
One GitHub Tree API call, 12h cache. The frontend uses this to badge
|
||||
rows in the model list before the user expands them."""
|
||||
import time as _time
|
||||
import httpx as _httpx
|
||||
TTL = 12 * 3600.0
|
||||
now = _time.time()
|
||||
if (
|
||||
refresh
|
||||
or (now - _vllm_recipe_manifest["fetched_at"]) > TTL
|
||||
or not _vllm_recipe_manifest["models"]
|
||||
):
|
||||
url = (
|
||||
"https://api.github.com/repos/vllm-project/recipes/"
|
||||
"git/trees/main?recursive=1"
|
||||
)
|
||||
def _fetch_sync() -> tuple[int, dict | None, str]:
|
||||
try:
|
||||
headers = {"Accept": "application/vnd.github+json"}
|
||||
with _httpx.Client(timeout=10.0, follow_redirects=True) as client:
|
||||
r = client.get(url, headers=headers)
|
||||
if r.status_code != 200:
|
||||
return r.status_code, None, r.text[:200]
|
||||
return 200, r.json(), ""
|
||||
except Exception as e:
|
||||
return 0, None, f"fetch error: {e}"
|
||||
status, data, err = await asyncio.to_thread(_fetch_sync)
|
||||
if status == 200 and isinstance(data, dict):
|
||||
models: set[str] = set()
|
||||
for entry in data.get("tree") or []:
|
||||
path = (entry or {}).get("path") or ""
|
||||
if not path.startswith("models/") or not path.endswith(".yaml"):
|
||||
continue
|
||||
# path = "models/<org>/<model>.yaml" → "<org>/<model>"
|
||||
body = path[len("models/"):-len(".yaml")]
|
||||
if "/" in body:
|
||||
models.add(body)
|
||||
_vllm_recipe_manifest["models"] = models
|
||||
_vllm_recipe_manifest["fetched_at"] = now
|
||||
_vllm_recipe_manifest["error"] = ""
|
||||
else:
|
||||
_vllm_recipe_manifest["error"] = (
|
||||
f"HTTP {status}: {err}" if status else err
|
||||
)
|
||||
# Don't clobber a stale-but-usable list on transient failures.
|
||||
if not _vllm_recipe_manifest["models"]:
|
||||
return {
|
||||
"models": [],
|
||||
"count": 0,
|
||||
"error": _vllm_recipe_manifest["error"],
|
||||
}
|
||||
return {
|
||||
"models": sorted(_vllm_recipe_manifest["models"]),
|
||||
"count": len(_vllm_recipe_manifest["models"]),
|
||||
"fetched_at": _vllm_recipe_manifest["fetched_at"],
|
||||
"error": _vllm_recipe_manifest["error"],
|
||||
}
|
||||
|
||||
@router.get("/api/cookbook/vllm-recipe")
|
||||
async def vllm_recipe(repo: str, refresh: int = 0):
|
||||
"""Return the vLLM official recipe for a HuggingFace repo, if one
|
||||
exists at vllm-project/recipes. `repo` is the full HF id like
|
||||
'MiniMaxAI/MiniMax-M2'. Cached 6h."""
|
||||
import time as _time
|
||||
import httpx as _httpx
|
||||
import yaml as _yaml
|
||||
|
||||
TTL = 6 * 3600.0
|
||||
now = _time.time()
|
||||
repo = (repo or "").strip().strip("/")
|
||||
if "/" not in repo:
|
||||
return {"exists": False, "error": "repo must be <org>/<model>"}
|
||||
|
||||
cached = _vllm_recipe_cache.get(repo)
|
||||
if cached and not refresh and (now - cached[0]) < TTL:
|
||||
return cached[1] or {"exists": False, "cached": True}
|
||||
|
||||
url = (
|
||||
f"https://raw.githubusercontent.com/vllm-project/recipes/"
|
||||
f"main/models/{repo}.yaml"
|
||||
)
|
||||
|
||||
def _fetch_sync() -> tuple[int, str]:
|
||||
try:
|
||||
with _httpx.Client(timeout=8.0, follow_redirects=True) as client:
|
||||
r = client.get(url)
|
||||
return r.status_code, r.text
|
||||
except Exception as e:
|
||||
return 0, f"fetch error: {e}"
|
||||
|
||||
status, text = await asyncio.to_thread(_fetch_sync)
|
||||
if status == 404:
|
||||
_vllm_recipe_cache[repo] = (now, {"exists": False})
|
||||
return {"exists": False}
|
||||
if status != 200:
|
||||
return {"exists": False, "error": f"HTTP {status}", "transient": True}
|
||||
|
||||
try:
|
||||
doc = _yaml.safe_load(text) or {}
|
||||
except Exception as e:
|
||||
return {"exists": False, "error": f"yaml parse: {e}"}
|
||||
|
||||
meta = doc.get("meta") or {}
|
||||
model = doc.get("model") or {}
|
||||
features = doc.get("features") or {}
|
||||
deps = doc.get("dependencies") or []
|
||||
variants = doc.get("variants") or {}
|
||||
hw_overrides = doc.get("hardware_overrides") or {}
|
||||
strat_overrides = doc.get("strategy_overrides") or {}
|
||||
|
||||
# Tool-call + reasoning parsers, as flat arg arrays, so the frontend
|
||||
# can drop them straight into the launch command.
|
||||
tool_calling = features.get("tool_calling") or {}
|
||||
reasoning = features.get("reasoning") or {}
|
||||
|
||||
normalized = {
|
||||
"exists": True,
|
||||
"source_url": url,
|
||||
"title": meta.get("title") or "",
|
||||
"provider": meta.get("provider") or "",
|
||||
"description": meta.get("description") or "",
|
||||
"date_updated": str(meta.get("date_updated") or ""),
|
||||
"hardware_support": meta.get("hardware") or {},
|
||||
"model_id": model.get("model_id") or repo,
|
||||
"min_vllm_version": model.get("min_vllm_version") or "",
|
||||
"architecture": model.get("architecture") or "",
|
||||
"parameter_count": model.get("parameter_count") or "",
|
||||
"active_parameters": model.get("active_parameters") or "",
|
||||
"context_length": model.get("context_length") or 0,
|
||||
"base_args": list(model.get("base_args") or []),
|
||||
"base_env": dict(model.get("base_env") or {}),
|
||||
"tool_calling": {
|
||||
"description": tool_calling.get("description") or "",
|
||||
"args": list(tool_calling.get("args") or []),
|
||||
} if tool_calling else None,
|
||||
"reasoning": {
|
||||
"description": reasoning.get("description") or "",
|
||||
"args": list(reasoning.get("args") or []),
|
||||
} if reasoning else None,
|
||||
"dependencies": [
|
||||
{
|
||||
"note": (d.get("note") or "").strip(),
|
||||
"command": (d.get("command") or "").strip(),
|
||||
"optional": bool(d.get("optional", False)),
|
||||
}
|
||||
for d in deps if isinstance(d, dict)
|
||||
],
|
||||
"variants": {
|
||||
k: {
|
||||
"model_id": v.get("model_id") or model.get("model_id") or repo,
|
||||
"precision": v.get("precision") or "",
|
||||
"vram_minimum_gb": v.get("vram_minimum_gb") or 0,
|
||||
"description": v.get("description") or "",
|
||||
"extra_args": list(v.get("extra_args") or []),
|
||||
"extra_env": dict(v.get("extra_env") or {}),
|
||||
}
|
||||
for k, v in variants.items() if isinstance(v, dict)
|
||||
},
|
||||
"hardware_overrides": {
|
||||
hw: {
|
||||
"extra_args": list((ov or {}).get("extra_args") or []),
|
||||
"extra_env": dict((ov or {}).get("extra_env") or {}),
|
||||
}
|
||||
for hw, ov in hw_overrides.items() if isinstance(ov, dict)
|
||||
},
|
||||
"strategy_overrides": {
|
||||
strat: dict(ov or {})
|
||||
for strat, ov in strat_overrides.items() if isinstance(ov, dict)
|
||||
},
|
||||
"compatible_strategies": list(doc.get("compatible_strategies") or []),
|
||||
}
|
||||
_vllm_recipe_cache[repo] = (now, normalized)
|
||||
return normalized
|
||||
|
||||
@router.get("/api/cookbook/tasks/status")
|
||||
async def cookbook_tasks_status(request: Request):
|
||||
"""Check status of all active cookbook tmux sessions.
|
||||
|
||||
@@ -102,8 +102,11 @@ def _owner_session_filter(q, user):
|
||||
|
||||
The owner backfill runs in init_db before the app serves requests, so
|
||||
by the time this filter is live there are no NULL-owner rows to leak;
|
||||
we therefore match the owner strictly."""
|
||||
if user is None:
|
||||
we therefore match the owner strictly for authenticated callers."""
|
||||
if not user:
|
||||
from src.auth_helpers import _auth_disabled
|
||||
if user == "" or _auth_disabled():
|
||||
return q
|
||||
return q.filter(False)
|
||||
return q.filter(Document.owner == user)
|
||||
|
||||
|
||||
@@ -503,7 +503,8 @@ def setup_document_routes(session_manager, upload_handler=None) -> APIRouter:
|
||||
user = get_current_user(request)
|
||||
try:
|
||||
data = await request.json()
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
logger.warning("Failed to parse export request body, defaulting to empty", exc_info=e)
|
||||
data = {}
|
||||
ids = data.get("ids") or []
|
||||
if not ids:
|
||||
@@ -645,8 +646,8 @@ def setup_document_routes(session_manager, upload_handler=None) -> APIRouter:
|
||||
try:
|
||||
from src.agent_tools.document_tools import clear_active_document
|
||||
clear_active_document(doc_id)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
logger.warning("Failed to clear active document %r on detach", doc_id, exc_info=e)
|
||||
db.commit()
|
||||
db.refresh(doc)
|
||||
return _doc_to_dict(doc)
|
||||
@@ -1331,6 +1332,12 @@ def setup_document_routes(session_manager, upload_handler=None) -> APIRouter:
|
||||
if not pdf_path:
|
||||
raise HTTPException(404, f"Source PDF {upload_id} not found")
|
||||
|
||||
# Fail fast with a clear 503 if the optional PyMuPDF dependency
|
||||
# is missing — fill_fields/stamp_annotations will otherwise
|
||||
# raise RuntimeError deep inside and bubble out as a 500.
|
||||
# Mirrors the convention in _load_pdf_viewer_fitz above.
|
||||
_load_pdf_viewer_fitz()
|
||||
|
||||
values = parse_markdown_to_values(doc.current_content or "")
|
||||
out_path = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False).name
|
||||
_to_unlink.append(out_path)
|
||||
|
||||
@@ -13,6 +13,8 @@ and `email_pollers.py` (the background loops):
|
||||
"""
|
||||
|
||||
import os
|
||||
import base64
|
||||
import time
|
||||
import imaplib
|
||||
import smtplib
|
||||
import email as email_mod
|
||||
@@ -38,6 +40,106 @@ from src.secret_storage import decrypt as _decrypt
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _xoauth2_raw(user: str, access_token: str) -> str:
|
||||
"""The SASL XOAUTH2 initial-response string (unencoded).
|
||||
|
||||
Both smtplib.SMTP.auth() and imaplib.IMAP4.authenticate() base64-encode
|
||||
the value their callback returns, so callers pass this raw form — never
|
||||
pre-encoded — to avoid double base64.
|
||||
"""
|
||||
return f"user={user}\x01auth=Bearer {access_token}\x01\x01"
|
||||
|
||||
|
||||
def _xoauth2_bytes(user: str, access_token: str) -> bytes:
|
||||
"""Raw XOAUTH2 bytes for imaplib's authenticate() callback."""
|
||||
return _xoauth2_raw(user, access_token).encode()
|
||||
|
||||
|
||||
def make_oauth_state(account_id: str, owner: str) -> str:
|
||||
"""Return an HMAC-signed, base64-encoded OAuth state token.
|
||||
|
||||
Encodes account_id + owner + a random nonce, signed with the app secret
|
||||
so the callback can validate that the flow was initiated by an
|
||||
authenticated, owning user (CSRF / state-forgery protection).
|
||||
"""
|
||||
import hmac as _hmac, hashlib as _hl, secrets as _sec
|
||||
from src.secret_storage import _load_or_create_key
|
||||
nonce = _sec.token_hex(16)
|
||||
payload = json.dumps({"a": account_id, "o": owner, "n": nonce}, separators=(",", ":"))
|
||||
sig = _hmac.new(_load_or_create_key(), payload.encode(), _hl.sha256).hexdigest()
|
||||
return base64.urlsafe_b64encode(f"{payload}|{sig}".encode()).decode()
|
||||
|
||||
|
||||
def verify_oauth_state(state: str) -> dict | None:
|
||||
"""Verify an OAuth state token's HMAC signature.
|
||||
|
||||
Returns the decoded payload dict ({"a", "o", "n"}) on success, or None if
|
||||
the token is malformed, tampered, or signed with a different key.
|
||||
"""
|
||||
import hmac as _hmac, hashlib as _hl
|
||||
from src.secret_storage import _load_or_create_key
|
||||
try:
|
||||
decoded = base64.urlsafe_b64decode(state.encode()).decode()
|
||||
payload, sig = decoded.rsplit("|", 1)
|
||||
expected = _hmac.new(_load_or_create_key(), payload.encode(), _hl.sha256).hexdigest()
|
||||
if not _hmac.compare_digest(sig, expected):
|
||||
return None
|
||||
return json.loads(payload)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _refresh_google_token(account_id: str) -> str | None:
|
||||
"""Exchange the stored refresh token for a new access token and persist it."""
|
||||
import httpx
|
||||
from core.database import SessionLocal as _SL, EmailAccount as _EA
|
||||
from src.secret_storage import encrypt as _enc, decrypt as _dec
|
||||
client_id = os.environ.get("GOOGLE_OAUTH_CLIENT_ID", "")
|
||||
client_secret = os.environ.get("GOOGLE_OAUTH_CLIENT_SECRET", "")
|
||||
if not client_id or not client_secret:
|
||||
return None
|
||||
db = _SL()
|
||||
try:
|
||||
row = db.get(_EA, account_id)
|
||||
if not row or not row.oauth_refresh_token:
|
||||
return None
|
||||
refresh_token = _dec(row.oauth_refresh_token or "")
|
||||
if not refresh_token:
|
||||
return None
|
||||
resp = httpx.post("https://oauth2.googleapis.com/token", data={
|
||||
"client_id": client_id,
|
||||
"client_secret": client_secret,
|
||||
"refresh_token": refresh_token,
|
||||
"grant_type": "refresh_token",
|
||||
}, timeout=10)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
access_token = data["access_token"]
|
||||
row.oauth_access_token = _enc(access_token)
|
||||
row.oauth_token_expiry = str(int(time.time()) + data.get("expires_in", 3600))
|
||||
db.commit()
|
||||
return access_token
|
||||
except Exception:
|
||||
logger.warning(f"Google token refresh failed for account {account_id}")
|
||||
return None
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def _get_valid_google_token(account_id: str, cfg: dict) -> str | None:
|
||||
"""Return a valid Google access token, refreshing if expired or missing."""
|
||||
from src.secret_storage import decrypt as _dec
|
||||
access_token = _dec(cfg.get("oauth_access_token") or "")
|
||||
expiry_str = cfg.get("oauth_token_expiry") or ""
|
||||
if access_token and expiry_str:
|
||||
try:
|
||||
if int(expiry_str) - 60 > time.time():
|
||||
return access_token
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
return _refresh_google_token(account_id)
|
||||
|
||||
|
||||
def _smtp_security_mode(cfg: dict) -> str:
|
||||
raw = str(cfg.get("smtp_security") or "").strip().lower()
|
||||
if raw in {"ssl", "starttls", "none"}:
|
||||
@@ -54,20 +156,29 @@ def _send_smtp_message(cfg: dict, from_addr: str, recipients: list[str], message
|
||||
port = int(cfg.get("smtp_port") or 465)
|
||||
user = cfg.get("smtp_user") or ""
|
||||
password = cfg.get("smtp_password") or ""
|
||||
|
||||
def _auth_smtp(smtp):
|
||||
if cfg.get("oauth_provider") == "google":
|
||||
token = _get_valid_google_token(cfg.get("account_id"), cfg)
|
||||
if not token:
|
||||
raise RuntimeError("Google OAuth token unavailable — reconnect the account")
|
||||
smtp.ehlo()
|
||||
smtp.auth("XOAUTH2", lambda challenge=None: _xoauth2_raw(user, token), initial_response_ok=True)
|
||||
elif user and password:
|
||||
smtp.login(user, password)
|
||||
|
||||
security = _smtp_security_mode(cfg)
|
||||
|
||||
if security == "ssl":
|
||||
with smtplib.SMTP_SSL(host, port, timeout=timeout) as smtp:
|
||||
if user and password:
|
||||
smtp.login(user, password)
|
||||
_auth_smtp(smtp)
|
||||
smtp.sendmail(from_addr, recipients, message)
|
||||
return
|
||||
|
||||
with smtplib.SMTP(host, port, timeout=timeout) as smtp:
|
||||
if security == "starttls":
|
||||
smtp.starttls()
|
||||
if user and password:
|
||||
smtp.login(user, password)
|
||||
_auth_smtp(smtp)
|
||||
smtp.sendmail(from_addr, recipients, message)
|
||||
|
||||
|
||||
@@ -701,10 +812,16 @@ def _get_email_config(account_id: str | None = None, owner: str = "") -> dict:
|
||||
"imap_password": _decrypt(row.imap_password or ""),
|
||||
"imap_starttls": bool(row.imap_starttls),
|
||||
"from_address": row.from_address or row.imap_user or "",
|
||||
"oauth_provider": row.oauth_provider or "",
|
||||
"oauth_access_token": row.oauth_access_token or "",
|
||||
"oauth_refresh_token": row.oauth_refresh_token or "",
|
||||
"oauth_token_expiry": row.oauth_token_expiry or "",
|
||||
"display_name": row.display_name or "",
|
||||
}
|
||||
if not (cfg["smtp_host"] and cfg["smtp_user"] and cfg["smtp_password"]):
|
||||
is_oauth = bool(cfg.get("oauth_provider"))
|
||||
if not is_oauth and not (cfg["smtp_host"] and cfg["smtp_user"] and cfg["smtp_password"]):
|
||||
logger.warning(f"SMTP not configured for account {row.name!r}")
|
||||
if not (cfg["imap_host"] and cfg["imap_user"] and cfg["imap_password"]):
|
||||
if not is_oauth and not (cfg["imap_host"] and cfg["imap_user"] and cfg["imap_password"]):
|
||||
logger.warning(f"IMAP not configured for account {row.name!r}")
|
||||
return cfg
|
||||
finally:
|
||||
@@ -825,12 +942,19 @@ def _imap_connect(account_id: str | None = None, owner: str = "",
|
||||
timeout=timeout,
|
||||
)
|
||||
try:
|
||||
conn.login(cfg["imap_user"], cfg["imap_password"])
|
||||
if cfg.get("oauth_provider") == "google":
|
||||
token = _get_valid_google_token(cfg.get("account_id"), cfg)
|
||||
if not token:
|
||||
raise RuntimeError("Google OAuth token unavailable — reconnect the account in Settings → Integrations")
|
||||
conn.authenticate("XOAUTH2", lambda x: _xoauth2_bytes(cfg["imap_user"], token))
|
||||
else:
|
||||
conn.login(cfg["imap_user"], cfg["imap_password"])
|
||||
except Exception:
|
||||
# A failed AUTHENTICATE (e.g. an Office 365 app password on an
|
||||
# MFA-enabled tenant, #3174) otherwise orphans the already-connected
|
||||
# socket; close it before propagating so a misconfigured account
|
||||
# can't leak one descriptor per retry / background poller pass.
|
||||
# MFA-enabled tenant, #3174, or an expired/revoked OAuth token)
|
||||
# otherwise orphans the already-connected socket; close it before
|
||||
# propagating so a misconfigured account can't leak one descriptor
|
||||
# per retry / background poller pass.
|
||||
try:
|
||||
conn.shutdown()
|
||||
except Exception:
|
||||
|
||||
@@ -13,7 +13,9 @@ handlers need. The split is mechanical — no behavior change.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import sqlite3 as _sql3
|
||||
import time
|
||||
import email as email_mod
|
||||
import email.header
|
||||
import email.utils
|
||||
@@ -43,6 +45,7 @@ from routes.email_helpers import (
|
||||
_load_settings, _save_settings, _get_email_config,
|
||||
_send_smtp_message, _smtp_security_mode,
|
||||
_IMAP_TIMEOUT_SECONDS, _open_imap_connection,
|
||||
make_oauth_state, verify_oauth_state,
|
||||
_imap_connect, _imap, _decode_header, _detect_sent_folder, _detect_drafts_folder,
|
||||
_extract_attachment_text, _list_attachments_from_msg,
|
||||
_extract_attachment_to_disk, _extract_html, _extract_text,
|
||||
@@ -76,15 +79,16 @@ def _email_tag_owner_aliases(account_id: str | None, owner: str = "") -> list[st
|
||||
cfg.get("smtp_user") or "",
|
||||
cfg.get("from_address") or "",
|
||||
])
|
||||
except Exception:
|
||||
except Exception as _e:
|
||||
logger.warning("Failed to resolve email account alias", exc_info=_e)
|
||||
resolved_account_id = None
|
||||
row = db.get(_EA, resolved_account_id) if resolved_account_id else None
|
||||
if row:
|
||||
aliases.extend([row.owner or "", row.imap_user or "", row.from_address or ""])
|
||||
finally:
|
||||
db.close()
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as _e:
|
||||
logger.warning("Failed to load email aliases", exc_info=_e)
|
||||
out = []
|
||||
for a in aliases:
|
||||
a = (a or "").strip()
|
||||
@@ -285,7 +289,9 @@ def _group_uid_fetch_records(msg_data) -> list:
|
||||
|
||||
|
||||
def _smtp_ready(cfg: dict) -> bool:
|
||||
return bool(cfg.get("smtp_host") and cfg.get("smtp_user") and cfg.get("smtp_password"))
|
||||
if not cfg.get("smtp_host") or not cfg.get("smtp_user"):
|
||||
return False
|
||||
return bool(cfg.get("smtp_password") or cfg.get("oauth_provider"))
|
||||
|
||||
|
||||
def _resolve_send_config(account_id: str | None = None, owner: str = "") -> dict:
|
||||
@@ -1097,7 +1103,12 @@ def setup_email_routes():
|
||||
account_id: str | None = Query(None),
|
||||
owner: str = Depends(require_owner),
|
||||
):
|
||||
"""Search emails server-side via IMAP SEARCH. Matches subject, from, or body text."""
|
||||
"""Search emails server-side via IMAP SEARCH. Matches subject, from, or body text.
|
||||
|
||||
When the caller asks for INBOX and the account has an "All Mail"
|
||||
folder (Gmail does), we transparently swap to All Mail so the
|
||||
search surfaces archived / labelled emails too. Plain IMAP
|
||||
accounts fall back to whatever folder the caller specified."""
|
||||
if not q or len(q) < 2:
|
||||
return {"emails": [], "total": 0, "query": q}
|
||||
# CRLF in q would terminate the IMAP command early — reject defensively.
|
||||
@@ -1105,7 +1116,27 @@ def setup_email_routes():
|
||||
raise HTTPException(400, "Invalid query")
|
||||
try:
|
||||
with _imap(account_id, owner=owner) as conn:
|
||||
conn.select(_q(folder), readonly=True)
|
||||
# If the user asked for INBOX, try to upgrade to All Mail —
|
||||
# one folder == every email on Gmail-class servers.
|
||||
effective_folder = folder
|
||||
if (folder or "").upper() == "INBOX":
|
||||
try:
|
||||
status, folder_lines = conn.list()
|
||||
if status == "OK" and folder_lines:
|
||||
for raw in folder_lines:
|
||||
if isinstance(raw, bytes):
|
||||
raw = raw.decode("utf-8", errors="replace")
|
||||
m = re.match(r"\((?P<flags>[^)]*)\)\s+\"[^\"]*\"\s+(?P<name>.+)", raw)
|
||||
if not m:
|
||||
continue
|
||||
flags = (m.group("flags") or "").lower()
|
||||
name = m.group("name").strip().strip('"')
|
||||
if "\\all" in flags or "all mail" in name.lower():
|
||||
effective_folder = name
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
conn.select(_q(effective_folder), readonly=True)
|
||||
|
||||
# Escape backslash and quote for the IMAP-SEARCH quoted-string.
|
||||
q_escaped = q.replace('\\', '\\\\').replace('"', '\\"')
|
||||
@@ -1113,7 +1144,7 @@ def setup_email_routes():
|
||||
|
||||
status, data = _imap_uid_search(conn, search_cmd)
|
||||
if status != "OK" or not data[0]:
|
||||
return {"emails": [], "total": 0, "query": q}
|
||||
return {"emails": [], "total": 0, "query": q, "folder": effective_folder}
|
||||
|
||||
uid_list = data[0].split()
|
||||
total = len(uid_list)
|
||||
@@ -1178,6 +1209,13 @@ def setup_email_routes():
|
||||
"is_flagged": "\\Flagged" in flags,
|
||||
"flags": flags,
|
||||
"has_attachments": has_attachments,
|
||||
# Stamp the folder so the frontend opens each
|
||||
# email from the folder it actually lives in
|
||||
# (the search may have run against All Mail
|
||||
# even though the caller asked for INBOX),
|
||||
# otherwise clicks open whatever happens to
|
||||
# have the same UID in INBOX → wrong email.
|
||||
"folder": effective_folder,
|
||||
})
|
||||
except Exception as e:
|
||||
logger.warning(f"Error parsing search result {uid}: {e}")
|
||||
@@ -1724,6 +1762,22 @@ def setup_email_routes():
|
||||
logger.error(f"Failed to mark unread {uid}: {e}")
|
||||
return {"success": False, "error": "Mail operation failed"}
|
||||
|
||||
@router.post("/flag/{uid}")
|
||||
async def flag_email(uid: str, folder: str = Query("INBOX"), account_id: str | None = Query(None),
|
||||
on: bool = Query(True), owner: str = Depends(require_owner)):
|
||||
"""Toggle the \\Flagged flag (a.k.a. favorite / star) on an email.
|
||||
Pass `on=true` to favorite, `on=false` to unfavorite."""
|
||||
try:
|
||||
with _imap(account_id, owner=owner) as conn:
|
||||
conn.select(_q(folder))
|
||||
if not _store_email_flag(conn, uid, "\\Flagged", add=bool(on)):
|
||||
return {"success": False, "error": "Email not found"}
|
||||
_invalidate_list_cache(account_id, folder)
|
||||
return {"success": True, "flagged": bool(on)}
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to flag {uid}: {e}")
|
||||
return {"success": False, "error": "Mail operation failed"}
|
||||
|
||||
@router.post("/mark-read/{uid}")
|
||||
async def mark_read(uid: str, folder: str = Query("INBOX"), account_id: str | None = Query(None), owner: str = Depends(require_owner)):
|
||||
"""Mark an email as read (set \\Seen flag)."""
|
||||
@@ -1973,7 +2027,7 @@ def setup_email_routes():
|
||||
outer = MIMEMultipart("alternative")
|
||||
body_container = outer
|
||||
|
||||
outer["From"] = cfg["from_address"]
|
||||
outer["From"] = email.utils.formataddr((cfg.get("display_name") or "", cfg["from_address"]))
|
||||
outer["To"] = to
|
||||
if cc:
|
||||
outer["Cc"] = cc
|
||||
@@ -2104,6 +2158,77 @@ def setup_email_routes():
|
||||
logger.error(f"cancel_scheduled {sid!r} failed: {e}")
|
||||
return {"success": False, "error": "Mail operation failed"}
|
||||
|
||||
# ── Agent send-confirm: list/approve/cancel ──────────────────────────
|
||||
# When `agent_email_confirm` is on, the MCP send_email tool drops the
|
||||
# composed email into scheduled_emails with status='agent_draft' (a
|
||||
# far-future send_at so the poller never picks it up). These endpoints
|
||||
# let the chat UI surface them for the user and either approve (flip
|
||||
# to status='pending' with send_at=now so the poller delivers it) or
|
||||
# cancel (status='cancelled').
|
||||
@router.get("/pending")
|
||||
async def list_pending_agent_drafts(owner: str = Depends(require_owner)):
|
||||
import sqlite3
|
||||
try:
|
||||
conn = sqlite3.connect(SCHEDULED_DB)
|
||||
conn.row_factory = sqlite3.Row
|
||||
rows = conn.execute(
|
||||
"""SELECT id, to_addr, subject, body, created_at, account_id
|
||||
FROM scheduled_emails
|
||||
WHERE status = 'agent_draft' AND owner = ?
|
||||
ORDER BY created_at DESC""",
|
||||
(owner or "",),
|
||||
).fetchall()
|
||||
conn.close()
|
||||
return {"pending": [dict(r) for r in rows]}
|
||||
except Exception as e:
|
||||
logger.error(f"list_pending_agent_drafts failed: {e}")
|
||||
return {"pending": [], "error": "Mail operation failed"}
|
||||
|
||||
@router.post("/pending/{sid}/approve")
|
||||
async def approve_agent_draft(sid: str, owner: str = Depends(require_owner)):
|
||||
"""Approve a draft staged by the agent: flip status → pending and
|
||||
backdate send_at so the scheduled-send poller picks it up
|
||||
immediately."""
|
||||
import sqlite3
|
||||
try:
|
||||
conn = sqlite3.connect(SCHEDULED_DB)
|
||||
cur = conn.execute(
|
||||
"""UPDATE scheduled_emails
|
||||
SET status = 'pending', send_at = ?
|
||||
WHERE id = ? AND status = 'agent_draft' AND owner = ?""",
|
||||
(datetime.utcnow().isoformat(), sid, owner or ""),
|
||||
)
|
||||
conn.commit()
|
||||
affected = cur.rowcount
|
||||
conn.close()
|
||||
if not affected:
|
||||
return {"success": False, "error": "Draft not found or already handled"}
|
||||
return {"success": True}
|
||||
except Exception as e:
|
||||
logger.error(f"approve_agent_draft {sid!r} failed: {e}")
|
||||
return {"success": False, "error": "Mail operation failed"}
|
||||
|
||||
@router.delete("/pending/{sid}")
|
||||
async def cancel_agent_draft(sid: str, owner: str = Depends(require_owner)):
|
||||
"""Discard a draft the agent staged for approval."""
|
||||
import sqlite3
|
||||
try:
|
||||
conn = sqlite3.connect(SCHEDULED_DB)
|
||||
cur = conn.execute(
|
||||
"""UPDATE scheduled_emails SET status = 'cancelled'
|
||||
WHERE id = ? AND status = 'agent_draft' AND owner = ?""",
|
||||
(sid, owner or ""),
|
||||
)
|
||||
conn.commit()
|
||||
affected = cur.rowcount
|
||||
conn.close()
|
||||
if not affected:
|
||||
return {"success": False, "error": "Draft not found or already handled"}
|
||||
return {"success": True}
|
||||
except Exception as e:
|
||||
logger.error(f"cancel_agent_draft {sid!r} failed: {e}")
|
||||
return {"success": False, "error": "Mail operation failed"}
|
||||
|
||||
@router.get("/resolve-contact")
|
||||
async def resolve_contact(name: str = Query(..., description="Name to search for"), owner: str = Depends(require_owner)):
|
||||
"""Search Sent folder for a contact by name. Returns matching email addresses."""
|
||||
@@ -2164,6 +2289,7 @@ def setup_email_routes():
|
||||
try:
|
||||
cfg = _resolve_send_config(req.account_id, owner=owner)
|
||||
except Exception as e:
|
||||
logger.warning(f"No SMTP-capable account resolved: {e}")
|
||||
return {"success": False, "error": str(e) or "No SMTP-capable email account configured"}
|
||||
|
||||
# Use 'mixed' if we have attachments, 'alternative' otherwise
|
||||
@@ -2176,7 +2302,7 @@ def setup_email_routes():
|
||||
outer = MIMEMultipart("alternative")
|
||||
body_container = outer
|
||||
|
||||
outer["From"] = cfg["from_address"]
|
||||
outer["From"] = email.utils.formataddr((cfg.get("display_name") or "", cfg["from_address"]))
|
||||
outer["To"] = req.to
|
||||
if req.cc:
|
||||
outer["Cc"] = req.cc
|
||||
@@ -2227,6 +2353,10 @@ def setup_email_routes():
|
||||
|
||||
_account_id = cfg.get("account_id") or req.account_id # capture for the IMAP append in the closure
|
||||
_in_reply_to = (req.in_reply_to or "").strip()
|
||||
_oauth_provider = cfg.get("oauth_provider") or ""
|
||||
_oauth_access_token = cfg.get("oauth_access_token") or ""
|
||||
_oauth_refresh_token = cfg.get("oauth_refresh_token") or ""
|
||||
_oauth_token_expiry = cfg.get("oauth_token_expiry") or ""
|
||||
|
||||
def _deliver():
|
||||
try:
|
||||
@@ -2237,6 +2367,11 @@ def setup_email_routes():
|
||||
"smtp_security": _smtp_security,
|
||||
"smtp_user": _smtp_user,
|
||||
"smtp_password": _smtp_pw,
|
||||
"account_id": _account_id,
|
||||
"oauth_provider": _oauth_provider,
|
||||
"oauth_access_token": _oauth_access_token,
|
||||
"oauth_refresh_token": _oauth_refresh_token,
|
||||
"oauth_token_expiry": _oauth_token_expiry,
|
||||
},
|
||||
_from,
|
||||
_recipients,
|
||||
@@ -2349,7 +2484,7 @@ def setup_email_routes():
|
||||
msg.attach(MIMEText(_draft_html, "html", "utf-8"))
|
||||
else:
|
||||
msg = MIMEText(req.body, "plain", "utf-8")
|
||||
msg["From"] = cfg["from_address"]
|
||||
msg["From"] = email.utils.formataddr((cfg.get("display_name") or "", cfg["from_address"]))
|
||||
msg["To"] = req.to
|
||||
if req.cc:
|
||||
msg["Cc"] = req.cc
|
||||
@@ -2617,11 +2752,15 @@ def setup_email_routes():
|
||||
source_uid = (data.get("uid") or "").strip()
|
||||
source_folder = (data.get("folder") or "INBOX").strip()
|
||||
fast_reply = bool(data.get("fast", False))
|
||||
user_hint = (data.get("user_hint") or "").strip()
|
||||
|
||||
if not original_body:
|
||||
return {"success": False, "error": "No email body provided"}
|
||||
|
||||
if message_id:
|
||||
# Skip cache lookup when the caller supplied a user_hint — the
|
||||
# cached generic reply doesn't reflect the instructions and
|
||||
# would silently override them.
|
||||
if message_id and not user_hint:
|
||||
try:
|
||||
_c = _sql3.connect(SCHEDULED_DB)
|
||||
owner_clause, owner_params = _email_cache_owner_clause(owner)
|
||||
@@ -2761,8 +2900,13 @@ def setup_email_routes():
|
||||
user_msg = (
|
||||
f"Recipient: {to}\nSubject: {subject}\n\n"
|
||||
f"Original email and any current draft:\n{original_body[:6000]}\n\n"
|
||||
f"Draft a reply. Return only the reply body text."
|
||||
)
|
||||
if user_hint:
|
||||
user_msg += (
|
||||
f"User's instructions for THIS reply (follow these — they override "
|
||||
f"defaults like length/tone):\n{user_hint[:2000]}\n\n"
|
||||
)
|
||||
user_msg += "Draft a reply. Return only the reply body text."
|
||||
|
||||
# Build a candidate chain so a stale session-stored API key
|
||||
# (the most common cause of "authentication failed" here)
|
||||
@@ -2992,6 +3136,8 @@ def setup_email_routes():
|
||||
"from_address": r.from_address or "",
|
||||
"has_imap_password": bool(r.imap_password),
|
||||
"has_smtp_password": bool(r.smtp_password),
|
||||
"oauth_provider": r.oauth_provider or "",
|
||||
"display_name": r.display_name or "",
|
||||
})
|
||||
return {"accounts": out}
|
||||
finally:
|
||||
@@ -3024,6 +3170,7 @@ def setup_email_routes():
|
||||
smtp_user=(data.get("smtp_user") or "").strip(),
|
||||
smtp_password=_enc(data.get("smtp_password") or ""),
|
||||
from_address=(data.get("from_address") or "").strip(),
|
||||
display_name=(data.get("display_name") or "").strip(),
|
||||
# SECURITY: stamp the creator so all subsequent reads / mutations
|
||||
# can filter by user. Without this every new account leaks to
|
||||
# every other user.
|
||||
@@ -3058,7 +3205,7 @@ def setup_email_routes():
|
||||
if not row:
|
||||
return {"ok": False, "error": "Account not found"}
|
||||
# Simple fields
|
||||
for key in ("name", "imap_host", "imap_user", "smtp_host", "smtp_user", "from_address"):
|
||||
for key in ("name", "imap_host", "imap_user", "smtp_host", "smtp_user", "from_address", "display_name"):
|
||||
if key in data:
|
||||
setattr(row, key, (data[key] or "").strip())
|
||||
for key in ("imap_port", "smtp_port"):
|
||||
@@ -3247,4 +3394,123 @@ def setup_email_routes():
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
# ── Google OAuth2 routes ──
|
||||
|
||||
@router.get("/oauth/google/authorize")
|
||||
async def google_oauth_authorize(account_id: str = Query(...), request: Request = None, owner: str = Depends(require_user)):
|
||||
import urllib.parse
|
||||
_assert_owns_account(account_id, owner)
|
||||
client_id = os.environ.get("GOOGLE_OAUTH_CLIENT_ID", "")
|
||||
if not client_id:
|
||||
raise HTTPException(400, "GOOGLE_OAUTH_CLIENT_ID not set — add it to .env")
|
||||
redirect_uri = (
|
||||
os.environ.get("GOOGLE_OAUTH_REDIRECT_URI")
|
||||
or f"http://{request.headers.get('host', 'localhost:7000')}/api/email/oauth/google/callback"
|
||||
)
|
||||
state = make_oauth_state(account_id, owner)
|
||||
params = urllib.parse.urlencode({
|
||||
"client_id": client_id,
|
||||
"redirect_uri": redirect_uri,
|
||||
"response_type": "code",
|
||||
"scope": "https://mail.google.com/ email",
|
||||
"access_type": "offline",
|
||||
"prompt": "consent",
|
||||
"state": state,
|
||||
})
|
||||
from fastapi.responses import RedirectResponse as _RR
|
||||
return _RR(f"https://accounts.google.com/o/oauth2/v2/auth?{params}")
|
||||
|
||||
@router.get("/oauth/google/callback")
|
||||
async def google_oauth_callback(
|
||||
code: str = Query(None),
|
||||
state: str = Query(None),
|
||||
error: str = Query(None),
|
||||
request: Request = None,
|
||||
):
|
||||
import urllib.parse
|
||||
from fastapi.responses import RedirectResponse as _RR
|
||||
if error:
|
||||
return _RR("/?section=integrations&email_oauth_error=google_error")
|
||||
if not code or not state:
|
||||
return _RR("/?section=integrations&email_oauth_error=missing_code")
|
||||
state_data = verify_oauth_state(state)
|
||||
if not state_data:
|
||||
return _RR("/?section=integrations&email_oauth_error=invalid_state")
|
||||
account_id = state_data.get("a", "")
|
||||
owner = state_data.get("o", "")
|
||||
client_id = os.environ.get("GOOGLE_OAUTH_CLIENT_ID", "")
|
||||
client_secret = os.environ.get("GOOGLE_OAUTH_CLIENT_SECRET", "")
|
||||
redirect_uri = (
|
||||
os.environ.get("GOOGLE_OAUTH_REDIRECT_URI")
|
||||
or f"http://{request.headers.get('host', 'localhost:7000')}/api/email/oauth/google/callback"
|
||||
)
|
||||
import httpx as _httpx
|
||||
try:
|
||||
resp = _httpx.post("https://oauth2.googleapis.com/token", data={
|
||||
"code": code,
|
||||
"client_id": client_id,
|
||||
"client_secret": client_secret,
|
||||
"redirect_uri": redirect_uri,
|
||||
"grant_type": "authorization_code",
|
||||
}, timeout=10)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
except Exception:
|
||||
logger.warning("Google token exchange failed")
|
||||
return _RR("/?section=integrations&email_oauth_error=token_exchange_failed")
|
||||
access_token = data.get("access_token", "")
|
||||
refresh_token = data.get("refresh_token", "")
|
||||
expiry = str(int(time.time()) + data.get("expires_in", 3600))
|
||||
# Fetch the email address from userinfo so we can auto-fill imap_user.
|
||||
email_addr = ""
|
||||
display_name = ""
|
||||
try:
|
||||
ui = _httpx.get("https://www.googleapis.com/oauth2/v1/userinfo",
|
||||
headers={"Authorization": f"Bearer {access_token}"}, timeout=10)
|
||||
if ui.is_success:
|
||||
ui_data = ui.json()
|
||||
email_addr = ui_data.get("email", "")
|
||||
display_name = ui_data.get("name", "")
|
||||
except Exception:
|
||||
pass
|
||||
from core.database import SessionLocal, EmailAccount
|
||||
from src.secret_storage import encrypt as _enc
|
||||
db = SessionLocal()
|
||||
try:
|
||||
row = db.query(EmailAccount).filter(EmailAccount.id == account_id).first()
|
||||
if not row:
|
||||
return _RR("/?section=integrations&email_oauth_error=account_not_found")
|
||||
# SECURITY: verify the account belongs to the initiating user.
|
||||
if owner and row.owner and row.owner != owner:
|
||||
logger.warning("OAuth callback owner mismatch — rejecting token write")
|
||||
return _RR("/?section=integrations&email_oauth_error=ownership_error")
|
||||
row.oauth_provider = "google"
|
||||
row.oauth_access_token = _enc(access_token)
|
||||
if refresh_token:
|
||||
row.oauth_refresh_token = _enc(refresh_token)
|
||||
row.oauth_token_expiry = expiry
|
||||
# Auto-fill Google IMAP/SMTP settings if not already configured.
|
||||
if not row.imap_host:
|
||||
row.imap_host = "imap.gmail.com"
|
||||
row.imap_port = 993
|
||||
row.imap_starttls = False
|
||||
if not row.smtp_host:
|
||||
row.smtp_host = "smtp.gmail.com"
|
||||
row.smtp_port = 587
|
||||
if email_addr:
|
||||
if not row.imap_user:
|
||||
row.imap_user = email_addr
|
||||
if not row.smtp_user:
|
||||
row.smtp_user = email_addr
|
||||
if not row.from_address:
|
||||
row.from_address = email_addr
|
||||
if not row.name or row.name == row.id:
|
||||
row.name = email_addr
|
||||
if display_name and not row.display_name:
|
||||
row.display_name = display_name
|
||||
db.commit()
|
||||
finally:
|
||||
db.close()
|
||||
return _RR("/?section=integrations&email_oauth_success=1")
|
||||
|
||||
return router
|
||||
|
||||
@@ -9,6 +9,7 @@ from pathlib import Path
|
||||
from fastapi import APIRouter, HTTPException, Form, Depends
|
||||
from core.constants import EMBEDDING_ENDPOINT_FILE, FASTEMBED_CACHE_DIR
|
||||
from core.middleware import require_admin
|
||||
from src.runtime_paths import get_app_root
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -224,8 +224,6 @@ def setup_gallery_routes() -> APIRouter:
|
||||
@router.post("/api/gallery/{image_id}/replace")
|
||||
async def gallery_replace(request: Request, image_id: str):
|
||||
"""Replace an existing gallery image file with a new one."""
|
||||
from pathlib import Path
|
||||
|
||||
user = get_current_user(request)
|
||||
db = SessionLocal()
|
||||
try:
|
||||
@@ -241,9 +239,8 @@ def setup_gallery_routes() -> APIRouter:
|
||||
raise HTTPException(400, "No image provided")
|
||||
|
||||
content = await read_upload_limited(file, GALLERY_UPLOAD_MAX_BYTES, "Gallery replacement")
|
||||
img_dir = Path(GENERATED_IMAGES_DIR)
|
||||
img_dir.mkdir(parents=True, exist_ok=True)
|
||||
img_path = img_dir / _sanitize_gallery_filename(img.filename)
|
||||
GALLERY_IMAGE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
img_path = _gallery_image_path(img.filename)
|
||||
img_path.write_bytes(content)
|
||||
|
||||
# Refresh dimensions in case the editor resized the canvas.
|
||||
|
||||
@@ -119,7 +119,7 @@ def setup_hwfit_routes():
|
||||
return detect_system(host=host, ssh_port=ssh_port, platform=platform, fresh=fresh)
|
||||
|
||||
@router.get("/models")
|
||||
def get_models(use_case: str = "", sort: str = "score", limit: int = 50, search: str = "", host: str = "", quant: str = "", ctx: str = "", gpu_count: str = "", gpu_group: str = "", ssh_port: str = "", platform: str = "", fresh: bool = False, manual_mode: str = "", manual_gpu_count: str = "", manual_vram_gb: str = "", manual_ram_gb: str = "", manual_backend: str = "", ignore_detected_gpu: bool = False, ignore_detected_ram: bool = False, fit_only: bool = False):
|
||||
def get_models(use_case: str = "", sort: str = "newest", limit: int = 50, search: str = "", host: str = "", quant: str = "", ctx: str = "", gpu_count: str = "", gpu_group: str = "", ssh_port: str = "", platform: str = "", fresh: bool = False, manual_mode: str = "", manual_gpu_count: str = "", manual_vram_gb: str = "", manual_ram_gb: str = "", manual_backend: str = "", ignore_detected_gpu: bool = False, ignore_detected_ram: bool = False, fit_only: bool = False):
|
||||
"""Rank LLM models against detected hardware and return scored results.
|
||||
gpu_count: override GPU count (0 = CPU only, 1-N = simulate N GPUs of the
|
||||
active group). gpu_group: index into system.gpu_groups (the homogeneous
|
||||
|
||||
@@ -273,65 +273,30 @@ def setup_memory_routes(memory_manager: MemoryManager, session_manager: SessionM
|
||||
async def api_audit_memories(request: Request, session: str = Form(None)):
|
||||
"""Deduplicate and consolidate memories via LLM.
|
||||
|
||||
Uses the default model from settings, or falls back to a session's model.
|
||||
Uses task/utility/default settings through the shared resolver, with
|
||||
the active session as fallback when no task or utility model is set.
|
||||
Returns before and after memory counts.
|
||||
"""
|
||||
from routes.model_routes import _load_settings, _normalize_base, build_chat_url
|
||||
from core.database import ModelEndpoint
|
||||
import json as _json
|
||||
|
||||
endpoint_url = model = None
|
||||
headers = {}
|
||||
|
||||
# Try utility model from settings first — memory audit is a background
|
||||
# task and should prefer the lighter utility model over the main chat model.
|
||||
from src.task_endpoint import resolve_task_endpoint
|
||||
user = _owner(request)
|
||||
t_url, t_model, t_headers = resolve_task_endpoint(owner=user)
|
||||
if t_url and t_model:
|
||||
endpoint_url, model, headers = t_url, t_model, t_headers
|
||||
else:
|
||||
# Fall back to default model if no task/utility model configured
|
||||
settings = _load_settings()
|
||||
ep_id = settings.get("default_endpoint_id", "")
|
||||
default_model = settings.get("default_model", "")
|
||||
if ep_id:
|
||||
db = SessionLocal()
|
||||
try:
|
||||
ep = db.query(ModelEndpoint).filter(
|
||||
ModelEndpoint.id == ep_id, ModelEndpoint.is_enabled == True
|
||||
).first()
|
||||
if ep:
|
||||
base = _normalize_base(ep.base_url)
|
||||
endpoint_url = build_chat_url(base)
|
||||
model = default_model
|
||||
if not model and ep.models:
|
||||
try:
|
||||
models = _json.loads(ep.models) if isinstance(ep.models, str) else ep.models
|
||||
if models:
|
||||
model = models[0]
|
||||
except Exception:
|
||||
pass
|
||||
if ep.api_key:
|
||||
headers = {"Authorization": f"Bearer {ep.api_key}"}
|
||||
finally:
|
||||
db.close()
|
||||
fallback_url = fallback_model = None
|
||||
fallback_headers = None
|
||||
if session:
|
||||
try:
|
||||
sess = session_manager.get_session(session)
|
||||
_assert_session_owner(sess, user)
|
||||
fallback_url = sess.endpoint_url
|
||||
fallback_model = sess.model
|
||||
fallback_headers = sess.headers
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
# Fall back to session model if no default configured
|
||||
if not endpoint_url and session:
|
||||
try:
|
||||
sess = session_manager.get_session(session)
|
||||
_assert_session_owner(sess, _owner(request))
|
||||
endpoint_url = sess.endpoint_url
|
||||
model = sess.model
|
||||
headers = sess.headers
|
||||
except KeyError:
|
||||
pass
|
||||
endpoint_url, model, headers = resolve_task_endpoint(
|
||||
fallback_url, fallback_model, fallback_headers, owner=user
|
||||
)
|
||||
|
||||
if not endpoint_url or not model:
|
||||
raise HTTPException(400, "No default model configured — set one in Settings")
|
||||
|
||||
user = _owner(request)
|
||||
result = await audit_memories(
|
||||
memory_manager,
|
||||
memory_vector,
|
||||
@@ -369,18 +334,28 @@ def setup_memory_routes(memory_manager: MemoryManager, session_manager: SessionM
|
||||
model = None
|
||||
headers = {}
|
||||
|
||||
user = _owner(request)
|
||||
|
||||
if session:
|
||||
try:
|
||||
sess = session_manager.get_session(session)
|
||||
_assert_session_owner(sess, _owner(request))
|
||||
endpoint_url, model, headers = resolve_task_endpoint(
|
||||
sess.endpoint_url, sess.model, sess.headers, owner=_owner(request)
|
||||
)
|
||||
_assert_session_owner(sess, user)
|
||||
except KeyError:
|
||||
logger.warning("Session %s not found, falling back to utility endpoint", session)
|
||||
endpoint_url, model, headers = resolve_endpoint("utility", owner=_owner(request))
|
||||
sess = None
|
||||
except HTTPException as exc:
|
||||
if exc.status_code != 404:
|
||||
raise
|
||||
sess = None
|
||||
|
||||
if sess is None:
|
||||
logger.warning("Session %s not found or inaccessible, falling back to utility endpoint", session)
|
||||
endpoint_url, model, headers = resolve_endpoint("utility", owner=user)
|
||||
else:
|
||||
endpoint_url, model, headers = resolve_task_endpoint(
|
||||
sess.endpoint_url, sess.model, sess.headers, owner=user
|
||||
)
|
||||
else:
|
||||
endpoint_url, model, headers = resolve_task_endpoint(owner=_owner(request))
|
||||
endpoint_url, model, headers = resolve_task_endpoint(owner=user)
|
||||
|
||||
if not endpoint_url or not model:
|
||||
raise HTTPException(400, "No LLM model configured. Set a default model in Settings.")
|
||||
|
||||
@@ -5,6 +5,7 @@ import re
|
||||
import uuid
|
||||
import json
|
||||
import hashlib
|
||||
import ipaddress
|
||||
import socket
|
||||
import time as _time
|
||||
import logging
|
||||
@@ -26,7 +27,7 @@ from src.endpoint_resolver import (
|
||||
build_models_url,
|
||||
build_headers,
|
||||
)
|
||||
from src.auth_helpers import _auth_disabled, owner_filter
|
||||
from src.auth_helpers import _auth_disabled, effective_user, owner_filter
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -562,6 +563,8 @@ def _safe_build_models_url(base_url: str) -> str:
|
||||
"""Build a /models URL without letting optional provider imports break probes."""
|
||||
try:
|
||||
return build_models_url(base_url)
|
||||
except ValueError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
logger.debug("Model URL detection failed for %s: %s", base_url, exc)
|
||||
return f"{(base_url or '').rstrip('/')}/models"
|
||||
@@ -633,7 +636,7 @@ def _probe_single_model(base: str, api_key: str, model_id: str, timeout: int = 1
|
||||
|
||||
try:
|
||||
t0 = _time.time()
|
||||
r = httpx.post(target_url, headers=h, json=payload, timeout=timeout)
|
||||
r = httpx.post(target_url, headers=h, json=payload, timeout=timeout, verify=llm_verify())
|
||||
latency = round((_time.time() - t0) * 1000)
|
||||
if r.is_success:
|
||||
return {"status": "ok", "latency_ms": latency}
|
||||
@@ -659,13 +662,20 @@ def _probe_single_model(base: str, api_key: str, model_id: str, timeout: int = 1
|
||||
|
||||
# Hostnames / IP prefixes that indicate a local endpoint
|
||||
_LOCAL_HOSTS = {"localhost", "127.0.0.1", "0.0.0.0", "::1"}
|
||||
_PRIVATE_PREFIXES = ("10.", "172.16.", "172.17.", "172.18.", "172.19.",
|
||||
"172.20.", "172.21.", "172.22.", "172.23.", "172.24.",
|
||||
"172.25.", "172.26.", "172.27.", "172.28.", "172.29.",
|
||||
"172.30.", "172.31.", "192.168.")
|
||||
_PRIVATE_NETWORKS = (
|
||||
ipaddress.ip_network("10.0.0.0/8"),
|
||||
ipaddress.ip_network("172.16.0.0/12"),
|
||||
ipaddress.ip_network("192.168.0.0/16"),
|
||||
)
|
||||
_TAILSCALE_CGNAT = ipaddress.ip_network("100.64.0.0/10")
|
||||
|
||||
|
||||
_TAILSCALE_RE = re.compile(r"^100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.")
|
||||
def _local_ip_literal(host: str) -> bool:
|
||||
try:
|
||||
ip = ipaddress.ip_address(host)
|
||||
except ValueError:
|
||||
return False
|
||||
return any(ip in network for network in _PRIVATE_NETWORKS) or ip in _TAILSCALE_CGNAT
|
||||
|
||||
|
||||
def _classify_endpoint(base_url: str, endpoint_kind: str = "auto") -> str:
|
||||
@@ -679,9 +689,7 @@ def _classify_endpoint(base_url: str, endpoint_kind: str = "auto") -> str:
|
||||
return "api"
|
||||
try:
|
||||
host = urlparse(base_url).hostname or ""
|
||||
if host in _LOCAL_HOSTS or host.startswith(_PRIVATE_PREFIXES):
|
||||
return "local"
|
||||
if _TAILSCALE_RE.match(host):
|
||||
if host in _LOCAL_HOSTS or _local_ip_literal(host):
|
||||
return "local"
|
||||
except Exception:
|
||||
pass
|
||||
@@ -1255,13 +1263,16 @@ def setup_model_routes(model_discovery):
|
||||
# Require auth; "" is the unconfigured single-user mode, treated as
|
||||
# "see everything" by _fetch_models.
|
||||
try:
|
||||
from src.auth_helpers import get_current_user as _gcu
|
||||
owner = _gcu(request) or ""
|
||||
except Exception:
|
||||
owner = ""
|
||||
# Reject anonymous in configured deployments — no leaking the model
|
||||
# list to unauthenticated callers.
|
||||
try:
|
||||
if getattr(request.state, "api_token", False):
|
||||
scopes = set(getattr(request.state, "api_token_scopes", []) or [])
|
||||
if "chat" not in scopes:
|
||||
raise HTTPException(403, "API token is not scoped for chat")
|
||||
if not getattr(request.state, "api_token_owner", None):
|
||||
raise HTTPException(403, "API token has no owner")
|
||||
owner = effective_user(request) or ""
|
||||
|
||||
# Reject anonymous in configured deployments — no leaking the model
|
||||
# list to unauthenticated callers.
|
||||
auth_mgr = getattr(request.app.state, "auth_manager", None)
|
||||
if not owner and not _auth_disabled() and auth_mgr is not None and getattr(auth_mgr, "is_configured", False):
|
||||
raise HTTPException(401, "Not authenticated")
|
||||
|
||||
@@ -10,7 +10,8 @@ from fastapi import APIRouter, HTTPException, Request
|
||||
from pydantic import BaseModel
|
||||
|
||||
from core.database import SessionLocal, Note
|
||||
from src.auth_helpers import get_current_user
|
||||
from core.middleware import INTERNAL_TOOL_USER
|
||||
from src.auth_helpers import require_user
|
||||
from src.constants import DATA_DIR
|
||||
from sqlalchemy.orm.attributes import flag_modified
|
||||
|
||||
@@ -208,14 +209,17 @@ async def dispatch_reminder(
|
||||
try:
|
||||
from src.endpoint_resolver import resolve_endpoint
|
||||
from src.llm_core import llm_call_async
|
||||
from src.reminder_personas import synthesis_system_prompt
|
||||
url, model, headers = resolve_endpoint("utility", owner=owner or None)
|
||||
if not url:
|
||||
url, model, headers = resolve_endpoint("default", owner=owner or None)
|
||||
if url and model:
|
||||
persona_id = (settings.get("reminder_llm_persona") or "").strip()
|
||||
sys_prompt = synthesis_system_prompt(persona_id)
|
||||
raw = await llm_call_async(
|
||||
url=url, model=model,
|
||||
messages=[
|
||||
{"role": "system", "content": "You are a reminder assistant. Write a single short, warm, motivating sentence (max 25 words) reminding the user about the note below. Do not add greetings, preamble, or hashtags. Output only the sentence."},
|
||||
{"role": "system", "content": sys_prompt},
|
||||
{"role": "user", "content": f"Title: {title}\n\n{note_body}".strip()},
|
||||
],
|
||||
temperature=0.7, max_tokens=200, headers=headers, timeout=30,
|
||||
@@ -567,10 +571,19 @@ def setup_note_routes(task_scheduler=None):
|
||||
router = APIRouter(prefix="/api/notes", tags=["notes"])
|
||||
|
||||
def _owner(request: Request) -> Optional[str]:
|
||||
return get_current_user(request)
|
||||
# require_user, not bare get_current_user: a request that reaches
|
||||
# these owner-scoped routes with NO identity (auth-middleware
|
||||
# regression, SSRF from a sibling service) must fail closed (401)
|
||||
# when auth is configured — not be treated as the single-user mode
|
||||
# and handed blanket access to every account's notes. The documented
|
||||
# anonymous modes (AUTH_ENABLED=false, LOCALHOST_BYPASS on loopback,
|
||||
# unconfigured first-run) still resolve to None, the single-user
|
||||
# path. fire_reminder below already gated this way; the CRUD routes
|
||||
# did not.
|
||||
return require_user(request) or None
|
||||
|
||||
def _is_admin_or_single_user(request: Request, user: str | None) -> bool:
|
||||
if user == "internal-tool":
|
||||
if user == INTERNAL_TOOL_USER:
|
||||
return True
|
||||
if not user:
|
||||
# require_user() already admitted this request, which only happens
|
||||
@@ -802,8 +815,7 @@ def setup_note_routes(task_scheduler=None):
|
||||
Returns {synthesis, email_sent}.
|
||||
"""
|
||||
# Gate against anonymous callers — LLM synthesis can burn tokens.
|
||||
from src.auth_helpers import require_user as _ru
|
||||
user = _ru(request)
|
||||
user = require_user(request)
|
||||
body = await request.json()
|
||||
note_id = str(body.get("note_id") or "").strip()
|
||||
if not note_id:
|
||||
@@ -826,6 +838,12 @@ def setup_note_routes(task_scheduler=None):
|
||||
_override["reminder_webhook_integration_id"] = body["webhook_integration_id"]
|
||||
if body.get("webhook_payload_template"):
|
||||
_override["reminder_webhook_payload_template"] = body["webhook_payload_template"]
|
||||
# Mirror the in-UI AI Synthesis toggle + persona so the test
|
||||
# actually exercises the synthesis path before/without a Save.
|
||||
if "llm_synthesis" in body:
|
||||
_override["reminder_llm_synthesis"] = bool(body["llm_synthesis"])
|
||||
if "llm_persona" in body:
|
||||
_override["reminder_llm_persona"] = str(body["llm_persona"] or "")
|
||||
else:
|
||||
db = SessionLocal()
|
||||
try:
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
"""Routes for personal documents management."""
|
||||
import os
|
||||
import logging
|
||||
import shutil
|
||||
import uuid
|
||||
from typing import List, Tuple
|
||||
from typing import Any, Dict, List, Tuple
|
||||
from fastapi import APIRouter, HTTPException, Query, Request, UploadFile, File, Depends
|
||||
from src.request_models import DirectoryRequest
|
||||
from core.constants import BASE_DIR, PERSONAL_DIR, PERSONAL_UPLOADS_DIR
|
||||
@@ -18,14 +19,15 @@ UPLOADS_DIR = PERSONAL_UPLOADS_DIR
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _personal_upload_dir_for_owner(owner: str | None) -> str:
|
||||
def _personal_upload_dir_for_owner(owner: str | None, *, create: bool = True) -> str:
|
||||
"""Return the per-owner upload directory used for direct RAG uploads."""
|
||||
owner_segment = secure_filename((owner or "local").strip())[:80] or "local"
|
||||
upload_dir = os.path.abspath(os.path.join(UPLOADS_DIR, owner_segment))
|
||||
base_abs = os.path.abspath(UPLOADS_DIR)
|
||||
if os.path.commonpath([upload_dir, base_abs]) != base_abs:
|
||||
raise ValueError("Unsafe upload owner path")
|
||||
os.makedirs(upload_dir, exist_ok=True)
|
||||
if create:
|
||||
os.makedirs(upload_dir, exist_ok=True)
|
||||
return upload_dir
|
||||
|
||||
|
||||
@@ -44,6 +46,87 @@ def _unique_personal_upload_path(upload_dir: str, original_name: str | None) ->
|
||||
raise ValueError("Unsafe upload filename")
|
||||
return file_path, filename, safe_name
|
||||
|
||||
|
||||
def _unique_existing_target(path: str) -> str:
|
||||
"""Return a non-existing sibling path for rename collision handling."""
|
||||
if not os.path.exists(path):
|
||||
return path
|
||||
stem, ext = os.path.splitext(path)
|
||||
while True:
|
||||
candidate = f"{stem}-{uuid.uuid4().hex[:10]}{ext}"
|
||||
if not os.path.exists(candidate):
|
||||
return candidate
|
||||
|
||||
|
||||
def _remove_empty_tree(path: str) -> None:
|
||||
"""Best-effort removal of empty directories under ``path``."""
|
||||
if not os.path.isdir(path):
|
||||
return
|
||||
for root, dirs, _files in os.walk(path, topdown=False):
|
||||
for dirname in dirs:
|
||||
candidate = os.path.join(root, dirname)
|
||||
try:
|
||||
os.rmdir(candidate)
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
os.rmdir(path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def rename_personal_upload_owner(
|
||||
old_owner: str,
|
||||
new_owner: str,
|
||||
*,
|
||||
personal_docs_manager: Any = None,
|
||||
rag_manager: Any = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""Move direct personal uploads and rewrite RAG owner metadata on user rename."""
|
||||
old_dir = _personal_upload_dir_for_owner(old_owner, create=False)
|
||||
new_dir = _personal_upload_dir_for_owner(new_owner, create=False)
|
||||
path_map: Dict[str, str] = {}
|
||||
moved_files = 0
|
||||
|
||||
if os.path.isdir(old_dir) and old_dir != new_dir:
|
||||
os.makedirs(new_dir, exist_ok=True)
|
||||
for root, _dirs, files in os.walk(old_dir):
|
||||
rel_root = os.path.relpath(root, old_dir)
|
||||
target_root = new_dir if rel_root == "." else os.path.join(new_dir, rel_root)
|
||||
os.makedirs(target_root, exist_ok=True)
|
||||
for filename in files:
|
||||
source = os.path.abspath(os.path.join(root, filename))
|
||||
target = _unique_existing_target(os.path.abspath(os.path.join(target_root, filename)))
|
||||
shutil.move(source, target)
|
||||
path_map[source] = target
|
||||
moved_files += 1
|
||||
_remove_empty_tree(old_dir)
|
||||
|
||||
if personal_docs_manager is not None:
|
||||
rename_directory = getattr(personal_docs_manager, "rename_directory", None)
|
||||
if callable(rename_directory):
|
||||
rename_directory(old_dir, new_dir, path_map=path_map)
|
||||
|
||||
rag_result = None
|
||||
if rag_manager is not None:
|
||||
rename_owner = getattr(rag_manager, "rename_owner", None)
|
||||
if callable(rename_owner):
|
||||
rag_result = rename_owner(
|
||||
old_owner,
|
||||
new_owner,
|
||||
path_map=path_map,
|
||||
path_prefixes=[(old_dir, new_dir)],
|
||||
)
|
||||
|
||||
return {
|
||||
"old_dir": old_dir,
|
||||
"new_dir": new_dir,
|
||||
"moved_files": moved_files,
|
||||
"path_map": path_map,
|
||||
"rag_result": rag_result,
|
||||
}
|
||||
|
||||
|
||||
def setup_personal_routes(personal_docs_manager, rag_manager, rag_available):
|
||||
"""
|
||||
Setup personal documents related routes.
|
||||
@@ -275,11 +358,13 @@ def setup_personal_routes(personal_docs_manager, rag_manager, rag_available):
|
||||
except Exception as e:
|
||||
logger.warning(f"RAG removal failed for {filepath}: {e}")
|
||||
|
||||
# Delete file from disk if it's in uploads dir
|
||||
# Delete file from disk if it's in the caller's own uploads dir.
|
||||
# Scope to the per-owner subdir, not the shared uploads root, so one
|
||||
# admin can't delete another user's personal files by path.
|
||||
deleted_from_disk = False
|
||||
try:
|
||||
abs_target = os.path.abspath(filepath)
|
||||
base_abs = os.path.abspath(UPLOADS_DIR)
|
||||
abs_target = os.path.realpath(filepath)
|
||||
base_abs = os.path.realpath(_personal_upload_dir_for_owner(owner, create=False))
|
||||
in_uploads = (
|
||||
abs_target == base_abs
|
||||
or os.path.commonpath([abs_target, base_abs]) == base_abs
|
||||
|
||||
@@ -12,8 +12,10 @@ from typing import Optional
|
||||
from fastapi import APIRouter, HTTPException, Query, Request
|
||||
from fastapi.responses import HTMLResponse, StreamingResponse
|
||||
from pydantic import BaseModel, Field
|
||||
from core.middleware import INTERNAL_TOOL_USER
|
||||
from src.endpoint_resolver import resolve_endpoint
|
||||
from src.auth_helpers import _auth_disabled, get_current_user
|
||||
from core.auth import RESERVED_USERNAMES
|
||||
from src.constants import DEEP_RESEARCH_DIR
|
||||
|
||||
_SESSION_ID_RE = re.compile(r"^[a-zA-Z0-9-]{1,128}$")
|
||||
@@ -385,9 +387,9 @@ def setup_research_routes(research_handler, session_manager=None) -> APIRouter:
|
||||
"""Launch a research job from the dedicated panel."""
|
||||
from src.auth_helpers import require_privilege
|
||||
user = require_privilege(request, "can_use_research")
|
||||
if user == "internal-tool":
|
||||
if user == INTERNAL_TOOL_USER:
|
||||
tool_owner = (request.headers.get("X-Odysseus-Owner") or "").strip()
|
||||
if tool_owner and tool_owner not in {"internal-tool", "api", "demo", "system"}:
|
||||
if tool_owner and tool_owner not in RESERVED_USERNAMES:
|
||||
auth_mgr = getattr(request.app.state, "auth_manager", None)
|
||||
if auth_mgr is not None and getattr(auth_mgr, "is_configured", False):
|
||||
try:
|
||||
|
||||
@@ -11,7 +11,7 @@ from core.session_manager import SessionManager
|
||||
from core.models import ChatMessage
|
||||
from src.request_models import SessionResponse
|
||||
from core.database import Session as DbSession, SessionLocal, Document, GalleryImage, utcnow_naive
|
||||
from src.auth_helpers import get_current_user, effective_user, _auth_disabled, owner_filter
|
||||
from src.auth_helpers import effective_user, _auth_disabled, owner_filter
|
||||
from src.session_actions import is_session_recently_active
|
||||
|
||||
|
||||
@@ -328,7 +328,7 @@ def setup_session_routes(session_manager: SessionManager, config: dict, webhook_
|
||||
endpoint_id: str = Form(""),
|
||||
):
|
||||
skip_val = str(skip_validation).lower() == "true"
|
||||
user = get_current_user(request)
|
||||
user = effective_user(request)
|
||||
endpoint_api_key = ""
|
||||
endpoint_base_url = ""
|
||||
_reject_raw_endpoint_url_for_non_admin(request, user, endpoint_id, endpoint_url)
|
||||
@@ -477,7 +477,7 @@ def setup_session_routes(session_manager: SessionManager, config: dict, webhook_
|
||||
db.close()
|
||||
# Switch model/endpoint mid-session
|
||||
if model is not None and endpoint_url is not None:
|
||||
user = get_current_user(request)
|
||||
user = effective_user(request)
|
||||
_reject_raw_endpoint_url_for_non_admin(request, user, endpoint_id, endpoint_url)
|
||||
endpoint_api_key = ""
|
||||
endpoint_base_url = ""
|
||||
@@ -1004,6 +1004,7 @@ def setup_session_routes(session_manager: SessionManager, config: dict, webhook_
|
||||
"""
|
||||
from src.llm_core import llm_call
|
||||
user = effective_user(request)
|
||||
single_user_mode = not user and _auth_disabled()
|
||||
user_sessions = session_manager.get_sessions_for_user(user)
|
||||
|
||||
# Delete empty and throwaway sessions before sorting
|
||||
@@ -1022,7 +1023,12 @@ def setup_session_routes(session_manager: SessionManager, config: dict, webhook_
|
||||
}
|
||||
_THROWAWAY_MAX_MESSAGES = 4 # only delete if <= this many messages
|
||||
try:
|
||||
rows = db.query(DbSession).filter(DbSession.archived == False, DbSession.owner == user).limit(2000).all()
|
||||
rows_q = db.query(DbSession).filter(DbSession.archived == False)
|
||||
if user:
|
||||
rows_q = rows_q.filter(DbSession.owner == user)
|
||||
elif not single_user_mode:
|
||||
rows_q = rows_q.filter(DbSession.owner == user)
|
||||
rows = rows_q.limit(2000).all()
|
||||
folder_map = {r.id: r.folder for r in rows}
|
||||
# Precompute per-session message counts in TWO aggregate queries
|
||||
# instead of 1–3 queries PER session — with many chats the per-row
|
||||
@@ -1242,7 +1248,12 @@ def setup_session_routes(session_manager: SessionManager, config: dict, webhook_
|
||||
db = SessionLocal()
|
||||
try:
|
||||
for sid, folder_name in assignments.items():
|
||||
db_session = db.query(DbSession).filter(DbSession.id == sid, DbSession.owner == user).first()
|
||||
db_session_q = db.query(DbSession).filter(DbSession.id == sid)
|
||||
if user:
|
||||
db_session_q = db_session_q.filter(DbSession.owner == user)
|
||||
elif not single_user_mode:
|
||||
db_session_q = db_session_q.filter(DbSession.owner == user)
|
||||
db_session = db_session_q.first()
|
||||
if db_session:
|
||||
db_session.folder = folder_name
|
||||
db_session.updated_at = datetime.utcnow()
|
||||
|
||||
@@ -15,6 +15,7 @@ from collections import namedtuple
|
||||
from pathlib import Path
|
||||
from typing import Dict, Any
|
||||
from core.platform_compat import IS_APPLE_SILICON, which_tool
|
||||
from core.middleware import INTERNAL_TOOL_USER
|
||||
from src.optional_deps import prepare_optional_dependency_import
|
||||
|
||||
# POSIX-only: `pty`/`fcntl` transitively import `termios`, which does NOT exist
|
||||
@@ -55,7 +56,7 @@ def _require_admin(request: Request):
|
||||
# In-process tool loopback. The AuthMiddleware already validated the
|
||||
# internal token + loopback client before setting this marker, so
|
||||
# honour it here as admin-equivalent.
|
||||
if user == "internal-tool":
|
||||
if user == INTERNAL_TOOL_USER:
|
||||
return
|
||||
if not user or user == "api":
|
||||
raise HTTPException(403, "Admin only")
|
||||
|
||||
@@ -691,8 +691,12 @@ async def _run_skill_test_once(md: str, task: str, url, model, headers, owner) -
|
||||
{"role": "user", "content": task},
|
||||
]
|
||||
try:
|
||||
# max_tokens explicitly set: passing 0 lets some upstreams (Ollama,
|
||||
# OpenAI-compat) generate an empty completion, which manifested as
|
||||
# the skill test returning nothing while chat (which carries its
|
||||
# preset's max_tokens) worked. 4096 matches the chat default.
|
||||
async for chunk in stream_agent_loop(url, model, messages, headers=headers,
|
||||
temperature=0.3, max_tokens=0, max_rounds=8, owner=owner):
|
||||
temperature=0.3, max_tokens=4096, max_rounds=8, owner=owner):
|
||||
if not chunk.startswith("data: ") or chunk.strip() == "data: [DONE]":
|
||||
continue
|
||||
try:
|
||||
|
||||
@@ -11,6 +11,7 @@ from fastapi import APIRouter, HTTPException, Request
|
||||
from pydantic import BaseModel
|
||||
|
||||
from core.database import SessionLocal, ScheduledTask, TaskRun
|
||||
from core.middleware import INTERNAL_TOOL_USER
|
||||
from core.constants import internal_api_base
|
||||
from src.auth_helpers import get_current_user
|
||||
from src.constants import DATA_DIR, EMAIL_URGENCY_CACHE_DIR
|
||||
@@ -151,6 +152,7 @@ class TaskCreate(BaseModel):
|
||||
endpoint_url: Optional[str] = None
|
||||
then_task_id: Optional[str] = None # chain: run this task after success
|
||||
notifications_enabled: Optional[bool] = None # None lets action-specific defaults apply
|
||||
character_id: Optional[str] = None # built-in persona id (PERSONAS) — biases output voice
|
||||
|
||||
|
||||
class TaskUpdate(BaseModel):
|
||||
@@ -171,6 +173,7 @@ class TaskUpdate(BaseModel):
|
||||
endpoint_url: Optional[str] = None
|
||||
then_task_id: Optional[str] = None
|
||||
notifications_enabled: Optional[bool] = None
|
||||
character_id: Optional[str] = None
|
||||
|
||||
|
||||
def _display_task_name(t: ScheduledTask) -> str:
|
||||
@@ -203,6 +206,7 @@ def _task_to_dict(t: ScheduledTask, include_last_run_result: bool = False) -> di
|
||||
"output_target": t.output_target,
|
||||
"session_id": t.session_id,
|
||||
"crew_member_id": getattr(t, "crew_member_id", None),
|
||||
"character_id": getattr(t, "character_id", None),
|
||||
"model": t.model,
|
||||
"endpoint_url": t.endpoint_url,
|
||||
"run_count": t.run_count or 0,
|
||||
@@ -424,7 +428,7 @@ def setup_task_routes(task_scheduler) -> APIRouter:
|
||||
# In-process tool-loopback marker — AuthMiddleware validated
|
||||
# the internal token + loopback client before stamping this,
|
||||
# so treat as admin-equivalent.
|
||||
if user == "internal-tool":
|
||||
if user == INTERNAL_TOOL_USER:
|
||||
return True
|
||||
try:
|
||||
from core.auth import AuthManager
|
||||
@@ -552,6 +556,7 @@ def setup_task_routes(task_scheduler) -> APIRouter:
|
||||
then_task_id=then_task_id,
|
||||
webhook_token=webhook_token,
|
||||
notifications_enabled=notifications_enabled,
|
||||
character_id=(req.character_id or None),
|
||||
)
|
||||
db.add(task)
|
||||
db.commit()
|
||||
@@ -705,6 +710,9 @@ def setup_task_routes(task_scheduler) -> APIRouter:
|
||||
task.then_task_id = _validate_then_task_id(db, req.then_task_id, user, current_task_id=task.id)
|
||||
if req.notifications_enabled is not None:
|
||||
task.notifications_enabled = bool(req.notifications_enabled)
|
||||
if req.character_id is not None:
|
||||
# Empty string clears the persona; non-empty stores the id.
|
||||
task.character_id = req.character_id or None
|
||||
if req.cron_expression is not None:
|
||||
if req.cron_expression:
|
||||
try:
|
||||
|
||||
@@ -7,7 +7,7 @@ from fastapi import APIRouter, Request, File, UploadFile, HTTPException
|
||||
from typing import List
|
||||
import logging
|
||||
from core.middleware import require_admin
|
||||
from src.auth_helpers import get_current_user
|
||||
from src.auth_helpers import effective_user
|
||||
from src.upload_handler import count_recent_uploads
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -78,7 +78,7 @@ def setup_upload_routes(upload_handler):
|
||||
|
||||
for u in files:
|
||||
try:
|
||||
meta = upload_handler.save_upload(u, client_ip, owner=get_current_user(request))
|
||||
meta = upload_handler.save_upload(u, client_ip, owner=effective_user(request))
|
||||
out.append({
|
||||
"id": meta["id"],
|
||||
"name": meta["name"],
|
||||
@@ -138,7 +138,7 @@ def setup_upload_routes(upload_handler):
|
||||
original_name = info.get("name", file_id)
|
||||
auth_mgr = getattr(request.app.state, "auth_manager", None)
|
||||
auth_configured = bool(auth_mgr and auth_mgr.is_configured)
|
||||
current_user = get_current_user(request)
|
||||
current_user = effective_user(request)
|
||||
file_owner = info.get("owner") if info else None
|
||||
if auth_configured:
|
||||
if not current_user:
|
||||
@@ -204,7 +204,7 @@ def setup_upload_routes(upload_handler):
|
||||
info = _load_upload_info(file_id)
|
||||
auth_mgr = getattr(request.app.state, "auth_manager", None)
|
||||
auth_configured = bool(auth_mgr and auth_mgr.is_configured)
|
||||
current_user = get_current_user(request)
|
||||
current_user = effective_user(request)
|
||||
file_owner = info.get("owner") if info else None
|
||||
if auth_configured:
|
||||
if not current_user:
|
||||
@@ -247,7 +247,7 @@ def setup_upload_routes(upload_handler):
|
||||
raise HTTPException(404, "File not found")
|
||||
auth_mgr = getattr(request.app.state, "auth_manager", None)
|
||||
auth_configured = bool(auth_mgr and auth_mgr.is_configured)
|
||||
current_user = get_current_user(request)
|
||||
current_user = effective_user(request)
|
||||
file_owner = info.get("owner")
|
||||
if auth_configured:
|
||||
if not current_user:
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
"""Webhook, API Token, and sync chat routes."""
|
||||
|
||||
import asyncio
|
||||
import uuid
|
||||
import logging
|
||||
from typing import Optional
|
||||
@@ -385,10 +384,10 @@ def setup_webhook_routes(
|
||||
sess.add_message(ChatMessage("assistant", reply))
|
||||
session_manager.save_sessions()
|
||||
|
||||
asyncio.create_task(webhook_manager.fire("chat.completed", {
|
||||
webhook_manager.fire_and_forget("chat.completed", {
|
||||
"session_id": session_id, "model": sess.model,
|
||||
"user_message": message[:2000], "response": reply[:2000],
|
||||
}))
|
||||
})
|
||||
|
||||
return {"response": reply, "session_id": session_id, "model": sess.model}
|
||||
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Backfill release_date on entries in services/hwfit/data/hf_models.json.
|
||||
|
||||
Why: the `newest` sort in the cookbook ranks rows by release_date. Anything
|
||||
missing a date sorts to the bottom. This script pulls `created_at` from the
|
||||
HuggingFace API for each catalog entry without one (or all entries when
|
||||
--refresh is passed) and writes the catalog back.
|
||||
|
||||
Usage:
|
||||
python scripts/backfill_model_release_dates.py # missing only
|
||||
python scripts/backfill_model_release_dates.py --refresh # all entries
|
||||
python scripts/backfill_model_release_dates.py --limit 50 # cap requests
|
||||
python scripts/backfill_model_release_dates.py --dry-run # show, don't write
|
||||
|
||||
Auth: set HF_TOKEN env var (or huggingface-cli login) to access gated repos.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
try:
|
||||
from huggingface_hub import HfApi
|
||||
from huggingface_hub.utils import HfHubHTTPError
|
||||
except ImportError:
|
||||
print("Install huggingface_hub: pip install huggingface_hub", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
CATALOG_PATH = Path(__file__).resolve().parent.parent / "services" / "hwfit" / "data" / "hf_models.json"
|
||||
|
||||
|
||||
def fetch_release_date(api: HfApi, repo_id: str) -> str | None:
|
||||
"""Return YYYY-MM-DD release date, or None on miss / error."""
|
||||
try:
|
||||
info = api.model_info(repo_id, files_metadata=False)
|
||||
except HfHubHTTPError as e:
|
||||
# 401 = gated/private, 404 = renamed/deleted. Either way, no date.
|
||||
status = getattr(getattr(e, "response", None), "status_code", None)
|
||||
print(f" {repo_id}: HTTP {status or '?'}", file=sys.stderr)
|
||||
return None
|
||||
except Exception as e:
|
||||
print(f" {repo_id}: {type(e).__name__}: {e}", file=sys.stderr)
|
||||
return None
|
||||
created = getattr(info, "created_at", None)
|
||||
if not created:
|
||||
return None
|
||||
return created.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
p.add_argument("--refresh", action="store_true", help="Overwrite existing release_date too (default: only fill missing).")
|
||||
p.add_argument("--limit", type=int, default=0, help="Stop after N API calls (0 = no limit).")
|
||||
p.add_argument("--dry-run", action="store_true", help="Don't write back; just report.")
|
||||
p.add_argument("--sleep", type=float, default=0.05, help="Seconds to sleep between requests (default 0.05).")
|
||||
args = p.parse_args()
|
||||
|
||||
if not CATALOG_PATH.exists():
|
||||
print(f"Catalog not found: {CATALOG_PATH}", file=sys.stderr)
|
||||
sys.exit(2)
|
||||
|
||||
with CATALOG_PATH.open(encoding="utf-8") as f:
|
||||
catalog = json.load(f)
|
||||
|
||||
candidates = []
|
||||
for i, m in enumerate(catalog):
|
||||
name = m.get("name")
|
||||
if not name:
|
||||
continue
|
||||
existing = (m.get("release_date") or "").strip()
|
||||
if existing and not args.refresh:
|
||||
continue
|
||||
candidates.append(i)
|
||||
|
||||
if args.limit:
|
||||
candidates = candidates[: args.limit]
|
||||
|
||||
print(f"Catalog: {CATALOG_PATH}")
|
||||
print(f"Total entries: {len(catalog)}")
|
||||
print(f"Targets ({'refresh all' if args.refresh else 'missing only'}{'' if not args.limit else f', capped at {args.limit}'}): {len(candidates)}")
|
||||
if not candidates:
|
||||
print("Nothing to do.")
|
||||
return
|
||||
|
||||
api = HfApi(token=os.environ.get("HF_TOKEN") or None)
|
||||
updated = 0
|
||||
skipped = 0
|
||||
started = time.time()
|
||||
for n, idx in enumerate(candidates, start=1):
|
||||
entry = catalog[idx]
|
||||
name = entry["name"]
|
||||
old = (entry.get("release_date") or "").strip()
|
||||
new = fetch_release_date(api, name)
|
||||
if new is None:
|
||||
skipped += 1
|
||||
tag = "skip"
|
||||
elif new == old:
|
||||
tag = "unchanged"
|
||||
else:
|
||||
entry["release_date"] = new
|
||||
updated += 1
|
||||
tag = f"set {new}" + (f" (was {old})" if old else "")
|
||||
print(f"[{n}/{len(candidates)}] {name} — {tag}")
|
||||
if args.sleep:
|
||||
time.sleep(args.sleep)
|
||||
|
||||
elapsed = time.time() - started
|
||||
print()
|
||||
print(f"Done in {elapsed:.1f}s — {updated} updated, {skipped} skipped (HF unavailable / gated / missing date).")
|
||||
|
||||
if args.dry_run:
|
||||
print("Dry run — no write.")
|
||||
return
|
||||
|
||||
if updated:
|
||||
# Atomic write: tmp file in the same dir, then rename. Keeps the
|
||||
# catalog usable even if the process dies mid-write.
|
||||
tmp = CATALOG_PATH.with_suffix(".json.tmp")
|
||||
with tmp.open("w", encoding="utf-8") as f:
|
||||
json.dump(catalog, f, indent=1, ensure_ascii=False)
|
||||
f.write("\n")
|
||||
tmp.replace(CATALOG_PATH)
|
||||
print(f"Wrote {CATALOG_PATH}")
|
||||
else:
|
||||
print("No changes to write.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,341 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Import models from the upstream vllm-project/recipes catalog into our
|
||||
local hf_models.json. Two modes:
|
||||
|
||||
--update-existing Stamp min_vllm_version + vllm_recipe=True on rows we
|
||||
already carry. Cheap, no HF API calls.
|
||||
--add-missing Create new catalog rows for every recipe model we
|
||||
don't carry. Hits the HF API for created_at + downloads
|
||||
(~1 req per missing model, paced).
|
||||
|
||||
Both modes write atomically (tmp + rename) so a crashed run leaves the
|
||||
catalog intact. Default with no mode flags runs both, prefer to pass them
|
||||
explicitly.
|
||||
|
||||
Usage:
|
||||
python scripts/import_from_vllm_recipes.py --update-existing
|
||||
python scripts/import_from_vllm_recipes.py --add-missing
|
||||
python scripts/import_from_vllm_recipes.py --dry-run
|
||||
python scripts/import_from_vllm_recipes.py --limit 10
|
||||
|
||||
Auth: set HF_TOKEN to access gated repos when --add-missing.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
try:
|
||||
import httpx
|
||||
import yaml
|
||||
except ImportError:
|
||||
print("pip install httpx PyYAML", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
try:
|
||||
from huggingface_hub import HfApi
|
||||
from huggingface_hub.utils import HfHubHTTPError
|
||||
except ImportError:
|
||||
HfApi = None
|
||||
HfHubHTTPError = Exception
|
||||
|
||||
|
||||
CATALOG_PATH = Path(__file__).resolve().parent.parent / "services" / "hwfit" / "data" / "hf_models.json"
|
||||
RECIPES_TREE_URL = (
|
||||
"https://api.github.com/repos/vllm-project/recipes/git/trees/main?recursive=1"
|
||||
)
|
||||
RECIPE_RAW_URL = (
|
||||
"https://raw.githubusercontent.com/vllm-project/recipes/main/models/{repo}.yaml"
|
||||
)
|
||||
|
||||
|
||||
# Map recipe `precision` to the closest catalog `quantization` label that
|
||||
# fit.py / models.py already understand.
|
||||
_PRECISION_TO_QUANT = {
|
||||
"fp8": "FP8",
|
||||
"nvfp4": "NVFP4",
|
||||
"mxfp4": "MXFP4",
|
||||
"bf16": "BF16",
|
||||
"fp16": "F16",
|
||||
"f16": "F16",
|
||||
"fp4": "FP4",
|
||||
"int8": "INT8",
|
||||
"int4": "INT4",
|
||||
"awq-4bit": "AWQ-4bit",
|
||||
"awq-8bit": "AWQ-8bit",
|
||||
}
|
||||
|
||||
# Architecture name → use_case fallback. fit.py weights use_case for filtering;
|
||||
# missing field defaults to a generic bucket.
|
||||
_ARCH_USE_CASE = {
|
||||
"moe": "General-purpose reasoning, long-context",
|
||||
"llama": "General-purpose chat",
|
||||
"qwen2": "General-purpose chat",
|
||||
"qwen3": "General-purpose reasoning",
|
||||
"deepseek_v3_moe": "General-purpose reasoning, long-context",
|
||||
"deepseek_v4_moe": "General-purpose reasoning, long-context",
|
||||
}
|
||||
|
||||
|
||||
def _parse_param_count(s) -> int:
|
||||
"""'230B' / '8.6B' / '4.2T' → integer parameter count."""
|
||||
if s is None:
|
||||
return 0
|
||||
s = str(s).strip().replace(",", "")
|
||||
m = re.match(r"^([\d.]+)\s*([KMBT]?)$", s, re.I)
|
||||
if not m:
|
||||
return 0
|
||||
num = float(m.group(1))
|
||||
unit = (m.group(2) or "").upper()
|
||||
mult = {"K": 1e3, "M": 1e6, "B": 1e9, "T": 1e12, "": 1.0}[unit]
|
||||
return int(num * mult)
|
||||
|
||||
|
||||
def _capabilities_for(arch: str, hardware: dict, ctx_len: int, has_reasoning: bool) -> list[str]:
|
||||
caps = []
|
||||
if "moe" in (arch or "").lower():
|
||||
caps.append("moe")
|
||||
if has_reasoning:
|
||||
caps.append("reasoning")
|
||||
if ctx_len and ctx_len >= 100_000:
|
||||
caps.append("long_context")
|
||||
if any(hw in (hardware or {}) for hw in ("mi300x", "mi325x", "mi350x", "mi355x")):
|
||||
caps.append("amd_supported")
|
||||
return caps
|
||||
|
||||
|
||||
def _fetch_manifest(client: httpx.Client) -> set[str]:
|
||||
r = client.get(RECIPES_TREE_URL, headers={"Accept": "application/vnd.github+json"}, timeout=15)
|
||||
r.raise_for_status()
|
||||
tree = (r.json() or {}).get("tree") or []
|
||||
out: set[str] = set()
|
||||
for e in tree:
|
||||
path = (e or {}).get("path") or ""
|
||||
if path.startswith("models/") and path.endswith(".yaml"):
|
||||
body = path[len("models/"):-len(".yaml")]
|
||||
if "/" in body:
|
||||
out.add(body)
|
||||
return out
|
||||
|
||||
|
||||
def _fetch_recipe(client: httpx.Client, repo: str) -> dict | None:
|
||||
url = RECIPE_RAW_URL.format(repo=repo)
|
||||
try:
|
||||
r = client.get(url, timeout=10)
|
||||
if r.status_code != 200:
|
||||
return None
|
||||
return yaml.safe_load(r.text) or {}
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _stamp_from_recipe(entry: dict, recipe: dict) -> bool:
|
||||
"""Mutate entry with recipe-derived fields. Returns True if anything changed."""
|
||||
model = recipe.get("model") or {}
|
||||
meta = recipe.get("meta") or {}
|
||||
features = recipe.get("features") or {}
|
||||
|
||||
changed = False
|
||||
new_min = (model.get("min_vllm_version") or "").strip()
|
||||
if new_min and entry.get("min_vllm_version") != new_min:
|
||||
entry["min_vllm_version"] = new_min
|
||||
changed = True
|
||||
if not entry.get("vllm_recipe"):
|
||||
entry["vllm_recipe"] = True
|
||||
changed = True
|
||||
# Hardware support map — useful for filtering "which models run on my AMD box".
|
||||
hw = meta.get("hardware") or {}
|
||||
if hw and entry.get("recipe_hardware") != hw:
|
||||
entry["recipe_hardware"] = {k: str(v) for k, v in hw.items()}
|
||||
changed = True
|
||||
# Tool/reasoning parser hints — purely informational at catalog level;
|
||||
# the live launch command builder still reads them from the recipe API.
|
||||
if features.get("reasoning") and not entry.get("has_reasoning_parser"):
|
||||
entry["has_reasoning_parser"] = True
|
||||
changed = True
|
||||
if features.get("tool_calling") and not entry.get("has_tool_call_parser"):
|
||||
entry["has_tool_call_parser"] = True
|
||||
changed = True
|
||||
return changed
|
||||
|
||||
|
||||
def _build_new_entry(repo: str, recipe: dict, hf_info=None) -> dict | None:
|
||||
"""Build a fresh catalog entry from a recipe + (optional) HF model info."""
|
||||
model = recipe.get("model") or {}
|
||||
meta = recipe.get("meta") or {}
|
||||
features = recipe.get("features") or {}
|
||||
variants = recipe.get("variants") or {}
|
||||
|
||||
org, name = repo.split("/", 1)
|
||||
raw_params = _parse_param_count(model.get("parameter_count"))
|
||||
active_raw = _parse_param_count(model.get("active_parameters"))
|
||||
ctx = model.get("context_length") or 0
|
||||
|
||||
# Pick the smallest-VRAM variant as the catalog quant — that's what most
|
||||
# users land on first. NVFP4/MXFP4 typically win this on Blackwell;
|
||||
# FP8 elsewhere; BF16 baseline only.
|
||||
pick_quant = None
|
||||
pick_vram = None
|
||||
for vk, vv in variants.items():
|
||||
if not isinstance(vv, dict):
|
||||
continue
|
||||
prec = (vv.get("precision") or "").lower()
|
||||
vram = vv.get("vram_minimum_gb") or 0
|
||||
quant = _PRECISION_TO_QUANT.get(prec)
|
||||
if quant and (pick_vram is None or (vram and vram < pick_vram)):
|
||||
pick_quant = quant
|
||||
pick_vram = vram or pick_vram
|
||||
if not pick_quant:
|
||||
pick_quant = "BF16"
|
||||
|
||||
arch = (model.get("architecture") or "").lower()
|
||||
use_case = _ARCH_USE_CASE.get(arch, "General-purpose chat")
|
||||
caps = _capabilities_for(arch, meta.get("hardware") or {}, ctx, bool(features.get("reasoning")))
|
||||
|
||||
rel_date = ""
|
||||
downloads = 0
|
||||
likes = 0
|
||||
if hf_info is not None:
|
||||
created = getattr(hf_info, "created_at", None)
|
||||
if created:
|
||||
rel_date = created.strftime("%Y-%m-%d")
|
||||
downloads = int(getattr(hf_info, "downloads", 0) or 0)
|
||||
likes = int(getattr(hf_info, "likes", 0) or 0)
|
||||
if not rel_date:
|
||||
rel_date = str(meta.get("date_updated") or datetime.utcnow().strftime("%Y-%m-%d"))
|
||||
|
||||
entry: dict = {
|
||||
"name": repo,
|
||||
"provider": org,
|
||||
"parameter_count": str(model.get("parameter_count") or "?"),
|
||||
"parameters_raw": raw_params,
|
||||
"is_moe": "moe" in arch,
|
||||
"quantization": pick_quant,
|
||||
"context_length": int(ctx or 0),
|
||||
"use_case": use_case,
|
||||
"capabilities": caps,
|
||||
"pipeline_tag": "text-generation",
|
||||
"architecture": arch or "unknown",
|
||||
"hf_downloads": downloads,
|
||||
"hf_likes": likes,
|
||||
"release_date": rel_date,
|
||||
# Recipe-derived bits.
|
||||
"vllm_recipe": True,
|
||||
"min_vllm_version": (model.get("min_vllm_version") or "").strip() or None,
|
||||
"recipe_hardware": {k: str(v) for k, v in (meta.get("hardware") or {}).items()},
|
||||
"has_reasoning_parser": bool(features.get("reasoning")),
|
||||
"has_tool_call_parser": bool(features.get("tool_calling")),
|
||||
}
|
||||
if active_raw:
|
||||
entry["active_parameters"] = active_raw
|
||||
if pick_vram:
|
||||
# min_vram_gb is what hwfit uses for "does this fit". Recipe states a
|
||||
# minimum for the chosen variant; round up slightly for KV-cache room.
|
||||
entry["min_vram_gb"] = float(pick_vram)
|
||||
entry["min_ram_gb"] = float(round(pick_vram * 0.6, 1))
|
||||
entry["recommended_ram_gb"] = float(round(pick_vram * 1.2, 1))
|
||||
# Drop empty / None fields to keep the JSON tidy.
|
||||
return {k: v for k, v in entry.items() if v not in (None, "", [], {})}
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
p.add_argument("--update-existing", action="store_true", help="Stamp min_vllm_version + vllm_recipe on existing rows.")
|
||||
p.add_argument("--add-missing", action="store_true", help="Add new rows for recipe models not in the catalog.")
|
||||
p.add_argument("--limit", type=int, default=0, help="Stop after N recipe fetches.")
|
||||
p.add_argument("--dry-run", action="store_true", help="Don't write back; just report.")
|
||||
p.add_argument("--sleep", type=float, default=0.05, help="Seconds between HTTP requests.")
|
||||
args = p.parse_args()
|
||||
if not args.update_existing and not args.add_missing:
|
||||
args.update_existing = args.add_missing = True
|
||||
|
||||
with CATALOG_PATH.open(encoding="utf-8") as f:
|
||||
catalog = json.load(f)
|
||||
by_name = {m.get("name"): m for m in catalog if m.get("name")}
|
||||
|
||||
client = httpx.Client(follow_redirects=True)
|
||||
print(f"Catalog: {CATALOG_PATH} ({len(catalog)} entries)")
|
||||
print("Fetching upstream manifest…")
|
||||
try:
|
||||
manifest = _fetch_manifest(client)
|
||||
except Exception as e:
|
||||
print(f"FATAL: manifest fetch failed: {e}", file=sys.stderr)
|
||||
sys.exit(2)
|
||||
print(f"Manifest: {len(manifest)} recipes")
|
||||
|
||||
existing = sorted(by_name.keys() & manifest)
|
||||
missing = sorted(manifest - by_name.keys())
|
||||
print(f"Match catalog ↔ manifest: existing={len(existing)} missing={len(missing)}")
|
||||
|
||||
targets: list[tuple[str, str]] = [] # (repo, action)
|
||||
if args.update_existing:
|
||||
targets.extend((r, "update") for r in existing)
|
||||
if args.add_missing:
|
||||
targets.extend((r, "add") for r in missing)
|
||||
if args.limit:
|
||||
targets = targets[: args.limit]
|
||||
print(f"Targets: {len(targets)}")
|
||||
|
||||
hf_api = HfApi(token=os.environ.get("HF_TOKEN") or None) if HfApi else None
|
||||
updated = added = skipped = 0
|
||||
started = time.time()
|
||||
|
||||
for n, (repo, action) in enumerate(targets, 1):
|
||||
recipe = _fetch_recipe(client, repo)
|
||||
if not recipe:
|
||||
print(f"[{n}/{len(targets)}] {repo:55} skip (no recipe fetched)")
|
||||
skipped += 1
|
||||
time.sleep(args.sleep)
|
||||
continue
|
||||
if action == "update":
|
||||
entry = by_name[repo]
|
||||
if _stamp_from_recipe(entry, recipe):
|
||||
updated += 1
|
||||
print(f"[{n}/{len(targets)}] {repo:55} updated")
|
||||
else:
|
||||
print(f"[{n}/{len(targets)}] {repo:55} unchanged")
|
||||
else: # add
|
||||
hf_info = None
|
||||
if hf_api:
|
||||
try:
|
||||
hf_info = hf_api.model_info(repo, files_metadata=False)
|
||||
except HfHubHTTPError as e:
|
||||
code = getattr(getattr(e, "response", None), "status_code", "?")
|
||||
print(f" HF {code} for {repo} — building from recipe only", file=sys.stderr)
|
||||
except Exception as e:
|
||||
print(f" HF error for {repo}: {e}", file=sys.stderr)
|
||||
new_entry = _build_new_entry(repo, recipe, hf_info)
|
||||
if new_entry:
|
||||
catalog.append(new_entry)
|
||||
by_name[repo] = new_entry
|
||||
added += 1
|
||||
print(f"[{n}/{len(targets)}] {repo:55} added ({new_entry.get('parameter_count','?')}, {new_entry.get('quantization','?')})")
|
||||
else:
|
||||
skipped += 1
|
||||
print(f"[{n}/{len(targets)}] {repo:55} skip (couldn't build entry)")
|
||||
time.sleep(args.sleep)
|
||||
|
||||
elapsed = time.time() - started
|
||||
print()
|
||||
print(f"Done in {elapsed:.1f}s — added={added}, updated={updated}, skipped={skipped}")
|
||||
|
||||
if args.dry_run:
|
||||
print("Dry run — no write.")
|
||||
return
|
||||
if added or updated:
|
||||
tmp = CATALOG_PATH.with_suffix(".json.tmp")
|
||||
with tmp.open("w", encoding="utf-8") as f:
|
||||
json.dump(catalog, f, indent=1, ensure_ascii=False)
|
||||
f.write("\n")
|
||||
tmp.replace(CATALOG_PATH)
|
||||
print(f"Wrote {CATALOG_PATH} ({len(catalog)} entries)")
|
||||
else:
|
||||
print("No changes — catalog untouched.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -103,9 +103,13 @@ def cmd_list(args) -> None:
|
||||
end = _parse_dt(args.end) if args.end else (start + timedelta(days=30))
|
||||
db = SessionLocal()
|
||||
try:
|
||||
# Overlap semantics, matching the web route (routes/calendar_routes.py)
|
||||
# and the recurring-expansion contract: an event is in the window when
|
||||
# it starts before the window end AND ends after the window start. This
|
||||
# includes multi-day / in-progress events that began before `start`.
|
||||
q = db.query(CalendarEvent).filter(
|
||||
CalendarEvent.dtstart >= start,
|
||||
CalendarEvent.dtstart < end,
|
||||
CalendarEvent.dtend > start,
|
||||
)
|
||||
if args.calendar:
|
||||
cal = db.query(CalendarCal).filter(CalendarCal.name == args.calendar).first()
|
||||
|
||||
@@ -19,6 +19,10 @@ GPU_BANDWIDTH = {
|
||||
"6950 xt": 576, "6900 xt": 512, "6800 xt": 512, "6800": 512, "6700 xt": 384, "6600 xt": 256, "6600": 224,
|
||||
"mi300x": 5300, "mi300": 5300, "mi250x": 3277, "mi250": 3277, "mi210": 1638, "mi100": 1229,
|
||||
"9070 xt": 624, "9070": 488, "9060 xt": 322, "9060": 322,
|
||||
# NVIDIA GB10 Grace-Blackwell superchip (DGX Spark). Unified LPDDR5X memory,
|
||||
# not Apple Silicon, so it lives in the generic GPU table — the Apple-only
|
||||
# lookup never matches it (its name carries no "apple").
|
||||
"gb10": 273,
|
||||
}
|
||||
|
||||
# Pre-sort keys by length descending for correct substring matching
|
||||
@@ -109,10 +113,15 @@ def _lookup_bandwidth(system):
|
||||
if not isinstance(gpu_name, str) or not gpu_name:
|
||||
return None
|
||||
|
||||
if isinstance(system, dict):
|
||||
bw = _lookup_apple_bandwidth(system)
|
||||
if bw is not None:
|
||||
return bw
|
||||
# Apple tiers live only in the Apple-specific table now (#2564), so route
|
||||
# BOTH dict and bare-string callers through it. A bare string carries no
|
||||
# gpu_cores, so the helper falls back to the conservative (lowest) tier for
|
||||
# that model -- before #2564 the generic table answered string lookups, and
|
||||
# dropping that made _lookup_bandwidth("Apple M3 Max") return None.
|
||||
apple_input = system if isinstance(system, dict) else {"gpu_name": gpu_name}
|
||||
bw = _lookup_apple_bandwidth(apple_input)
|
||||
if bw is not None:
|
||||
return bw
|
||||
|
||||
gn = gpu_name.lower()
|
||||
for key in _BW_KEYS_SORTED:
|
||||
@@ -121,6 +130,44 @@ def _lookup_bandwidth(system):
|
||||
return None
|
||||
|
||||
|
||||
def _canonical_cpu_backend(system):
|
||||
"""Return the canonical CPU backend for cpu_only speed estimation.
|
||||
|
||||
Normalizes CPU-architecture aliases separately from the GPU backend, and
|
||||
overrides GPU-only backends (CUDA/ROCm/Metal) so they do not inherit a
|
||||
discrete-GPU fallback constant when the model is actually running on CPU.
|
||||
"""
|
||||
backend = (system.get("backend") or "").lower().strip()
|
||||
cpu_arch = (system.get("cpu_arch") or "").lower().strip()
|
||||
cpu_name = (system.get("cpu_name") or "").lower()
|
||||
gpu_name = (system.get("gpu_name") or "").lower()
|
||||
|
||||
# Already-canonical CPU backends
|
||||
if backend in ("cpu_x86", "cpu_arm"):
|
||||
return backend
|
||||
|
||||
# Raw CPU-architecture aliases. Treat plain "arm" as 32-bit ARM, not the
|
||||
# ARM64-class CPU fallback used for Apple Silicon/aarch64 machines.
|
||||
if backend in ("x86_64", "amd64", "i386", "i686"):
|
||||
return "cpu_x86"
|
||||
if backend in ("arm64", "aarch64"):
|
||||
return "cpu_arm"
|
||||
|
||||
# Prefer an explicit CPU architecture field when present
|
||||
if cpu_arch:
|
||||
if cpu_arch in ("x86_64", "amd64", "x86", "i386", "i686"):
|
||||
return "cpu_x86"
|
||||
if cpu_arch in ("arm64", "aarch64"):
|
||||
return "cpu_arm"
|
||||
|
||||
# Apple Silicon enters ranking as backend="metal"; its CPU path is ARM.
|
||||
if backend in ("metal", "mps", "apple") or "apple" in cpu_name or "apple" in gpu_name:
|
||||
return "cpu_arm"
|
||||
|
||||
# Conservative default for CUDA/ROCm/discrete GPU backends and unknowns.
|
||||
return "cpu_x86"
|
||||
|
||||
|
||||
def _estimate_speed(model, quant, run_mode, system, offload_frac=0.0):
|
||||
"""Estimate tok/s. Uses active params for MoE (only active experts run per token).
|
||||
|
||||
@@ -138,6 +185,11 @@ def _estimate_speed(model, quant, run_mode, system, offload_frac=0.0):
|
||||
bw = _lookup_bandwidth(system)
|
||||
backend = system.get("backend", "cpu_x86")
|
||||
|
||||
# CPU-only inference must never inherit a GPU backend's fallback constant,
|
||||
# even if the detected system happens to report a CUDA/Metal/ROCm backend.
|
||||
if run_mode == "cpu_only":
|
||||
backend = _canonical_cpu_backend(system)
|
||||
|
||||
if bw and run_mode in ("gpu", "cpu_offload"):
|
||||
bpp = QUANT_BYTES_PER_PARAM.get(quant, 0.5)
|
||||
model_gb = pb * bpp
|
||||
|
||||
@@ -320,7 +320,7 @@ def _detect_apple_silicon():
|
||||
|
||||
# Only Apple Silicon (arm64) has a Metal GPU worth serving LLMs on; Intel
|
||||
# Macs fall through to the CPU path.
|
||||
if "arm" not in arch and "aarch64" not in arch:
|
||||
if _canonical_cpu_arch(arch) != "arm64":
|
||||
return None
|
||||
|
||||
# Chip name, e.g. "Apple M4 Max" — carries the Pro/Max/Ultra variant that
|
||||
@@ -503,6 +503,25 @@ def _get_cpu_count():
|
||||
return os.cpu_count() or 1
|
||||
|
||||
|
||||
def _canonical_cpu_arch(value):
|
||||
arch = str(value or "").lower().strip().replace("-", "_")
|
||||
if arch in ("x86_64", "amd64", "x64"):
|
||||
return "x86_64"
|
||||
if arch in ("i386", "i686", "x86"):
|
||||
return "x86"
|
||||
if arch in ("arm64", "aarch64"):
|
||||
return "arm64"
|
||||
if arch == "arm" or arch.startswith("armv"):
|
||||
return "arm"
|
||||
return arch
|
||||
|
||||
|
||||
def _get_cpu_arch():
|
||||
if _remote_host:
|
||||
return _canonical_cpu_arch(_run(["uname", "-m"]) or "")
|
||||
return _canonical_cpu_arch(platform.machine())
|
||||
|
||||
|
||||
def _powershell_exe():
|
||||
"""Pick the best PowerShell executable for LOCAL execution: prefer pwsh
|
||||
(PowerShell 7+), fall back to Windows PowerShell 5.1. Returns an absolute
|
||||
@@ -528,6 +547,7 @@ def _detect_windows():
|
||||
$r.cpu_name = $cpu.Name
|
||||
$r.cpu_cores = (Get-CimInstance Win32_Processor | Measure-Object -Property NumberOfLogicalProcessors -Sum).Sum
|
||||
$r.arch = $cpu.AddressWidth
|
||||
$r.cpu_arch = if ($env:PROCESSOR_ARCHITEW6432) { $env:PROCESSOR_ARCHITEW6432 } else { $env:PROCESSOR_ARCHITECTURE }
|
||||
# GPU detection via nvidia-smi (fastest) or WMI fallback
|
||||
try {
|
||||
$nv = nvidia-smi --query-gpu=memory.total,name --format=csv,noheader,nounits 2>$null
|
||||
@@ -599,6 +619,7 @@ def _detect_windows():
|
||||
"available_ram_gb": d.get("avail_gb", 0),
|
||||
"cpu_cores": _as_int(d.get("cpu_cores"), 1),
|
||||
"cpu_name": _cpu_name,
|
||||
"cpu_arch": _canonical_cpu_arch(d.get("cpu_arch")),
|
||||
"has_gpu": bool(d.get("gpu_name")),
|
||||
"gpu_name": d.get("gpu_name"),
|
||||
"gpu_vram_gb": d.get("gpu_vram_gb"),
|
||||
@@ -794,6 +815,7 @@ def detect_system(host="", ssh_port="", platform="", fresh=False):
|
||||
available_ram = round(_get_available_ram_gb(), 1)
|
||||
cpu_cores = _get_cpu_count()
|
||||
cpu_name = _get_cpu_name()
|
||||
cpu_arch = _get_cpu_arch()
|
||||
|
||||
gpu_info = _detect_apple_silicon() or _detect_nvidia() or _detect_amd()
|
||||
|
||||
@@ -803,6 +825,7 @@ def detect_system(host="", ssh_port="", platform="", fresh=False):
|
||||
"available_ram_gb": available_ram,
|
||||
"cpu_cores": cpu_cores,
|
||||
"cpu_name": cpu_name,
|
||||
"cpu_arch": cpu_arch,
|
||||
"has_gpu": True,
|
||||
"gpu_name": gpu_info["gpu_name"],
|
||||
"gpu_vram_gb": gpu_info["gpu_vram_gb"],
|
||||
@@ -817,17 +840,13 @@ def detect_system(host="", ssh_port="", platform="", fresh=False):
|
||||
"unified_memory": gpu_info.get("unified_memory", False),
|
||||
}
|
||||
else:
|
||||
if _remote_host:
|
||||
arch_out = _run(["uname", "-m"]) or ""
|
||||
else:
|
||||
import platform as _platform
|
||||
arch_out = _platform.machine().lower()
|
||||
backend = "cpu_arm" if "aarch64" in arch_out or "arm" in arch_out else "cpu_x86"
|
||||
backend = "cpu_arm" if cpu_arch == "arm64" else "cpu_x86"
|
||||
result = {
|
||||
"total_ram_gb": total_ram,
|
||||
"available_ram_gb": available_ram,
|
||||
"cpu_cores": cpu_cores,
|
||||
"cpu_name": cpu_name,
|
||||
"cpu_arch": cpu_arch,
|
||||
"has_gpu": False,
|
||||
"gpu_name": None,
|
||||
"gpu_vram_gb": None,
|
||||
|
||||
@@ -15,6 +15,8 @@ from urllib.parse import urljoin, urlparse
|
||||
import httpx
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
from src.constants import WEB_FETCH_SOFT_MAX_BYTES, WEB_FETCH_HARD_MAX_BYTES, WEB_FETCH_USER_AGENT
|
||||
|
||||
from .analytics import RateLimitError, error_logger
|
||||
from .cache import (
|
||||
CONTENT_CACHE_DIR,
|
||||
@@ -89,18 +91,128 @@ def _public_http_url(url: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _get_public_url(url: str, headers: dict, timeout: int, max_redirects: int = 5) -> httpx.Response:
|
||||
class BodyTooLargeError(Exception):
|
||||
"""The server declared a body larger than the hard fetch ceiling."""
|
||||
|
||||
def __init__(self, url: str, declared_bytes: int):
|
||||
self.url = url
|
||||
self.declared_bytes = declared_bytes
|
||||
super().__init__(
|
||||
f"response body is {declared_bytes:,} bytes, over the "
|
||||
f"{WEB_FETCH_HARD_MAX_BYTES:,}-byte hard cap"
|
||||
)
|
||||
|
||||
|
||||
class _CappedFetch:
|
||||
"""Result of a size-capped streaming GET.
|
||||
|
||||
Carries just what fetch_webpage_content needs from an httpx.Response,
|
||||
plus the cap bookkeeping: the (possibly truncated) body, whether the
|
||||
cap cut it short, and the size the server declared via Content-Length
|
||||
(wire bytes; None when absent).
|
||||
"""
|
||||
|
||||
__slots__ = ("status_code", "headers", "content", "truncated",
|
||||
"declared_bytes", "encoding", "url")
|
||||
|
||||
def __init__(self, status_code, headers, content, truncated,
|
||||
declared_bytes, encoding, url):
|
||||
self.status_code = status_code
|
||||
self.headers = headers
|
||||
self.content = content
|
||||
self.truncated = truncated
|
||||
self.declared_bytes = declared_bytes
|
||||
self.encoding = encoding
|
||||
self.url = url
|
||||
|
||||
@property
|
||||
def text(self) -> str:
|
||||
return self.content.decode(self.encoding or "utf-8", errors="replace")
|
||||
|
||||
def raise_for_status(self):
|
||||
if self.status_code >= 400:
|
||||
request = httpx.Request("GET", self.url)
|
||||
raise httpx.HTTPStatusError(
|
||||
f"HTTP {self.status_code} for {self.url}",
|
||||
request=request,
|
||||
response=httpx.Response(self.status_code, request=request),
|
||||
)
|
||||
|
||||
|
||||
def _get_public_url(url: str, headers: dict, timeout: int, max_redirects: int = 5,
|
||||
max_bytes: int = None) -> "_CappedFetch":
|
||||
"""Capped streaming GET with SSRF-guarded manual redirects.
|
||||
|
||||
The body is streamed and buffering stops at ``max_bytes`` (default: the
|
||||
soft cap), so an oversized resource cannot be pulled into memory or the
|
||||
content cache in full. When Content-Length already declares a body over
|
||||
the hard ceiling, the fetch is refused before any body bytes are read.
|
||||
"""
|
||||
cap = min(max_bytes or WEB_FETCH_SOFT_MAX_BYTES, WEB_FETCH_HARD_MAX_BYTES)
|
||||
current = url
|
||||
for _ in range(max_redirects + 1):
|
||||
if not _public_http_url(current):
|
||||
raise httpx.RequestError("Blocked private/internal URL", request=httpx.Request("GET", current))
|
||||
response = httpx.get(current, headers=headers, timeout=timeout, follow_redirects=False)
|
||||
if response.status_code not in (301, 302, 303, 307, 308):
|
||||
return response
|
||||
location = response.headers.get("location")
|
||||
if not location:
|
||||
return response
|
||||
current = urljoin(str(response.url), location)
|
||||
# Force identity transfer-encoding. With gzip/deflate the wire bytes
|
||||
# (and Content-Length) can be a small fraction of the decoded body, so
|
||||
# a tiny compressed response could pass the hard-cap preflight and then
|
||||
# expand past the ceiling in a single decoded chunk before the streamed
|
||||
# cap below can slice it. Identity makes Content-Length the true body
|
||||
# size and keeps each streamed chunk bounded by the network read.
|
||||
req_headers = dict(headers or {})
|
||||
req_headers["Accept-Encoding"] = "identity"
|
||||
with httpx.stream("GET", current, headers=req_headers, timeout=timeout,
|
||||
follow_redirects=False) as response:
|
||||
if response.status_code in (301, 302, 303, 307, 308):
|
||||
location = response.headers.get("location")
|
||||
if not location:
|
||||
return _CappedFetch(response.status_code, response.headers, b"",
|
||||
False, None, response.encoding, str(response.url))
|
||||
current = urljoin(str(response.url), location)
|
||||
continue
|
||||
|
||||
# A server can ignore the identity request and still return a
|
||||
# compressed body; httpx.iter_bytes would then decode it, and a tiny
|
||||
# gzip can balloon into one decoded chunk far past the cap before we
|
||||
# slice. Refuse a compressed Content-Encoding so the streamed cap
|
||||
# stays a real memory bound (Content-Length is the compressed wire
|
||||
# length here, so the preflight and size metadata are unreliable too).
|
||||
enc = (response.headers.get("content-encoding") or "").strip().lower()
|
||||
if enc and enc != "identity":
|
||||
raise httpx.RequestError(
|
||||
f"Refusing compressed response (Content-Encoding: {enc}) after "
|
||||
"requesting identity: cannot bound decoded body size",
|
||||
request=httpx.Request("GET", current),
|
||||
)
|
||||
|
||||
declared = None
|
||||
raw_len = response.headers.get("content-length")
|
||||
if raw_len and raw_len.isdigit():
|
||||
declared = int(raw_len)
|
||||
# Refuse before buffering anything when the server already tells
|
||||
# us the body exceeds the absolute ceiling (Content-Length is wire
|
||||
# bytes; the decompressed body can only be larger).
|
||||
if declared is not None and declared > WEB_FETCH_HARD_MAX_BYTES:
|
||||
raise BodyTooLargeError(current, declared)
|
||||
|
||||
chunks = []
|
||||
read = 0
|
||||
truncated = False
|
||||
# We requested identity above, so iter_bytes yields the raw body in
|
||||
# network-read-sized chunks (no decompression expansion); the cap
|
||||
# therefore bounds what we actually buffer.
|
||||
for chunk in response.iter_bytes():
|
||||
read += len(chunk)
|
||||
if read > cap:
|
||||
keep = cap - (read - len(chunk))
|
||||
if keep > 0:
|
||||
chunks.append(chunk[:keep])
|
||||
truncated = True
|
||||
break
|
||||
chunks.append(chunk)
|
||||
return _CappedFetch(response.status_code, response.headers,
|
||||
b"".join(chunks), truncated, declared,
|
||||
response.encoding, str(response.url))
|
||||
raise httpx.RequestError("Too many redirects", request=httpx.Request("GET", current))
|
||||
|
||||
# PDF extraction (optional dependency)
|
||||
@@ -222,9 +334,19 @@ def _empty_result(url: str, error: str = "") -> dict:
|
||||
# ----------------------------------------------------------------------
|
||||
# Main content fetcher
|
||||
# ----------------------------------------------------------------------
|
||||
def fetch_webpage_content(url: str, timeout: int = 5, retry_attempt: int = 0) -> dict:
|
||||
"""Fetch and extract meaningful content from a webpage with caching."""
|
||||
cache_key = generate_cache_key(url)
|
||||
def fetch_webpage_content(url: str, timeout: int = 5, retry_attempt: int = 0,
|
||||
max_bytes: int = None) -> dict:
|
||||
"""Fetch and extract meaningful content from a webpage with caching.
|
||||
|
||||
``max_bytes`` raises the download budget per call (clamped to the hard
|
||||
cap); the default is the soft cap. When the body is cut short the result
|
||||
carries ``truncated``/``fetched_bytes``/``total_bytes`` so callers can
|
||||
tell the model the content is partial (#3812).
|
||||
"""
|
||||
effective_cap = min(max_bytes or WEB_FETCH_SOFT_MAX_BYTES, WEB_FETCH_HARD_MAX_BYTES)
|
||||
# The cap is part of the cache identity: a truncated soft-cap fetch must
|
||||
# not be served to a later full-budget request for the same URL.
|
||||
cache_key = generate_cache_key(f"{url}#cap={effective_cap}")
|
||||
cache_file = CONTENT_CACHE_DIR / f"{cache_key}.cache"
|
||||
|
||||
# Check cache
|
||||
@@ -247,18 +369,24 @@ def fetch_webpage_content(url: str, timeout: int = 5, retry_attempt: int = 0) ->
|
||||
# Fetch
|
||||
try:
|
||||
headers = {
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
|
||||
"User-Agent": WEB_FETCH_USER_AGENT,
|
||||
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
|
||||
"Accept-Language": "en-US,en;q=0.5",
|
||||
"Accept-Encoding": "gzip, deflate",
|
||||
# identity so the streamed size cap in _get_public_url stays honest
|
||||
# (a compressed body can decode to far more than Content-Length).
|
||||
"Accept-Encoding": "identity",
|
||||
"Connection": "keep-alive",
|
||||
}
|
||||
response = _get_public_url(url, headers=headers, timeout=timeout)
|
||||
response = _get_public_url(url, headers=headers, timeout=timeout,
|
||||
max_bytes=effective_cap)
|
||||
|
||||
if response.status_code == 429:
|
||||
raise RateLimitError(f"Rate limit hit for {url} (attempt {retry_attempt})")
|
||||
|
||||
response.raise_for_status()
|
||||
except BodyTooLargeError as e:
|
||||
error_logger.warning(f"Refused oversized body for {url}: {e}")
|
||||
return _empty_result(url, f"TooLarge: {e}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
error_logger.warning(f"HTTP {e.response.status_code} fetching {url}: {e}")
|
||||
return _empty_result(url, f"HTTP {e.response.status_code}: {e}")
|
||||
@@ -269,9 +397,27 @@ def fetch_webpage_content(url: str, timeout: int = 5, retry_attempt: int = 0) ->
|
||||
error_logger.error(str(e))
|
||||
return _empty_result(url, str(e))
|
||||
|
||||
# Size bookkeeping shared by every content branch below. getattr keeps
|
||||
# plain httpx.Response stand-ins (tests) working without the cap fields.
|
||||
_size_fields = {
|
||||
"truncated": getattr(response, "truncated", False),
|
||||
"fetched_bytes": len(response.content),
|
||||
"total_bytes": getattr(response, "declared_bytes", None),
|
||||
}
|
||||
|
||||
# PDF handling
|
||||
content_type = response.headers.get("Content-Type", "").lower()
|
||||
if "application/pdf" in content_type or url.lower().endswith(".pdf"):
|
||||
if _size_fields["truncated"]:
|
||||
# A PDF cut mid-stream is not parseable; unlike text there is no
|
||||
# useful partial result, so report the budget problem instead.
|
||||
_declared = _size_fields["total_bytes"]
|
||||
return _empty_result(
|
||||
url,
|
||||
f"TooLarge: PDF exceeds the {effective_cap:,}-byte fetch budget"
|
||||
+ (f" (size {_declared:,} bytes)" if _declared else "")
|
||||
+ "; retry with a larger budget if it fits under the hard cap",
|
||||
)
|
||||
if pdf_extract_text is None:
|
||||
logger.error("pdfminer.six is not installed; cannot extract PDF text.")
|
||||
pdf_text = ""
|
||||
@@ -295,6 +441,7 @@ def fetch_webpage_content(url: str, timeout: int = 5, retry_attempt: int = 0) ->
|
||||
"js_message": "",
|
||||
"success": bool(pdf_text),
|
||||
"error": "" if pdf_text else "Failed to extract PDF text",
|
||||
**_size_fields,
|
||||
}
|
||||
_cache_result(cache_file, cache_key, result, url)
|
||||
return result
|
||||
@@ -329,6 +476,7 @@ def fetch_webpage_content(url: str, timeout: int = 5, retry_attempt: int = 0) ->
|
||||
"js_message": "",
|
||||
"success": bool(text_body),
|
||||
"error": "" if text_body else "Empty response body",
|
||||
**_size_fields,
|
||||
}
|
||||
_cache_result(cache_file, cache_key, result, url)
|
||||
return result
|
||||
@@ -391,6 +539,7 @@ def fetch_webpage_content(url: str, timeout: int = 5, retry_attempt: int = 0) ->
|
||||
"js_message": js_message,
|
||||
"success": True,
|
||||
"error": "",
|
||||
**_size_fields,
|
||||
}
|
||||
_cache_result(cache_file, cache_key, result, url)
|
||||
return result
|
||||
|
||||
@@ -9,14 +9,12 @@ from urllib.parse import urljoin, urlparse, parse_qs
|
||||
import httpx
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
from src.constants import SEARXNG_INSTANCE
|
||||
from src.constants import SEARXNG_INSTANCE, REQUEST_TIMEOUT, WEB_FETCH_USER_AGENT
|
||||
from .analytics import RateLimitError, error_logger
|
||||
from .query import build_enhanced_query
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
REQUEST_TIMEOUT = 20
|
||||
|
||||
# Provider registry — maps setting value to (label, needs_key, needs_url)
|
||||
PROVIDER_INFO = {
|
||||
"searxng": ("SearXNG", False, True),
|
||||
@@ -140,7 +138,7 @@ def searxng_search_api(query: str, count: Optional[int] = None, categories: str
|
||||
count = count if count is not None else _get_result_count()
|
||||
instance = _get_search_instance()
|
||||
api_key = ""
|
||||
headers = {"User-Agent": "Mozilla/5.0"}
|
||||
headers = {"User-Agent": WEB_FETCH_USER_AGENT}
|
||||
if api_key:
|
||||
headers["Authorization"] = f"Bearer {api_key}"
|
||||
# News/fresh queries do badly in the 'general' category — it favours
|
||||
@@ -252,7 +250,7 @@ def searxng_search(query, max_results=10):
|
||||
"""Search using SearXNG instance - parsing HTML."""
|
||||
instance = _get_search_instance()
|
||||
api_key = ""
|
||||
req_headers = {"User-Agent": "Mozilla/5.0"}
|
||||
req_headers = {"User-Agent": WEB_FETCH_USER_AGENT}
|
||||
if api_key:
|
||||
req_headers["Authorization"] = f"Bearer {api_key}"
|
||||
try:
|
||||
@@ -391,7 +389,7 @@ def duckduckgo_search(query: str, count: Optional[int] = None, time_filter: Opti
|
||||
response = httpx.get(
|
||||
"https://html.duckduckgo.com/html/",
|
||||
params={"q": query, "kp": _safesearch_for("duckduckgo_html")},
|
||||
headers={"User-Agent": "Mozilla/5.0"},
|
||||
headers={"User-Agent": WEB_FETCH_USER_AGENT},
|
||||
timeout=REQUEST_TIMEOUT,
|
||||
)
|
||||
response.raise_for_status()
|
||||
|
||||
@@ -16,8 +16,9 @@ sys.path.insert(0, BASE_DIR)
|
||||
from src.constants import (
|
||||
DATA_DIR, AUTH_FILE, UPLOAD_DIR, PERSONAL_DIR, PERSONAL_UPLOADS_DIR,
|
||||
TTS_CACHE_DIR, GENERATED_IMAGES_DIR, DEEP_RESEARCH_DIR, CHROMA_DIR,
|
||||
RAG_DIR, MEMORY_VECTORS_DIR,
|
||||
RAG_DIR, MEMORY_VECTORS_DIR, PASSWORD_MIN_LENGTH,
|
||||
)
|
||||
from core.auth import RESERVED_USERNAMES
|
||||
|
||||
DIRS = [
|
||||
DATA_DIR,
|
||||
@@ -59,15 +60,23 @@ def _prompt_admin_credentials():
|
||||
print(" (Press Enter to accept defaults)")
|
||||
print()
|
||||
|
||||
username = input(" Username [admin]: ").strip().lower()
|
||||
if not username:
|
||||
username = "admin"
|
||||
while True:
|
||||
username = input(" Username [admin]: ").strip().lower()
|
||||
if not username:
|
||||
username = "admin"
|
||||
if username in RESERVED_USERNAMES:
|
||||
print(f" '{username}' is a reserved username. Choose another.")
|
||||
continue
|
||||
break
|
||||
|
||||
while True:
|
||||
password = getpass.getpass(" Password: ")
|
||||
if not password:
|
||||
print(" Password cannot be empty.")
|
||||
continue
|
||||
if len(password) < PASSWORD_MIN_LENGTH:
|
||||
print(f" Password must be at least {PASSWORD_MIN_LENGTH} characters.")
|
||||
continue
|
||||
confirm = getpass.getpass(" Confirm password: ")
|
||||
if password != confirm:
|
||||
print(" Passwords don't match. Try again.")
|
||||
@@ -93,8 +102,13 @@ def create_default_admin():
|
||||
password = os.getenv("ODYSSEUS_ADMIN_PASSWORD", "").strip()
|
||||
|
||||
if username and password:
|
||||
# Both provided via env — use them directly
|
||||
pass
|
||||
# Both provided via env — validate before using
|
||||
if username in RESERVED_USERNAMES:
|
||||
print(f" [error] ODYSSEUS_ADMIN_USER '{username}' is a reserved username")
|
||||
return "failed"
|
||||
if len(password) < PASSWORD_MIN_LENGTH:
|
||||
print(f" [error] ODYSSEUS_ADMIN_PASSWORD must be at least {PASSWORD_MIN_LENGTH} characters")
|
||||
return "failed"
|
||||
elif sys.stdin.isatty() and not os.getenv("ODYSSEUS_SKIP_ADMIN_PROMPT"):
|
||||
# Interactive terminal — ask the user
|
||||
username, password = _prompt_admin_credentials()
|
||||
|
||||
@@ -0,0 +1,412 @@
|
||||
# Architecture Runtime Inventory
|
||||
|
||||
> **Purpose**: Phase 0 planning baseline for codebase readability improvements (#4071).
|
||||
> **Parent issue**: [#4082](https://github.com/pewdiepie-archdaemon/odysseus/issues/4082)
|
||||
> **Last updated**: dev@b58af42 | 2026-06-16
|
||||
> **Status**: Draft — to be reviewed before follow-up slices open.
|
||||
> **Snapshot basis**: Importer / file / import-line counts are refreshed to `dev@b58af42` (2026-06-16) and are recomputable via the commands in §3.4. **Line counts** in §2.1 / §2.2 are a snapshot from an earlier baseline and drift as `dev` moves — recompute any of them with `wc -l <file>`. This inventory tracks structure and risk, not live metrics.
|
||||
|
||||
This document maps the current runtime module structure, identifies high-risk boundaries, and recommends safe first refactor slices. It does **not** move files, change imports, or alter runtime behavior.
|
||||
|
||||
---
|
||||
|
||||
## 1. Current Structure Overview
|
||||
|
||||
### 1.1 Top-Level Layout
|
||||
|
||||
```
|
||||
odysseus/
|
||||
├── app.py # FastAPI app entrypoint (1,145 lines)
|
||||
├── conf/ # Configuration (config.py, settings.py, settings_scrub.py)
|
||||
├── src/ # 95 flat .py files + 2 subdirectories
|
||||
│ ├── agent_tools/ # Tool helpers: document, filesystem, subprocess, web
|
||||
│ └── search/ # Search subsystem
|
||||
├── routes/ # 54 flat .py files — HTTP route handlers
|
||||
├── core/ # 10 files — database models, auth, middleware, session
|
||||
├── mcp_servers/ # 5 files — MCP server implementations
|
||||
├── scripts/ # CLI tools and one-shot scripts
|
||||
├── static/ # Frontend HTML/CSS/JS
|
||||
├── tests/ # 583 test files (~54,800 lines)
|
||||
└── services/ # (exists as needed)
|
||||
```
|
||||
|
||||
### 1.2 Directory Flatness Metric
|
||||
|
||||
| Directory | Flat `.py` Files | Subdirectories | Concern |
|
||||
|-----------|-----------------|----------------|---------|
|
||||
| `src/` | **95** | 2 (`agent_tools/`, `search/`) | No domain grouping; 95 files in one directory |
|
||||
| `routes/` | **54** | 0 | All route handlers in one flat directory |
|
||||
| `core/` | 10 | 0 | Manageable, but `database.py` is oversized |
|
||||
|
||||
---
|
||||
|
||||
## 2. Largest Runtime Modules
|
||||
|
||||
### 2.1 Python Backend
|
||||
|
||||
| Rank | File | Lines | Classes | Functions | Risk |
|
||||
|------|------|-------|---------|-----------|------|
|
||||
| 1 | `src/tool_implementations.py` | **4,032** | 0 | ~48 | **HIGH** |
|
||||
| 2 | `routes/email_routes.py` | **3,245** | — | — | **MEDIUM** |
|
||||
| 3 | `routes/cookbook_routes.py` | **2,969** | — | — | **MEDIUM** |
|
||||
| 4 | `src/agent_loop.py` | **2,961** | 0 | ~24 | **HIGH** |
|
||||
| 5 | `src/task_scheduler.py` | **2,330** | — | 5 | MEDIUM |
|
||||
| 6 | `routes/model_routes.py` | **2,266** | — | — | MEDIUM |
|
||||
| 7 | `core/database.py` | **2,265** | 28 | ~59 helpers | **HIGH** |
|
||||
| 8 | `src/builtin_actions.py` | **2,262** | 2 | ~24 | MEDIUM |
|
||||
| 9 | `src/llm_core.py` | **2,164** | — | — | MEDIUM |
|
||||
| 10 | `mcp_servers/email_server.py` | 2,197 | — | — | LOW (separate process) |
|
||||
| 11 | `src/visual_report.py` | 1,918 | — | — | LOW |
|
||||
| 12 | `routes/gallery_routes.py` | 1,896 | — | — | LOW |
|
||||
| 13 | `src/ai_interaction.py` | 1,846 | — | — | MEDIUM |
|
||||
| 14 | `routes/document_routes.py` | 1,717 | — | — | LOW |
|
||||
| 15 | `routes/skills_routes.py` | 1,648 | — | — | LOW |
|
||||
|
||||
**Heuristic**: Files > 2,000 lines with 20+ public symbols and many importers are the highest-risk splits. Files 1,000–2,000 lines are medium-risk if tightly coupled.
|
||||
|
||||
### 2.2 Frontend
|
||||
|
||||
| File | Lines | Concern |
|
||||
|------|-------|---------|
|
||||
| `static/style.css` | **36,653** | Entire app CSS in one file (tracked separately in #2617) |
|
||||
| `static/js/document.js` | **9,776** | Single JS file for document functionality |
|
||||
| `static/js/slashCommands.js` | 6,498 | |
|
||||
| `static/js/settings.js` | 5,266 | |
|
||||
| `static/js/emailLibrary.js` | 5,217 | |
|
||||
| `static/js/notes.js` | 5,124 | |
|
||||
| `static/js/chat.js` | 4,985 | |
|
||||
| `static/app.js` | 4,090 | |
|
||||
|
||||
**Note**: Frontend modularization is tracked separately in #2617 (CSS) and is not the focus of this Phase 0 inventory. Frontend is listed here for completeness but follow-up slices should target Python backend boundaries first.
|
||||
|
||||
---
|
||||
|
||||
## 3. Import Dependency Graph
|
||||
|
||||
### 3.1 Who Depends on `core/database.py`
|
||||
|
||||
**102 files** import from `core.database` — this is the most depended-upon module:
|
||||
|
||||
- All route handlers (`routes/*.py`)
|
||||
- Most `src/*.py` files
|
||||
- `core/session_manager.py`, `core/auth.py`
|
||||
- Multiple test files
|
||||
|
||||
**Implication**: Any split of `core/database.py` is the highest-risk refactor. It should be tackled **last**, never first.
|
||||
|
||||
### 3.2 Who Depends on `src/tool_implementations.py`
|
||||
|
||||
**17 files** import from `src.tool_implementations`:
|
||||
- `src/agent_loop.py`, `src/builtin_actions.py`, `src/tool_index.py`
|
||||
- `src/task_scheduler.py`, `src/tool_policy.py`
|
||||
- Various tests
|
||||
|
||||
### 3.3 Who Depends on `src/agent_loop.py`
|
||||
|
||||
**22 files** import from `src.agent_loop`:
|
||||
|
||||
- `src/tool_policy.py`, `src/teacher_escalation.py`, `src/bg_monitor.py`
|
||||
- `src/task_scheduler.py`
|
||||
- Multiple test files
|
||||
|
||||
### 3.4 Cross-Layer Import Violations
|
||||
|
||||
**`src/` importing from `routes/`** (backwards dependency — domain logic depending on HTTP layer):
|
||||
|
||||
```
|
||||
src/tool_implementations.py ──→ routes/calendar_routes.py
|
||||
src/tool_implementations.py ──→ routes/cookbook_helpers.py
|
||||
src/tool_implementations.py ──→ routes/email_helpers.py
|
||||
src/tool_implementations.py ──→ routes/email_pollers.py
|
||||
src/tool_implementations.py ──→ routes/email_routes.py
|
||||
src/tool_implementations.py ──→ routes/model_routes.py
|
||||
src/tool_implementations.py ──→ routes/note_routes.py
|
||||
src/tool_implementations.py ──→ routes/prefs_routes.py
|
||||
```
|
||||
|
||||
> These are **runtime imports** (inside function bodies, not at module top), which mitigates circular import risk but indicates fuzzy layer boundaries. Function-level inline imports from the HTTP layer into business logic are a code smell.
|
||||
|
||||
**Import counts (top-level)**:
|
||||
| Direction | Count | Notes |
|
||||
|-----------|-------|-------|
|
||||
| `routes/` → `src/` | **374** | Expected: HTTP handlers call domain logic |
|
||||
| `routes/` → `core/` | **126** | Expected: handlers access DB models |
|
||||
| `src/` → `routes/` | **31** | **Unexpected**: domain logic reaching into HTTP layer (direct grep of import lines referencing `routes/`) |
|
||||
| `src/` → `core/` | **106** | Acceptable but could be reduced with a data-access layer |
|
||||
|
||||
> **How the metrics in this document are computed** — recompute against current `dev` before treating any count as authoritative (the tree drifts; these numbers are a snapshot, not a live value):
|
||||
> - `src/` flat `.py` files: `find src -maxdepth 1 -name '*.py' | wc -l`
|
||||
> - `tests/` test files: `find tests -name 'test_*.py' | wc -l`
|
||||
> - `core.database` importers: `grep -rlE '(from|import) +core\.database' --include='*.py' . | grep -v core/database.py | wc -l`
|
||||
> - `src.agent_loop` importers: `grep -rlE '(from|import) +src\.agent_loop' --include='*.py' . | grep -v src/agent_loop.py | wc -l`
|
||||
> - Cross-layer import lines: `grep -rhE '(from|import) +<pkg>' --include='*.py' <dir>/ | wc -l` (e.g. `(from|import) +routes` over `src/`)
|
||||
|
||||
---
|
||||
|
||||
## 4. Route Ownership Map
|
||||
|
||||
Routes can be grouped into logical feature domains. Current flat structure obscures these boundaries:
|
||||
|
||||
| Domain | Route Files | Total Lines | Review Complexity |
|
||||
|--------|-------------|-------------|-------------------|
|
||||
| **Email** | `email_routes.py`, `email_helpers.py`, `email_pollers.py` | 5,936 | HIGH — most complex domain |
|
||||
| **Chat / Agent** | `chat_routes.py`, `chat_helpers.py`, `shell_routes.py`, `codex_routes.py`, `skills_routes.py` | 6,365 | HIGH — core interaction surface |
|
||||
| **Cookbook** | `cookbook_routes.py`, `cookbook_helpers.py`, `cookbook_output.py` | 4,110 | MEDIUM |
|
||||
| **Model / LLM** | `model_routes.py`, `assistant_routes.py`, `copilot_routes.py` | 2,764 | MEDIUM |
|
||||
| **Calendar / Contacts** | `calendar_routes.py`, `contacts_routes.py` | 2,336 | MEDIUM |
|
||||
| **Documents** | `document_routes.py`, `document_helpers.py` | 1,954 | LOW |
|
||||
| **Auth** | `auth_routes.py`, `api_token_routes.py`, `device_flow.py` | 1,171 | LOW |
|
||||
| **Tasks** | `task_routes.py` (standalone) | 1,157 | LOW |
|
||||
| **Session** | `session_routes.py` (standalone) | 1,287 | LOW |
|
||||
| **Gallery** | `gallery_routes.py`, `gallery_helpers.py` | 1,896 | LOW |
|
||||
| **Memory** | `memory_routes.py` | — | LOW |
|
||||
| **Research** | `research_routes.py` | — | LOW |
|
||||
| **MCP** | `mcp_routes.py` | — | LOW |
|
||||
| **Notes** | `note_routes.py` | — | LOW |
|
||||
| **Other** | `prefs_routes.py`, `upload_routes.py`, `vault_routes.py`, `webhook_routes.py`, `workspace_routes.py`, `search_routes.py`, `history_routes.py`, `hwfit_routes.py`, `preset_routes.py`, `signature_routes.py`, `backup_routes.py`, `cleanup_routes.py`, `diagnostics_routes.py`, `embedding_routes.py`, `emoji_routes.py`, `font_routes.py`, `stt_routes.py`, `tts_routes.py`, `compare_routes.py`, `personal_routes.py`, `editor_draft_routes.py`, `admin_wipe_routes.py`, `chatgpt_subscription_routes.py` | 2,000+ | LOW individual, HIGH cumulative |
|
||||
|
||||
---
|
||||
|
||||
## 5. Tool Registry & Implementation Boundaries
|
||||
|
||||
### 5.1 Current Tool Architecture
|
||||
|
||||
| Component | File | Lines | Role |
|
||||
|-----------|------|-------|------|
|
||||
| Tool schemas | `src/tool_schemas.py` | 1,392 | JSON Schema tool definitions (Duck-TypedDict) |
|
||||
| Tool index | `src/tool_index.py` | 542 | RAG-based tool retrieval from ChromaDB |
|
||||
| Tool implementations | `src/tool_implementations.py` | 4,032 | 33 `do_*` functions — all tool execution logic |
|
||||
| Tool security | `src/tool_security.py` | — | Owner-scoped tool blocking |
|
||||
| Tool policy | `src/tool_policy.py` | — | Guide-only directive, plan-mode disabled tools |
|
||||
| Tool utils | `src/tool_utils.py` | — | Shared tool helpers |
|
||||
|
||||
### 5.2 Tool Implementation Categories
|
||||
|
||||
The 33 `do_*` functions in `tool_implementations.py` fall into natural domain groups — the basis for slice 1's split in §6.2:
|
||||
|
||||
| Category | `do_*` functions | Count |
|
||||
|----------|------------------|-------|
|
||||
| **System / config** | `do_manage_skills`, `do_manage_tasks`, `do_manage_endpoints`, `do_manage_mcp`, `do_manage_webhooks`, `do_manage_tokens`, `do_manage_settings`, `do_api_call`, `do_app_api` | 9 |
|
||||
| **Cookbook / model serving** | `do_download_model`, `do_serve_model`, `do_list_served_models`, `do_stop_served_model`, `do_tail_serve_output`, `do_list_downloads`, `do_cancel_download`, `do_search_hf_models`, `do_adopt_served_model`, `do_list_cookbook_servers`, `do_list_serve_presets`, `do_serve_preset`, `do_list_cached_models` | 13 |
|
||||
| **Notes** | `do_manage_notes` | 1 |
|
||||
| **Calendar** | `do_manage_calendar` | 1 |
|
||||
| **Search** | `do_search_chats` | 1 |
|
||||
| **Research** | `do_manage_research`, `do_trigger_research` | 2 |
|
||||
| **Contacts** | `do_resolve_contact`, `do_manage_contact` | 2 |
|
||||
| **Vault** | `do_vault_search`, `do_vault_get`, `do_vault_unlock` | 3 |
|
||||
| **Image** | `do_edit_image` | 1 |
|
||||
| | **Total** | **33** |
|
||||
|
||||
> Low-level tools (filesystem, subprocess, web fetch, document parsing) live in `src/agent_tools/`, **not** in `tool_implementations.py` — out of scope for this split.
|
||||
|
||||
---
|
||||
|
||||
## 6. Risk Assessment & Candidate Slice Ranking
|
||||
|
||||
> **Candidate proposals, not a committed plan.** The rankings, package shapes (e.g. `src/pkg/`, `src/domain/`, `src/infra/`, `src/api/`), split ordering, and route-grouping strategy below are **options for maintainer discussion**. Per #4082/#4071, slice ownership and order are settled by maintainers before any follow-up PR. §1–§3 above are the factual current-state inventory.
|
||||
|
||||
### 6.1 Risk Scale
|
||||
|
||||
| Level | Criteria |
|
||||
|-------|----------|
|
||||
| **LOW** | File has ≤3 importers AND ≤500 lines, OR is a pure refactor with clear boundaries |
|
||||
| **MEDIUM** | File has 4–15 importers OR 500–1,500 lines |
|
||||
| **HIGH** | File has 16+ importers OR >2,000 lines, OR has cross-layer import violations |
|
||||
|
||||
### 6.2 Ranked Split Candidates
|
||||
|
||||
| Priority | Target | Risk | Rationale |
|
||||
|----------|--------|------|-----------|
|
||||
| **1** | `src/tool_implementations.py` → `src/tools/*.py` | **MEDIUM** | 4,032 lines → ~10 files by tool category. Already has natural boundaries. 17 importers, tracked in #3629. Use `__init__.py` shim to keep existing imports working. |
|
||||
| **2** | `routes/` → domain subdirectories (one domain per PR) | **MEDIUM** | 54 flat files. Done **one domain at a time** (e.g. a standalone PR for the email domain, then chat, …), not a broad reorganization — route modules carry helper imports, registration assumptions, and test import paths. |
|
||||
| **3** | `src/agent_loop.py` → `src/agent/loop.py` + submodules | **MEDIUM-HIGH** | 2,961 lines, 24 functions. Can extract prompt building, classification, verification, and runaway detection. Tracked in #3266. |
|
||||
| **4** | `src/` → `src/pkg/`, `src/domain/`, `src/infra/`, `src/api/` | **MEDIUM** | Structural reorganization. Split flat `src/` into layered packages. Must come after routes and tools are stable. |
|
||||
| **5** | `routes/email_*.py` consolidation | **LOW** | Already grouped by filename prefix. Low-risk cleanup within the email domain. |
|
||||
| **6** | `core/database.py` → `src/infra/database/models/*.py` | **HIGH** | 28 classes, 102 importers. Highest-risk split. Must be **last** in any sequence. Requires careful import shim strategy. |
|
||||
| **7** | Frontend CSS modularization | **MEDIUM** | 36,653 lines. Tracked in #2617. Separate timeline from backend work. |
|
||||
| **8** | Frontend JS modularization | **MEDIUM** | 9,776 lines in `document.js`. Introduce ES modules at minimum. |
|
||||
|
||||
### 6.3 Candidate First 3 Behavior-Preserving Slices
|
||||
|
||||
**Slice 1: Split `tool_implementations.py`** (Lowest-risk high-impact)
|
||||
|
||||
- Create `src/tools/` package with one file per tool category
|
||||
- Add `src/tools/__init__.py` re-exporting all symbols with current names
|
||||
- Update 17 importers to use new paths (can be deferred via shim)
|
||||
- Validation: `python -m pytest tests/ -x -q` + manual smoke test of tool execution
|
||||
- Reference: #3629
|
||||
|
||||
**Slice 2: Group `routes/` by domain** (one domain per PR, not a broad sweep)
|
||||
|
||||
Route modules carry helper imports, router registration assumptions, and test import paths, so this must be done **one domain at a time** rather than as a single reorganization PR. Example sequence (each its own PR):
|
||||
|
||||
- PR 2a: move the **email** domain (`email_routes.py`, `email_helpers.py`, `email_pollers.py`) → `routes/email/` + shim
|
||||
- PR 2b: move the **chat/agent** domain → `routes/chat/` + shim
|
||||
- PR 2c: move the **cookbook** domain → `routes/cookbook/` + shim
|
||||
- …and so on per domain from §4
|
||||
|
||||
Each PR: add `__init__.py` re-exporting old names, update `app.py` router imports, validation `python app.py` starts clean. **No behavior change** — pure file reorganization.
|
||||
|
||||
**Slice 3: Extract `agent_loop.py` submodules** (Improve reviewability)
|
||||
|
||||
- Move prompt assembly → `src/agent/prompt.py`
|
||||
- Move request classification → `src/agent/classifier.py`
|
||||
- Move sub-agent verification → `src/agent/verifier.py`
|
||||
- Move runaway detection → `src/agent/runaway.py`
|
||||
- Move context management → `src/agent/context.py`
|
||||
- Keep `src/agent/loop.py` as the main orchestration module
|
||||
- Validation: `python -m pytest tests/test_agent_loop.py tests/test_loop_breaker_runaway.py -v`
|
||||
|
||||
---
|
||||
|
||||
## 7. Safety Guardrails for Follow-Up Work
|
||||
|
||||
Per maintainer guidance in #4082 and #4071:
|
||||
|
||||
- [ ] **One domain/slice per PR** — never mix multiple reorganizations
|
||||
- [ ] **No behavior changes** mixed with file moves — pure reorganization only
|
||||
- [ ] **Keep compatibility shims** — `__init__.py` re-exports for all existing import paths
|
||||
- [ ] **Add or identify focused tests** before risky splits
|
||||
- [ ] **Do not start with `core/database.py`** or broad route movement unless this inventory shows a safe boundary
|
||||
- [ ] **Prefer small, reviewable slices** over large restructures
|
||||
- [ ] **No packaging/runtime/tooling migration** mixed into file moves
|
||||
- [ ] **No frontend framework migration** inside this stabilization lane
|
||||
- [ ] **Validate with `python -m compileall`** — every PR must pass CI checks
|
||||
- [ ] **Validate with `pytest`** — run the full test suite before opening each PR
|
||||
|
||||
---
|
||||
|
||||
## 8. Validation Commands
|
||||
|
||||
Each follow-up PR should be verifiable with these commands before submission:
|
||||
|
||||
```bash
|
||||
# Syntax check — must pass with zero errors
|
||||
python -m compileall src/ routes/ core/ conf/
|
||||
|
||||
# Full test suite — must match baseline pass rate
|
||||
python -m pytest tests/ -x -q
|
||||
|
||||
# Import shim verification — existing import paths must still work
|
||||
python -c "from src.tool_implementations import do_search_chats; print('OK')"
|
||||
|
||||
# App startup smoke test (if backend touched)
|
||||
timeout 5 python app.py 2>&1 | head -5 || true
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 9. Open Questions
|
||||
|
||||
1. Is `#2538` (specs ground truth) the canonical behavior map baseline, and should this inventory be kept in sync with those specs once merged?
|
||||
2. Should route grouping follow the domain map proposed here, or is there a different taxonomy preferred by maintainers?
|
||||
3. For the `tool_implementations.py` split (#3629), is the tool categorization in §5.2 acceptable, or should it follow a different grouping?
|
||||
4. Should compatibility shims (`__init__.py`) be temporary (removed in a follow-up wave) or permanent?
|
||||
5. Should an ADR (Architecture Decision Record) document be started to track decisions made during this process?
|
||||
|
||||
---
|
||||
|
||||
## 10. Future Direction (NOT current state)
|
||||
|
||||
The following are **future refactor targets** (candidate directions **pending maintainer agreement**, not committed), recorded here so this inventory does not imply they exist today. None of them are present in the current `dev` tree:
|
||||
|
||||
- `main.py` — proposed rename of the `app.py` entrypoint. Today the app boots via `app.py`.
|
||||
- `src/agent/` — proposed package to hold `agent_loop.py` submodules (prompt/classifier/verifier/runaway/context). Today `agent_loop.py` is a single flat file in `src/`.
|
||||
- `src/infra/`, `src/domain/`, `src/pkg/`, `src/api/` — proposed layered reorganization of the flat `src/` directory (slice 4 in §6).
|
||||
|
||||
These become real only when the corresponding slices land.
|
||||
|
||||
---
|
||||
|
||||
## Appendix A: File Listing
|
||||
|
||||
### `src/` (95 files — 61 shown; run `ls src/*.py` for the full list)
|
||||
|
||||
```
|
||||
agent_loop.py tool_implementations.py tool_schemas.py
|
||||
tool_index.py tool_security.py tool_policy.py
|
||||
tool_utils.py builtin_actions.py task_scheduler.py
|
||||
llm_core.py model_context.py model_discovery.py
|
||||
session_search.py context_budget.py context_compactor.py
|
||||
ai_interaction.py action_intents.py agent_runs.py
|
||||
app_helpers.py app_initializer.py config.py
|
||||
database.py memory.py memory_provider.py
|
||||
secret_storage.py prompt_security.py url_security.py
|
||||
url_safety.py rate_limiter.py cleanup_service.py
|
||||
readiness.py service_health.py exceptions.py
|
||||
request_models.py assistant_log.py bg_monitor.py
|
||||
builtin_mcp.py chat_helpers.py chroma_client.py
|
||||
document_processor.py embedding_lanes.py deep_research.py
|
||||
research_handler.py research_utils.py personal_docs.py
|
||||
rag_manager.py rag_singleton.py topic_analyzer.py
|
||||
visual_report.py youtube_handler.py pdf_forms.py
|
||||
pdf_form_doc.py pdf_runtime.py caldav_writeback.py
|
||||
email_thread_parser.py text_helpers.py user_time.py
|
||||
teacher_escalation.py cookbook_serve_lifecycle.py
|
||||
chatgpt_subscription.py mcp_manager.py
|
||||
```
|
||||
|
||||
### `routes/` (54 files)
|
||||
|
||||
```
|
||||
__init__.py _validators.py
|
||||
auth_routes.py api_token_routes.py device_flow.py
|
||||
chat_routes.py chat_helpers.py shell_routes.py
|
||||
codex_routes.py skills_routes.py
|
||||
email_routes.py email_helpers.py email_pollers.py
|
||||
cookbook_routes.py cookbook_helpers.py cookbook_output.py
|
||||
model_routes.py assistant_routes.py copilot_routes.py
|
||||
calendar_routes.py contacts_routes.py
|
||||
document_routes.py document_helpers.py
|
||||
gallery_routes.py gallery_helpers.py
|
||||
task_routes.py session_routes.py
|
||||
note_routes.py memory_routes.py research_routes.py
|
||||
mcp_routes.py search_routes.py history_routes.py
|
||||
webhook_routes.py workspace_routes.py upload_routes.py
|
||||
vault_routes.py prefs_routes.py preset_routes.py
|
||||
signature_routes.py personal_routes.py hwfit_routes.py
|
||||
backup_routes.py cleanup_routes.py diagnostics_routes.py
|
||||
embedding_routes.py emoji_routes.py font_routes.py
|
||||
stt_routes.py tts_routes.py compare_routes.py
|
||||
editor_draft_routes.py chatgpt_subscription_routes.py admin_wipe_routes.py
|
||||
```
|
||||
|
||||
### `core/` (10 files)
|
||||
|
||||
```
|
||||
__init__.py constants.py database.py models.py
|
||||
auth.py middleware.py session_manager.py exceptions.py
|
||||
atomic_io.py platform_compat.py
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Appendix B: Key Import Relationships
|
||||
|
||||
```
|
||||
core/database.py ←── 102 importers (routes/*, src/*, core/*, tests/*)
|
||||
↑
|
||||
├── routes/auth_routes.py
|
||||
├── routes/email_routes.py
|
||||
├── src/builtin_actions.py
|
||||
├── src/task_scheduler.py
|
||||
├── src/tool_implementations.py (inline)
|
||||
└── ...97 more
|
||||
|
||||
src/tool_implementations.py ←── 17 importers
|
||||
↑
|
||||
├── src/agent_loop.py
|
||||
├── src/builtin_actions.py
|
||||
├── src/tool_index.py
|
||||
├── src/task_scheduler.py
|
||||
├── src/tool_policy.py
|
||||
└── ...12 more (mostly tests)
|
||||
|
||||
src/agent_loop.py ←── 22 importers
|
||||
↑
|
||||
├── src/tool_policy.py
|
||||
├── src/teacher_escalation.py
|
||||
├── src/bg_monitor.py
|
||||
├── src/task_scheduler.py
|
||||
└── 18 more (incl. tests)
|
||||
```
|
||||
@@ -267,6 +267,10 @@ _DOMAIN_RULES = {
|
||||
- Use `resolve_contact` to look up a contact's email or phone number by name. Searches the CardDAV address book and sent email history.
|
||||
- Use `manage_contact` to list, add, update, or delete contacts in the address book.
|
||||
- Do NOT use `manage_memory` for contact lookups — contact details live in the address book, not memory.""",
|
||||
"integrations": """\
|
||||
## Integration/API rules
|
||||
- To query or control a configured service integration (Home Assistant, Miniflux, Gitea, Linkding, Jellyfin, or any other registered service), use `api_call` with the integration name, HTTP method, path, and optional JSON body.
|
||||
- Do not use shell, curl, or `app_api` to reach a user's connected integration when `api_call` is available.""",
|
||||
}
|
||||
|
||||
_DOMAIN_TOOL_MAP = {
|
||||
@@ -277,9 +281,10 @@ _DOMAIN_TOOL_MAP = {
|
||||
"notes_calendar_tasks": {"manage_notes", "manage_calendar", "manage_tasks"},
|
||||
"ui": {"ui_control"},
|
||||
"sessions": {"create_session", "list_sessions", "manage_session", "send_to_session", "search_chats"},
|
||||
"files": {"bash", "python", "read_file", "write_file", "edit_file", "grep", "glob", "ls", "get_workspace"},
|
||||
"files": {"bash", "python", "read_file", "write_file", "edit_file", "grep", "glob", "ls", "get_workspace", "manage_bg_jobs"},
|
||||
"settings": {"manage_settings", "manage_endpoints", "manage_mcp", "manage_webhooks", "manage_tokens", "app_api"},
|
||||
"contacts": {"resolve_contact", "manage_contact"},
|
||||
"integrations": {"api_call"},
|
||||
}
|
||||
|
||||
def _domain_rules_for_tools(tool_names: set) -> list[str]:
|
||||
@@ -408,7 +413,7 @@ Generate an image. Line 1 = description, line 2 = model name, line 3 = WxH (e.g.
|
||||
"ask_teacher": "- ```ask_teacher``` — Escalate a hard question to a more capable model. Line 1 = model name or 'auto', rest = the question. Use when stuck or need expert knowledge.",
|
||||
"list_models": "- ```list_models``` — Show all available AI models across all endpoints. Use when user asks what models are available.",
|
||||
"manage_session": "- ```manage_session``` — Rename, archive, delete, fork, switch, or `list` chats (the UI calls them 'chats'; 'session' is internal). Line 1 = action (list/switch/rename/archive/unarchive/delete/important/unimportant/truncate/fork), Line 2 = exact chat id from `list_sessions` (or `current` where supported). For delete/archive/truncate, always list first and reuse the exact id; never invent placeholder ids. `switch`/`open` returns a clickable anchor link the user can tap to open the chat — use for \"open my X chat\".",
|
||||
"manage_memory": "- ```manage_memory``` — Manage the user's persistent memory (facts, identity, preferences, context that persists across chats). Line 1 = action (list/add/edit/delete/search), rest = content. Use when user says 'remember this', states identity facts like 'my name is <name>' / 'call me <name>' / 'I live in <place>', or asks about stored memories.",
|
||||
"manage_memory": "- ```manage_memory``` — Manage the user's persistent memory (facts about the USER themselves, their preferences, context that persists across chats). Line 1 = action (list/add/edit/delete/search), rest = content. Use when user says 'remember this' about themselves, states identity facts like 'my name is <name>' / 'call me <name>' / 'I live in <place>', or asks about stored memories. DO NOT use for info about another person (their address, phone, email, birthday) — that goes in `manage_contact`. If the user pastes an address/phone with a name and says 'save this for <person>', use `manage_contact add` with the address arg, NOT manage_memory.",
|
||||
"manage_skills": "- ```manage_skills``` — Skill registry (SKILL.md format). Args (JSON): {\"action\": \"list|view|view_ref|search|add|edit|patch|publish|delete\", ...}. `list` returns the index of available skills (published + teacher-escalation drafts); `view name=foo` fetches the full SKILL.md; `view_ref name=foo path=...` loads a reference file under the skill directory. For `add`, provide an explicit kebab-case `name` and only report the exact returned name, because storage may normalize or dedupe it. Use this BEFORE doing domain work — there may already be a procedure (published or draft) that prescribes the correct steps. Drafts written by the teacher loop are authoritative guidance even though they're not yet published.",
|
||||
"manage_tasks": "- ```manage_tasks``` — Create and manage scheduled background tasks (recurring AI jobs). Args (JSON): {\"action\": \"list|create|edit|delete|pause|resume|run\", ...}",
|
||||
"manage_endpoints": "- ```manage_endpoints``` — Add, remove, or configure AI model API endpoints. Args (JSON): {\"action\": \"list|add|delete|enable|disable\", ...}. Use when user wants to add a new AI provider.",
|
||||
@@ -428,7 +433,9 @@ Notes, checklists, AND user reminders. Use this for "create/add/write a note", t
|
||||
```send_email
|
||||
{"to": "recipient@example.com", "subject": "Re: Your question", "body": "Hi, ...", "account": "gmail"}
|
||||
```
|
||||
Send a new email via SMTP. Use `resolve_contact` first if you only have a name. If multiple email accounts exist, call `list_email_accounts` first and pass the chosen `account`.""",
|
||||
Send a new email via SMTP. Use `resolve_contact` first if you only have a name. If multiple email accounts exist, call `list_email_accounts` first and pass the chosen `account`.
|
||||
|
||||
CRITICAL — signatures: DO NOT invent a sign-off name. End the body with just `Thanks,` or similar — never type a person's name unless the user explicitly told you what to sign as. When `agent_email_confirm` is on (default), the tool returns `{pending: true, pending_id: ...}` and stages the email for the user to approve in the chat UI instead of SMTPing immediately.""",
|
||||
"list_emails": """\
|
||||
```list_emails
|
||||
{"folder": "INBOX", "max_results": 20, "unread_only": false, "account": "gmail"}
|
||||
@@ -439,7 +446,9 @@ List recent emails from a folder, newest first, including read messages by defau
|
||||
```reply_to_email
|
||||
{"uid": "1234", "body": "Sounds good — talk Friday.", "account": "gmail"}
|
||||
```
|
||||
SEND a reply email immediately by UID. Do not use this for "open a reply" or "start a reply" — those should use `ui_control` with `open_email_reply <uid> <folder> reply` to open the email draft document. For follow-up requests like "reply ..." after reading/listing email where the user clearly wants to send now, use the exact UID and account from the latest `read_email`/`list_emails` result. Never invent UID `1`. Threads automatically (In-Reply-To/References handled).""",
|
||||
SEND a reply email immediately by UID. Do not use this for "open a reply" or "start a reply" — those should use `ui_control` with `open_email_reply <uid> <folder> reply` to open the email draft document. For follow-up requests like "reply ..." after reading/listing email where the user clearly wants to send now, use the exact UID and account from the latest `read_email`/`list_emails` result. Never invent UID `1`. Threads automatically (In-Reply-To/References handled).
|
||||
|
||||
CRITICAL — signatures: DO NOT invent a sign-off name. End the body with just `Thanks,` or similar — never type a person's name unless the user explicitly told you what to sign as. When `agent_email_confirm` is on (default), the tool returns `{pending: true, pending_id: ...}` and stages the email for the user to approve in the chat UI instead of SMTPing immediately.""",
|
||||
"bulk_email": """\
|
||||
```bulk_email
|
||||
{"action": "delete", "uids": ["10997", "10998"], "folder": "INBOX", "account": "Gmail"}
|
||||
@@ -449,7 +458,7 @@ Bulk delete/archive/mark emails. Use this for "delete all those" after listing e
|
||||
"archive_email": "- ```archive_email``` — Archive one email by UID. Args (JSON): {\"uid\":\"...\", \"folder\":\"INBOX\", \"account\":\"Gmail\"}. For multiple messages use bulk_email.",
|
||||
"mark_email_read": "- ```mark_email_read``` — Mark one email read/unread. Args (JSON): {\"uid\":\"...\", \"read\":true, \"folder\":\"INBOX\", \"account\":\"Gmail\"}. For multiple messages use bulk_email.",
|
||||
"resolve_contact": "- ```resolve_contact``` — Look up a contact's email by name. Searches CardDAV address book + sent email history. Args (JSON): {\"name\": \"...\"}. Use BEFORE send_email when the user gives only a name.",
|
||||
"manage_contact": "- ```manage_contact``` — Create/update/delete/list CardDAV contacts. Args (JSON): {\"action\": \"list|add|update|delete\", \"name\": \"...\", \"email\": \"...\", \"uid\": \"...\"}. Use only for explicit address-book/contact requests with contact details. Do NOT use for user identity facts like 'my name is <name>'; save those with manage_memory. For update/delete, call action=list first to get the uid.",
|
||||
"manage_contact": "- ```manage_contact``` — Create/update/delete/list CardDAV contacts. Args (JSON): {\"action\": \"list|add|update|delete\", \"name\": \"...\", \"email\": \"...\", \"phones\": [...], \"address\": \"...\", \"uid\": \"...\"}. Use for info about another person: email, phone, postal address. For 'save this for <person>' / address paste / phone next to a name, use this — NOT manage_memory. Do NOT use for user identity facts ('my name is X'); those are manage_memory. For update/delete, call action=list first for the uid.",
|
||||
"manage_calendar": """\
|
||||
```manage_calendar
|
||||
{"action": "create_event", "summary": "<event title>", "dtstart": "<natural language or ISO datetime>"}
|
||||
@@ -520,7 +529,7 @@ def get_builtin_overrides() -> dict:
|
||||
ov = get_setting("builtin_tool_overrides", {})
|
||||
return ov if isinstance(ov, dict) else {}
|
||||
except Exception as e:
|
||||
logger.warning('Failed to load builtin tool overrides: %s', e)
|
||||
logger.warning("Failed to load builtin tool overrides, using defaults", exc_info=e)
|
||||
return {}
|
||||
|
||||
|
||||
@@ -807,10 +816,25 @@ def _classify_agent_request(messages: List[Dict], last_user: str) -> Dict[str, o
|
||||
domains.add("sessions")
|
||||
if has(r"\b(file|folder|directory|repo|git|grep|find in files|read file|edit file|shell|terminal|bash|python)\b"):
|
||||
domains.add("files")
|
||||
# Managing detached bash jobs: "kill the background job", "stop the job",
|
||||
# "kill that job", "check the job output", "is the bg job done".
|
||||
if (has(r"\b(background|bg)\s+(jobs?|task)\b")
|
||||
or has(r"\b(kill|stop|cancel|terminate|check|tail|show|list)\b.{0,16}\bjobs?\b")
|
||||
or has(r"\bjobs?\b.{0,16}\b(output|status|done|finished|running)\b")):
|
||||
domains.add("files")
|
||||
if has(r"\b(endpoint|api token|mcp|webhook|preference|configure|config|setting)\b"):
|
||||
domains.add("settings")
|
||||
if has(r"\b(contact|contacts|phone|phone number|address book|vcard)\b"):
|
||||
domains.add("contacts")
|
||||
# API-integration intent — calling a configured service via the api_call
|
||||
# tool. Without this the #3794 repro ("Use the api_call tool to call Home
|
||||
# Assistant GET /api/states") matched no domain, classified as low-signal,
|
||||
# and the tool never reached the schema filter. Detect it explicitly so the
|
||||
# "integrations" domain seeds api_call deterministically (see
|
||||
# _DOMAIN_TOOL_MAP), independent of embedding retrieval.
|
||||
if has(r"\bapi[ _]call\b", r"\bintegrations?\b",
|
||||
r"\b(?:home ?assistant|miniflux|gitea|linkding|jellyfin)\b"):
|
||||
domains.add("integrations")
|
||||
|
||||
low_signal = not continuation and not domains
|
||||
return {
|
||||
@@ -839,8 +863,11 @@ def _recent_context_for_retrieval(messages: List[Dict], max_user: int = 3, max_c
|
||||
if isinstance(content, list):
|
||||
content = " ".join(b.get("text", "") for b in content if isinstance(b, dict))
|
||||
content = (content or "").strip()
|
||||
# Skip injected tool-result envelopes — role=user but not human intent.
|
||||
if not content or content.startswith("[Tool execution results]"):
|
||||
# Skip injected envelopes — role=user but not human intent. Tool results
|
||||
# are now wrapped via untrusted_context_message (metadata.trusted=False);
|
||||
# keep the legacy "[Tool execution results]" prefix for older histories.
|
||||
meta = msg.get("metadata") or {}
|
||||
if not content or meta.get("trusted") is False or content.startswith("[Tool execution results]"):
|
||||
continue
|
||||
collected.append(content)
|
||||
if len(collected) >= max_user:
|
||||
@@ -859,6 +886,7 @@ def _build_system_prompt(
|
||||
compact: bool = False,
|
||||
owner: Optional[str] = None,
|
||||
suppress_local_context: bool = False,
|
||||
active_email: Optional[Dict[str, str]] = None,
|
||||
) -> List[Dict]:
|
||||
"""Build agent system prompt, inject MCP/document context, merge consecutive system msgs."""
|
||||
global _cached_base_prompt, _cached_base_prompt_key
|
||||
@@ -924,8 +952,8 @@ def _build_system_prompt(
|
||||
try:
|
||||
from src.user_time import current_datetime_context_message
|
||||
_datetime_message = current_datetime_context_message()
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
logger.warning("Failed to build datetime context message", exc_info=e)
|
||||
|
||||
# Document context is kept as a SEPARATE message (not merged into the tool
|
||||
# prompt) so the context trimmer doesn't destroy it when truncating the
|
||||
@@ -968,8 +996,8 @@ def _build_system_prompt(
|
||||
try:
|
||||
from src.pdf_form_doc import find_source_upload_id
|
||||
_is_form_backed = bool(find_source_upload_id(active_document.current_content or ""))
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
logger.warning("Failed to detect if document is form-backed, assuming plain", exc_info=e)
|
||||
|
||||
if _is_form_backed:
|
||||
doc_ctx = (
|
||||
@@ -1051,6 +1079,66 @@ def _build_system_prompt(
|
||||
else:
|
||||
set_active_document(None)
|
||||
|
||||
# Active email reader — frontend told us the user has an email open.
|
||||
# Inject a context block so "reply", "summarize this", "what does it say"
|
||||
# resolve to the real UID instead of the agent inventing a fresh .md
|
||||
# draft with fake headers. This is the email equivalent of _doc_message.
|
||||
_email_message = None
|
||||
if active_email and active_email.get("uid"):
|
||||
_em_uid = active_email.get("uid", "")
|
||||
_em_folder = active_email.get("folder", "INBOX")
|
||||
_em_account = active_email.get("account", "")
|
||||
_em_subject = active_email.get("subject", "") or "(no subject)"
|
||||
_em_from = active_email.get("from", "") or "(unknown sender)"
|
||||
_em_preview = (active_email.get("body_preview", "") or "").strip()
|
||||
_preview_block = f"\nBody preview:\n```\n{_em_preview[:1800]}\n```" if _em_preview else ""
|
||||
_acct_arg = f" {_em_account}" if _em_account else ""
|
||||
email_ctx = (
|
||||
f"ACTIVE EMAIL OPEN (the user has this email open in a reader window right now)\n"
|
||||
f"UID: {_em_uid}\n"
|
||||
f"Folder: {_em_folder}\n"
|
||||
f"Account: {_em_account or '(default)'}\n"
|
||||
f"From: {_em_from}\n"
|
||||
f"Subject: {_em_subject}{_preview_block}\n\n"
|
||||
f"CRITICAL DEFAULT — every request about email this turn refers to "
|
||||
f"THIS email unless the user names a DIFFERENT specific recipient "
|
||||
f"(a name, an email address, or another thread). Examples that "
|
||||
f"ALL mean reply-to-the-open-email:\n"
|
||||
f" • 'reply' / 'reply to this' / 'respond'\n"
|
||||
f" • 'write email saying X' / 'send email saying X' / 'draft something'\n"
|
||||
f" • 'tell them X' / 'say hi' / 'thanks' / 'ack' / 'lmk'\n"
|
||||
f" • 'summarize it' / 'what does it say' / 'tldr'\n"
|
||||
f" • 'forward this' / 'forward to <addr>'\n"
|
||||
f"DO NOT ASK THE USER 'who do you want to send this to?' — the "
|
||||
f"answer is ALWAYS the sender of the open email (above) unless they "
|
||||
f"named someone else. Asking that is the wrong move every time.\n\n"
|
||||
f"RULES for the open email:\n"
|
||||
f"1. DRAFT a reply (default for any 'write/send/reply/tell them' "
|
||||
f"request without a different recipient): call `ui_control` with "
|
||||
f"`action=\"open_email_reply\"` and `extra=\"{_em_uid} {_em_folder} "
|
||||
f"reply\"`. This opens the proper reply doc with To/Subject/"
|
||||
f"In-Reply-To pre-filled by the backend. The user will see and edit "
|
||||
f"it before sending. DO NOT `create_document` a markdown file with "
|
||||
f"hand-written `To:` / `Subject:` / `In-Reply-To:` headers — that "
|
||||
f"is wrong every time.\n"
|
||||
f"2. SEND a reply immediately (skip the draft): call "
|
||||
f"`reply_to_email` with the UID above. Only do this when the user "
|
||||
f"explicitly says 'send' / 'send the reply' / 'reply and send'.\n"
|
||||
f"3. READ the full body (the preview above may be truncated): "
|
||||
f"call `read_email` with the UID/folder/account above.\n"
|
||||
f"4. SUMMARIZE / answer questions about it: read it first, then "
|
||||
f"answer in chat. Don't create a document for a summary unless "
|
||||
f"the user explicitly asks for one.\n"
|
||||
f"5. Never ask the user to paste the email or 'share it with you' "
|
||||
f"— you already have its identity above and can read the full body.\n"
|
||||
f"6. The ONLY time you ask 'who to send to?' is when the user "
|
||||
f"explicitly says 'send a NEW email to someone else' or names a "
|
||||
f"recipient you can't identify. A bare 'send email saying X' = the "
|
||||
f"open email's sender.\n"
|
||||
)
|
||||
_email_message = untrusted_context_message("active email reader", email_ctx)
|
||||
_email_message["_protected"] = True
|
||||
|
||||
# Inject writing style for any email writing path. This is deliberately
|
||||
# broader than read/list: models may compose via send_email, reply_to_email,
|
||||
# or ui_control open_email_reply after the first tool round.
|
||||
@@ -1258,6 +1346,9 @@ def _build_system_prompt(
|
||||
if _doc_message:
|
||||
merged.insert(last_user_idx, _doc_message)
|
||||
last_user_idx += 1 # the document message is now at last_user_idx
|
||||
if _email_message:
|
||||
merged.insert(last_user_idx, _email_message)
|
||||
last_user_idx += 1
|
||||
if _skills_message:
|
||||
merged.insert(last_user_idx, _skills_message)
|
||||
last_user_idx += 1
|
||||
@@ -1292,12 +1383,18 @@ def _build_base_prompt(
|
||||
from src.tool_index import ALWAYS_AVAILABLE
|
||||
|
||||
disabled = set(disabled_tools or [])
|
||||
if not get_setting("image_gen_enabled", True):
|
||||
if not get_setting("image_gen_enabled", False):
|
||||
disabled.add("generate_image")
|
||||
|
||||
if relevant_tools is not None:
|
||||
# RAG mode: include always-available + retrieved + admin (if needed)
|
||||
tool_names = set(ALWAYS_AVAILABLE) | set(relevant_tools)
|
||||
# RAG mode: trust the relevant_tools set as already-composed.
|
||||
# get_tools_for_query starts from ALWAYS_AVAILABLE and may
|
||||
# *discard* tools that conflict with the query's intent (e.g.
|
||||
# drop manage_memory for clear contact-save patterns). Unioning
|
||||
# ALWAYS_AVAILABLE back in here used to silently undo those
|
||||
# drops. Only force-include the irreducible loop primitives
|
||||
# (ask_user, update_plan) as belt-and-suspenders.
|
||||
tool_names = set(relevant_tools) | {"ask_user", "update_plan"}
|
||||
if needs_admin:
|
||||
tool_names |= _ADMIN_TOOLS
|
||||
agent_prompt = _assemble_prompt(tool_names, disabled, compact=compact)
|
||||
@@ -1488,8 +1585,14 @@ def _append_tool_results(
|
||||
if round_reasoning:
|
||||
msg["reasoning_content"] = round_reasoning
|
||||
messages.append(msg)
|
||||
# Tool output (shell/python stdout, file reads, fetched pages, email
|
||||
# bodies, MCP results) is sourced from outside the server. Wrap it as
|
||||
# untrusted data so prompt-injection inside a tool result is treated as
|
||||
# data, not instructions — same hardening as skills (#788) and the
|
||||
# web/RAG context. THREAT_MODEL.md lists tool output as a surface that
|
||||
# must go through untrusted_context_message.
|
||||
messages.append(
|
||||
{"role": "user", "content": f"[Tool execution results]\n\n{tool_output_text}"}
|
||||
untrusted_context_message("tool execution results", tool_output_text)
|
||||
)
|
||||
|
||||
|
||||
@@ -1738,6 +1841,7 @@ async def stream_agent_loop(
|
||||
max_tool_calls: int = 0,
|
||||
context_length: int = 0,
|
||||
active_document=None,
|
||||
active_email: Optional[Dict[str, str]] = None,
|
||||
session_id: Optional[str] = None,
|
||||
disabled_tools: Optional[Set[str]] = None,
|
||||
owner: Optional[str] = None,
|
||||
@@ -2025,6 +2129,7 @@ async def stream_agent_loop(
|
||||
compact=_is_api_model,
|
||||
owner=owner,
|
||||
suppress_local_context=guide_only,
|
||||
active_email=active_email,
|
||||
)
|
||||
if plan_mode and not guide_only:
|
||||
# Steer the model to investigate-then-propose. Hard tool gating handles
|
||||
@@ -2910,7 +3015,19 @@ async def stream_agent_loop(
|
||||
tool_output_data = {"type": "tool_output", "tool": block.tool_type, "command": cmd_display, "output": output_text, "exit_code": result.get("exit_code")}
|
||||
if "ui_event" in result:
|
||||
tool_output_data["ui_event"] = result["ui_event"]
|
||||
for k in ("toggle_name", "state", "mode", "model", "endpoint_url", "theme_name", "colors"):
|
||||
for k in (
|
||||
"toggle_name", "state", "mode", "model", "endpoint_url",
|
||||
"theme_name", "colors",
|
||||
# ui_control open_email_reply payload — without these the
|
||||
# frontend openReplyDraft bails on undefined uid and the
|
||||
# reply window silently never opens.
|
||||
"uid", "folder", "account_id",
|
||||
# Optional pre-filled body for open_email_reply so the
|
||||
# agent can compose-and-open in one tool call.
|
||||
"body",
|
||||
# ui_control open_panel payload
|
||||
"panel",
|
||||
):
|
||||
if k in result:
|
||||
tool_output_data[k] = result[k]
|
||||
# Forward image data from generate_image tool
|
||||
|
||||
@@ -22,6 +22,9 @@ from .subprocess_tools import BashTool, PythonTool
|
||||
from .web_tools import WebSearchTool, WebFetchTool
|
||||
from .filesystem_tools import ReadFileTool, WriteFileTool, EditFileTool, LsTool, GlobTool, GrepTool, GetWorkspaceTool
|
||||
from .document_tools import CreateDocumentTool, UpdateDocumentTool, EditDocumentTool, SuggestDocumentTool, ManageDocumentTool
|
||||
from .model_interaction_tools import ChatWithModelTool, AskTeacherTool, ListModelsTool
|
||||
from .bg_job_tools import ManageBgJobsTool
|
||||
from .session_tools import CreateSessionTool, ListSessionsTool, SendToSessionTool, ManageSessionTool
|
||||
|
||||
TOOL_HANDLERS = {
|
||||
"bash": BashTool().execute,
|
||||
@@ -40,6 +43,14 @@ TOOL_HANDLERS = {
|
||||
"suggest_document": SuggestDocumentTool().execute,
|
||||
"manage_documents": ManageDocumentTool().execute,
|
||||
"get_workspace": GetWorkspaceTool().execute,
|
||||
"chat_with_model": ChatWithModelTool().execute,
|
||||
"ask_teacher": AskTeacherTool().execute,
|
||||
"list_models": ListModelsTool().execute,
|
||||
"manage_bg_jobs": ManageBgJobsTool().execute,
|
||||
"create_session": CreateSessionTool().execute,
|
||||
"list_sessions": ListSessionsTool().execute,
|
||||
"send_to_session": SendToSessionTool().execute,
|
||||
"manage_session": ManageSessionTool().execute,
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -52,7 +63,7 @@ PYTHON_TIMEOUT = 30
|
||||
|
||||
# Tool types that trigger execution
|
||||
TOOL_TAGS = {"bash", "python", "web_search", "web_fetch", "read_file", "write_file", "edit_file",
|
||||
"grep", "glob", "ls", "get_workspace",
|
||||
"grep", "glob", "ls", "get_workspace", "manage_bg_jobs",
|
||||
"create_document", "update_document", "edit_document",
|
||||
"search_chats",
|
||||
"chat_with_model", "create_session", "list_sessions",
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
"""Agent tool to inspect and control detached background `bash` jobs.
|
||||
|
||||
`bash` blocks prefixed with a `#!bg` marker run detached via `src.bg_jobs`; the
|
||||
agent is auto-re-invoked with the output when they finish. This tool covers the
|
||||
gaps in that flow: list the jobs in the current chat, read a still-running job's
|
||||
output on demand, and kill a runaway job instead of waiting out its max-runtime.
|
||||
|
||||
Registry tool (`TOOL_HANDLERS["manage_bg_jobs"]`). Jobs are scoped to the chat
|
||||
that launched them, so every action requires the caller's `session_id` and a job
|
||||
from another session is treated as not found.
|
||||
"""
|
||||
|
||||
import json
|
||||
import time
|
||||
from typing import Any, Dict, List
|
||||
|
||||
_LIST_ACTIONS = {"list", "ls", "jobs"}
|
||||
_OUTPUT_ACTIONS = {"output", "get", "read", "tail", "status", "show"}
|
||||
_KILL_ACTIONS = {"kill", "stop", "cancel", "terminate"}
|
||||
|
||||
|
||||
def _age(rec: Dict[str, Any]) -> str:
|
||||
start = rec.get("started_at")
|
||||
if not start:
|
||||
return "?"
|
||||
secs = int(time.time() - start)
|
||||
if secs < 60:
|
||||
return f"{secs}s"
|
||||
if secs < 3600:
|
||||
return f"{secs // 60}m"
|
||||
return f"{secs // 3600}h{(secs % 3600) // 60}m"
|
||||
|
||||
|
||||
def _status_label(rec: Dict[str, Any]) -> str:
|
||||
status = rec.get("status", "?")
|
||||
if rec.get("killed"):
|
||||
return "killed"
|
||||
if rec.get("timed_out"):
|
||||
return "timed out"
|
||||
if rec.get("died"):
|
||||
return "died"
|
||||
if status in ("done", "failed"):
|
||||
return f"{status} (exit {rec.get('exit_code')})"
|
||||
return status
|
||||
|
||||
|
||||
def _row(rec: Dict[str, Any]) -> str:
|
||||
cmd = (rec.get("command") or "").strip().splitlines()[0][:80]
|
||||
return f"[{rec.get('id')}] {_status_label(rec)} | {_age(rec)} | {cmd}"
|
||||
|
||||
|
||||
class ManageBgJobsTool:
|
||||
async def execute(self, content: str, ctx: dict) -> dict:
|
||||
from src import bg_jobs
|
||||
|
||||
session_id = ctx.get("session_id")
|
||||
raw = (content or "").strip()
|
||||
try:
|
||||
args = json.loads(raw) if raw else {}
|
||||
except (ValueError, TypeError):
|
||||
args = {}
|
||||
if not isinstance(args, dict):
|
||||
args = {}
|
||||
action = str(args.get("action", "list")).strip().lower()
|
||||
job_id = str(args.get("job_id") or args.get("id") or "").strip()
|
||||
|
||||
if not session_id:
|
||||
return {"error": "manage_bg_jobs: no active chat session; background jobs are scoped to a chat.", "exit_code": 1}
|
||||
|
||||
if action in _LIST_ACTIONS:
|
||||
jobs: List[Dict[str, Any]] = bg_jobs.list_for_session(session_id)
|
||||
if not jobs:
|
||||
return {"output": "No background jobs in this chat.", "exit_code": 0}
|
||||
jobs.sort(key=lambda r: r.get("started_at") or 0, reverse=True)
|
||||
lines = "\n".join(_row(r) for r in jobs)
|
||||
return {"output": f"{len(jobs)} background job(s):\n{lines}", "exit_code": 0}
|
||||
|
||||
if action in _OUTPUT_ACTIONS or action in _KILL_ACTIONS:
|
||||
if not job_id:
|
||||
return {"error": f"manage_bg_jobs: action '{action}' requires a job_id (see action='list').", "exit_code": 1}
|
||||
rec = bg_jobs.get(job_id)
|
||||
# Scope: only the chat that launched a job may see or control it.
|
||||
if rec is None or rec.get("session_id") != session_id:
|
||||
return {"error": f"manage_bg_jobs: no background job '{job_id}' in this chat.", "exit_code": 1}
|
||||
|
||||
if action in _KILL_ACTIONS:
|
||||
if rec.get("status") != "running":
|
||||
return {"output": f"Job `{job_id}` already {_status_label(rec)}; nothing to kill.", "exit_code": 0}
|
||||
killed = bg_jobs.kill(job_id)
|
||||
return {"output": f"Killed background job `{job_id}` ({(killed or {}).get('command', '').splitlines()[0][:80]}).", "exit_code": 0}
|
||||
|
||||
out = rec.get("output") or "(no output yet)"
|
||||
return {
|
||||
"output": f"Job `{job_id}` [{_status_label(rec)}, {_age(rec)}]\nCommand: {rec.get('command')}\n\nOutput:\n{out}",
|
||||
"exit_code": 0,
|
||||
}
|
||||
|
||||
return {"error": f"manage_bg_jobs: unknown action '{action}'. Use list, output, or kill.", "exit_code": 1}
|
||||
@@ -1,6 +1,7 @@
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import difflib
|
||||
import fnmatch
|
||||
import shutil
|
||||
@@ -16,6 +17,31 @@ _CODENAV_SKIP_DIRS = frozenset({
|
||||
_CODENAV_MAX_HITS = 200
|
||||
_CODENAV_MAX_LINE = 400
|
||||
|
||||
|
||||
def _glob_to_regex(pat: str) -> "re.Pattern":
|
||||
"""Translate a forward-slash glob (**, *, ?) into a compiled regex.
|
||||
`**/` matches zero or more complete directories.
|
||||
`*` matches within a single path segment (does not cross /).
|
||||
"""
|
||||
i, n, out = 0, len(pat), []
|
||||
while i < n:
|
||||
if pat[i : i + 3] == "**/":
|
||||
out.append("(?:[^/]+/)*")
|
||||
i += 3
|
||||
elif pat[i : i + 2] == "**":
|
||||
out.append(".*")
|
||||
i += 2
|
||||
elif pat[i] == "*":
|
||||
out.append("[^/]*")
|
||||
i += 1
|
||||
elif pat[i] == "?":
|
||||
out.append("[^/]")
|
||||
i += 1
|
||||
else:
|
||||
out.append(re.escape(pat[i]))
|
||||
i += 1
|
||||
return re.compile("".join(out))
|
||||
|
||||
def _unified_diff(old: str, new: str, path: str) -> Optional[Dict[str, Any]]:
|
||||
if old == new:
|
||||
return None
|
||||
@@ -259,23 +285,38 @@ class GlobTool:
|
||||
return {"error": f"glob: {e}", "exit_code": 1}
|
||||
|
||||
def _glob():
|
||||
from pathlib import Path
|
||||
base = Path(root)
|
||||
if not base.is_dir():
|
||||
base = os.path.abspath(root)
|
||||
if not os.path.isdir(base):
|
||||
return None, f"glob: {root}: not a directory"
|
||||
norm_pat = pattern.replace("\\", "/")
|
||||
# Fast path: literal pattern (no wildcards) → direct path lookup.
|
||||
if not any(c in norm_pat for c in "*?["):
|
||||
cand = os.path.normpath(os.path.join(base, norm_pat))
|
||||
if os.path.exists(cand):
|
||||
return [cand], None
|
||||
# Literal not at exact path — fall through to walk so
|
||||
# e.g. "foo.py" still matches at any depth (like rglob).
|
||||
# Compile glob to regex: * stays within one segment, **/ spans dirs.
|
||||
regex = _glob_to_regex(norm_pat)
|
||||
matched = []
|
||||
cap = _CODENAV_MAX_HITS * 5
|
||||
try:
|
||||
for p in base.rglob(pattern):
|
||||
if set(p.relative_to(base).parts) & _CODENAV_SKIP_DIRS:
|
||||
continue
|
||||
try:
|
||||
mtime = p.stat().st_mtime
|
||||
except OSError:
|
||||
mtime = 0
|
||||
matched.append((mtime, str(p)))
|
||||
if len(matched) > _CODENAV_MAX_HITS * 5:
|
||||
for dp, dns, fns in os.walk(base):
|
||||
# Prune skipped dirs before descending (unlike rglob which
|
||||
# descends first then filters — fatal on large node_modules).
|
||||
dns[:] = [d for d in dns if d not in _CODENAV_SKIP_DIRS]
|
||||
for name in fns + dns:
|
||||
full = os.path.join(dp, name)
|
||||
rel = os.path.relpath(full, base).replace(os.sep, "/")
|
||||
if regex.fullmatch(rel) or regex.fullmatch(name):
|
||||
try:
|
||||
mtime = os.stat(full).st_mtime
|
||||
except OSError:
|
||||
mtime = 0
|
||||
matched.append((mtime, full))
|
||||
if len(matched) > cap:
|
||||
break
|
||||
except (OSError, ValueError) as _e:
|
||||
except OSError as _e:
|
||||
return None, f"glob: {_e}"
|
||||
matched.sort(key=lambda t: t[0], reverse=True)
|
||||
return [pth for _, pth in matched[:_CODENAV_MAX_HITS]], None
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
"""model_interaction_tools.py - agent tools for talking to other models.
|
||||
|
||||
Owns the model-interaction tool implementations (chat_with_model, ask_teacher,
|
||||
list_models) and their handler classes, registered in ``TOOL_HANDLERS``. Part
|
||||
of the tool -> registry migration (#3629): the implementations were moved here
|
||||
out of ``src.ai_interaction`` so dispatch flows through the registry instead of
|
||||
the elif chain / dispatch_ai_tool in tool_execution.py.
|
||||
|
||||
Shared helpers that still live in ``src.ai_interaction`` and are used by tools
|
||||
not yet migrated (``_resolve_model``, ``AI_CHAT_TIMEOUT``) are imported lazily
|
||||
inside the functions to avoid an import cycle at module load.
|
||||
"""
|
||||
import logging
|
||||
from typing import Dict, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
_TEACHER_SYSTEM_PROMPT = (
|
||||
"You are a senior AI mentor. A less capable model is stuck on a problem and asking for help. "
|
||||
"Provide clear, actionable guidance:\n"
|
||||
"1. Brief analysis of the problem\n"
|
||||
"2. Recommended approach (step by step)\n"
|
||||
"3. Key things to watch out for\n\n"
|
||||
"Be concise and practical. No preamble."
|
||||
)
|
||||
|
||||
|
||||
async def chat_with_model(content: str, session_id: Optional[str] = None, owner: Optional[str] = None) -> Dict:
|
||||
"""Send a message to a specific model and return its response.
|
||||
|
||||
Content format:
|
||||
Line 1: model_name (or model_name@endpoint_name)
|
||||
Line 2+: the message to send
|
||||
"""
|
||||
from src.ai_interaction import _resolve_model, AI_CHAT_TIMEOUT
|
||||
from src.llm_core import llm_call_async
|
||||
|
||||
lines = content.strip().split("\n", 1)
|
||||
if not lines or not lines[0].strip():
|
||||
return {"error": "First line must be the model name"}
|
||||
|
||||
model_spec = lines[0].strip()
|
||||
message = lines[1].strip() if len(lines) > 1 else ""
|
||||
if not message:
|
||||
return {"error": "No message provided (line 2+ is the message)"}
|
||||
|
||||
try:
|
||||
url, model, headers = _resolve_model(model_spec, owner=owner)
|
||||
except ValueError as e:
|
||||
return {"error": str(e)}
|
||||
|
||||
try:
|
||||
response = await llm_call_async(
|
||||
url, model,
|
||||
[{"role": "user", "content": message}],
|
||||
headers=headers,
|
||||
timeout=AI_CHAT_TIMEOUT,
|
||||
)
|
||||
# Truncate very long responses
|
||||
if len(response) > 10000:
|
||||
response = response[:10000] + "\n... (truncated)"
|
||||
return {"model": model, "response": response}
|
||||
except Exception as e:
|
||||
logger.error(f"chat_with_model failed: {e}")
|
||||
return {"error": f"Failed to get response from {model_spec}: {e}"}
|
||||
|
||||
|
||||
async def ask_teacher(content: str, session_id: Optional[str] = None, owner: Optional[str] = None) -> Dict:
|
||||
"""Ask a more capable model for help.
|
||||
|
||||
Content format:
|
||||
Line 1: model_name (or 'auto')
|
||||
Line 2+: the problem description
|
||||
"""
|
||||
from src.ai_interaction import _resolve_model, AI_CHAT_TIMEOUT
|
||||
from src.llm_core import llm_call_async
|
||||
from src.settings import get_setting
|
||||
|
||||
lines = content.strip().split("\n", 1)
|
||||
model_spec = lines[0].strip() if lines else "auto"
|
||||
problem = lines[1].strip() if len(lines) > 1 else ""
|
||||
|
||||
if not problem:
|
||||
return {"error": "No problem description provided"}
|
||||
|
||||
if model_spec.lower() in ("auto", ""):
|
||||
model_spec = get_setting("teacher_model", "")
|
||||
if not model_spec:
|
||||
return {"error": "No teacher model configured. Specify a model name or set teacher_model in settings."}
|
||||
|
||||
try:
|
||||
url, model, headers = _resolve_model(model_spec, owner=owner)
|
||||
except ValueError as e:
|
||||
return {"error": str(e)}
|
||||
|
||||
try:
|
||||
response = await llm_call_async(
|
||||
url, model,
|
||||
[
|
||||
{"role": "system", "content": _TEACHER_SYSTEM_PROMPT},
|
||||
{"role": "user", "content": f"Problem:\n{problem}"},
|
||||
],
|
||||
headers=headers,
|
||||
timeout=AI_CHAT_TIMEOUT,
|
||||
)
|
||||
if len(response) > 8000:
|
||||
response = response[:8000] + "\n... (truncated)"
|
||||
return {"model": model, "response": response, "teacher": True}
|
||||
except Exception as e:
|
||||
logger.error(f"ask_teacher failed: {e}")
|
||||
return {"error": f"Teacher call failed ({model_spec}): {e}"}
|
||||
|
||||
|
||||
async def list_models(content: str, session_id: Optional[str] = None, owner: Optional[str] = None) -> Dict:
|
||||
"""List all available models across configured endpoints.
|
||||
|
||||
Content = optional filter keyword.
|
||||
"""
|
||||
import json
|
||||
import httpx
|
||||
from src.database import SessionLocal, ModelEndpoint
|
||||
from src.llm_core import _detect_provider, ANTHROPIC_MODELS
|
||||
from src.auth_helpers import owner_filter
|
||||
from src.endpoint_resolver import resolve_endpoint_runtime, build_headers, build_models_url
|
||||
|
||||
keyword = content.strip().lower() if content.strip() else None
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
query = db.query(ModelEndpoint).filter(ModelEndpoint.is_enabled == True)
|
||||
if owner:
|
||||
query = owner_filter(query, ModelEndpoint, owner)
|
||||
endpoints = query.all()
|
||||
if not endpoints:
|
||||
return {"results": "No enabled model endpoints configured."}
|
||||
|
||||
result_lines = []
|
||||
total_models = 0
|
||||
|
||||
for ep in endpoints:
|
||||
try:
|
||||
base, api_key = resolve_endpoint_runtime(ep, owner=owner)
|
||||
except Exception:
|
||||
continue
|
||||
provider = _detect_provider(base)
|
||||
headers = build_headers(api_key, base)
|
||||
|
||||
model_ids = []
|
||||
if provider == "anthropic":
|
||||
model_ids = list(ANTHROPIC_MODELS)
|
||||
else:
|
||||
try:
|
||||
models_url = build_models_url(base)
|
||||
if models_url:
|
||||
r = httpx.get(models_url, headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
data = r.json()
|
||||
model_ids = [m.get("id") for m in (data.get("data") or []) if m.get("id")]
|
||||
if not model_ids:
|
||||
model_ids = [
|
||||
m.get("name") or m.get("model")
|
||||
for m in (data.get("models") or [])
|
||||
if m.get("name") or m.get("model")
|
||||
]
|
||||
else:
|
||||
model_ids = json.loads(ep.cached_models or "[]")
|
||||
except Exception:
|
||||
model_ids = ["(endpoint offline)"]
|
||||
|
||||
if keyword:
|
||||
model_ids = [m for m in model_ids if keyword in m.lower() or keyword in (ep.name or "").lower()]
|
||||
|
||||
if model_ids:
|
||||
result_lines.append(f"\n**{ep.name or base}** ({provider}):")
|
||||
for mid in model_ids:
|
||||
result_lines.append(f" - `{mid}`")
|
||||
total_models += 1
|
||||
|
||||
if not result_lines:
|
||||
return {"results": "No models found" + (f" matching '{keyword}'" if keyword else "") + "."}
|
||||
|
||||
header = f"Available models ({total_models} total):"
|
||||
return {"results": header + "\n".join(result_lines)}
|
||||
except Exception as e:
|
||||
logger.error(f"list_models failed: {e}")
|
||||
return {"error": str(e)}
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Handler classes registered in TOOL_HANDLERS
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class ChatWithModelTool:
|
||||
async def execute(self, content: str, ctx: dict) -> Dict:
|
||||
return await chat_with_model(content, ctx.get("session_id"), owner=ctx.get("owner"))
|
||||
|
||||
|
||||
class AskTeacherTool:
|
||||
async def execute(self, content: str, ctx: dict) -> Dict:
|
||||
return await ask_teacher(content, ctx.get("session_id"), owner=ctx.get("owner"))
|
||||
|
||||
|
||||
class ListModelsTool:
|
||||
async def execute(self, content: str, ctx: dict) -> Dict:
|
||||
return await list_models(content, ctx.get("session_id"), owner=ctx.get("owner"))
|
||||
@@ -0,0 +1,464 @@
|
||||
"""session_tools.py - agent tools for AI-to-AI session management.
|
||||
|
||||
Owns create_session, list_sessions, send_to_session and manage_session, moved
|
||||
out of src.ai_interaction as part of the tool -> registry migration (#3629), and
|
||||
their handler classes registered in TOOL_HANDLERS.
|
||||
|
||||
The session manager is a runtime-set singleton in src.ai_interaction, so each
|
||||
function fetches it via get_session_manager() (imported here); _resolve_model and
|
||||
AI_CHAT_TIMEOUT are reused from there too.
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import uuid
|
||||
from typing import Dict, Optional
|
||||
|
||||
from src.ai_interaction import get_session_manager, _resolve_model, AI_CHAT_TIMEOUT
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def create_session(content: str, session_id: Optional[str] = None, owner: Optional[str] = None) -> Dict:
|
||||
"""Create a new chat session.
|
||||
|
||||
Content format:
|
||||
Line 1: session name
|
||||
Line 2: model_name (or model_name@endpoint_name)
|
||||
"""
|
||||
_session_manager = get_session_manager()
|
||||
if not _session_manager:
|
||||
return {"error": "Session manager not available"}
|
||||
|
||||
lines = content.strip().split("\n")
|
||||
if len(lines) < 2:
|
||||
return {"error": "Need 2 lines: session name, then model spec"}
|
||||
|
||||
name = lines[0].strip()
|
||||
model_spec = lines[1].strip()
|
||||
|
||||
if not name:
|
||||
return {"error": "Session name cannot be empty"}
|
||||
|
||||
try:
|
||||
url, model, headers = _resolve_model(model_spec, owner=owner)
|
||||
except ValueError as e:
|
||||
return {"error": str(e)}
|
||||
|
||||
sid = str(uuid.uuid4())[:8]
|
||||
try:
|
||||
_session_manager.create_session(
|
||||
session_id=sid,
|
||||
name=name,
|
||||
endpoint_url=url,
|
||||
model=model,
|
||||
rag=False,
|
||||
owner=owner,
|
||||
)
|
||||
# Store headers on session for future calls
|
||||
sess = _session_manager.get_session(sid)
|
||||
if sess and headers:
|
||||
sess.headers = headers
|
||||
try:
|
||||
from src.event_bus import fire_event
|
||||
fire_event("session_created", owner)
|
||||
except Exception:
|
||||
logger.debug("session_created event dispatch failed", exc_info=True)
|
||||
|
||||
return {"session_id": sid, "name": name, "model": model, "endpoint_url": url}
|
||||
except Exception as e:
|
||||
logger.error(f"create_session failed: {e}")
|
||||
return {"error": f"Failed to create session: {e}"}
|
||||
|
||||
async def list_sessions(content: str, session_id: Optional[str] = None, owner: Optional[str] = None) -> Dict:
|
||||
"""List sessions sorted by most-recently-active first.
|
||||
|
||||
Output includes a relative "last active" timestamp per row so the
|
||||
agent can answer "open my last chat" without guessing from titles.
|
||||
The most-recent session is always first in the list.
|
||||
|
||||
Content = optional filter keyword (matches session name).
|
||||
"""
|
||||
_session_manager = get_session_manager()
|
||||
if not _session_manager:
|
||||
return {"error": "Session manager not available"}
|
||||
|
||||
keyword = content.strip().lower() if content.strip() else None
|
||||
|
||||
try:
|
||||
from core.database import SessionLocal, Session as DbSession
|
||||
from datetime import datetime, timezone
|
||||
|
||||
# Pull every session's last_accessed from the DB so we can sort
|
||||
# by recency. In-memory sessions hold name + model + msg_count;
|
||||
# the DB row holds the timestamps.
|
||||
db = SessionLocal()
|
||||
try:
|
||||
db_rows = {r.id: r for r in db.query(DbSession).all()}
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
# SECURITY: scope to the caller's sessions. Passing None returned
|
||||
# every user's sessions, which the agent tool then exposed via the
|
||||
# "list my chats" reply.
|
||||
sessions = _session_manager.get_sessions_for_user(owner)
|
||||
rows = []
|
||||
for sid, sess in sessions.items():
|
||||
if keyword and keyword not in (sess.name or "").lower():
|
||||
continue
|
||||
db_row = db_rows.get(sid)
|
||||
# Prefer last_accessed; fall back to updated_at, then created_at.
|
||||
ts = None
|
||||
if db_row:
|
||||
ts = getattr(db_row, 'last_accessed', None) or getattr(db_row, 'updated_at', None) or getattr(db_row, 'created_at', None)
|
||||
rows.append((ts, sid, sess))
|
||||
|
||||
# Sort by timestamp DESC; rows without a timestamp sink to the bottom.
|
||||
rows.sort(key=lambda r: r[0] or datetime.min, reverse=True)
|
||||
|
||||
def _rel(ts):
|
||||
if not ts:
|
||||
return 'never'
|
||||
now = datetime.utcnow()
|
||||
try:
|
||||
if ts.tzinfo is not None:
|
||||
now = datetime.now(timezone.utc)
|
||||
diff = (now - ts).total_seconds()
|
||||
except Exception:
|
||||
return 'unknown'
|
||||
if diff < 60: return 'just now'
|
||||
if diff < 3600: return f'{int(diff / 60)}m ago'
|
||||
if diff < 86400: return f'{int(diff / 3600)}h ago'
|
||||
if diff < 86400 * 7: return f'{int(diff / 86400)}d ago'
|
||||
return ts.strftime('%Y-%m-%d')
|
||||
|
||||
lines = []
|
||||
for i, (ts, sid, sess) in enumerate(rows):
|
||||
if i >= 50:
|
||||
lines.append(f"... and {len(rows) - 50} more (showing first 50)")
|
||||
break
|
||||
safe_name = (sess.name or "Untitled").replace("[", "\\[").replace("]", "\\]")
|
||||
msg_count = getattr(sess, "message_count", 0) or 0
|
||||
model = getattr(sess, "model", "unknown")
|
||||
marker = " ← most recent" if i == 0 else ""
|
||||
lines.append(f"- **[{safe_name}](#session-{sid})** (id: `{sid}`, model: {model}, {msg_count} msgs, last active {_rel(ts)}){marker}")
|
||||
|
||||
if not lines:
|
||||
return {"results": "No sessions found" + (f" matching '{keyword}'" if keyword else "") + "."}
|
||||
|
||||
return {
|
||||
"results": (
|
||||
f"Found {len(rows)} session(s), sorted most-recent first:\n"
|
||||
+ "\n".join(lines)
|
||||
+ "\n\nAssistant: when replying to the user, preserve the chat-title markdown links exactly as shown, e.g. `[Chat](#session-id)`. Do not rewrite this as a plain, non-clickable table."
|
||||
)
|
||||
}
|
||||
except Exception as e:
|
||||
logger.error(f"list_sessions failed: {e}")
|
||||
return {"error": str(e)}
|
||||
|
||||
async def send_to_session(content: str, session_id: Optional[str] = None, owner: Optional[str] = None) -> Dict:
|
||||
"""Send a message to an existing session and get a response.
|
||||
|
||||
Content format:
|
||||
Line 1: session_id
|
||||
Line 2+: message
|
||||
"""
|
||||
_session_manager = get_session_manager()
|
||||
from src.llm_core import llm_call_async
|
||||
from core.models import ChatMessage
|
||||
|
||||
if not _session_manager:
|
||||
return {"error": "Session manager not available"}
|
||||
|
||||
lines = content.strip().split("\n", 1)
|
||||
if len(lines) < 2:
|
||||
return {"error": "Need 2 lines: session_id, then message"}
|
||||
|
||||
target_sid = lines[0].strip()
|
||||
message = lines[1].strip()
|
||||
|
||||
sess = _session_manager.get_session(target_sid)
|
||||
if not sess:
|
||||
return {"error": f"Session '{target_sid}' not found"}
|
||||
|
||||
# Owner-scope: reject access to another user's session
|
||||
if owner and getattr(sess, "owner", None) and sess.owner != owner:
|
||||
return {"error": f"Session '{target_sid}' not found"}
|
||||
|
||||
if not message:
|
||||
return {"error": "No message provided"}
|
||||
|
||||
try:
|
||||
# Build context from session history
|
||||
context = sess.get_context_messages()
|
||||
context.append({"role": "user", "content": message})
|
||||
|
||||
response = await llm_call_async(
|
||||
sess.endpoint_url, sess.model, context,
|
||||
headers=sess.headers,
|
||||
timeout=AI_CHAT_TIMEOUT,
|
||||
)
|
||||
|
||||
# Save both messages to session
|
||||
sess.add_message(ChatMessage("user", message))
|
||||
sess.add_message(ChatMessage("assistant", response))
|
||||
|
||||
# Truncate for tool output
|
||||
if len(response) > 10000:
|
||||
response = response[:10000] + "\n... (truncated)"
|
||||
|
||||
return {
|
||||
"session_id": target_sid,
|
||||
"session_name": sess.name,
|
||||
"response": response,
|
||||
}
|
||||
except Exception as e:
|
||||
logger.error(f"send_to_session failed: {e}")
|
||||
return {"error": f"Failed to send to session: {e}"}
|
||||
|
||||
async def manage_session(content: str, session_id: Optional[str] = None, owner: Optional[str] = None) -> Dict:
|
||||
"""Manage sessions: rename, archive, delete, important, truncate, fork.
|
||||
|
||||
Content format:
|
||||
Line 1: action (rename|archive|unarchive|delete|important|unimportant|truncate|fork)
|
||||
Line 2: target session_id (or "current" to use the active session)
|
||||
Line 3+: action-specific params (e.g. new name for rename, keep_count for truncate)
|
||||
"""
|
||||
_session_manager = get_session_manager()
|
||||
if not _session_manager:
|
||||
return {"error": "Session manager not available"}
|
||||
|
||||
from src.database import SessionLocal, Session as DbSession
|
||||
|
||||
# Accept BOTH the structured JSON args the tool schema advertises
|
||||
# ({action, session_id, value}) AND the legacy line-based format
|
||||
# (line1=action, line2=session_id, line3=value). Native function-calling
|
||||
# models send JSON; fenced-block callers send lines. Previously only the
|
||||
# line format was parsed, so a model that followed the schema (JSON) got
|
||||
# "Need at least 2 lines" / "Rename needs line 3" and couldn't drive it.
|
||||
_raw = (content or "").strip()
|
||||
action = ""
|
||||
target_sid = ""
|
||||
value = None # the action param: new name (rename) / keep_count (truncate, fork)
|
||||
_list_filter = ""
|
||||
_parsed = None
|
||||
if _raw.startswith("{"):
|
||||
try:
|
||||
_parsed = json.loads(_raw)
|
||||
except Exception:
|
||||
_parsed = None
|
||||
if isinstance(_parsed, dict):
|
||||
action = str(_parsed.get("action") or "").strip().lower()
|
||||
target_sid = str(_parsed.get("session_id") or _parsed.get("session") or _parsed.get("id") or "").strip()
|
||||
_v = _parsed.get("value")
|
||||
if _v is None:
|
||||
_v = (_parsed.get("name") or _parsed.get("new_name")
|
||||
or _parsed.get("title") or _parsed.get("keep_count"))
|
||||
value = None if _v is None else str(_v).strip()
|
||||
_list_filter = str(_parsed.get("filter") or "").strip()
|
||||
else:
|
||||
lines = _raw.split("\n")
|
||||
if not lines or not lines[0].strip():
|
||||
return {"error": "Missing action (rename|archive|delete|important|truncate|fork|list|switch)"}
|
||||
action = lines[0].strip().lower()
|
||||
target_sid = lines[1].strip() if len(lines) >= 2 else ""
|
||||
value = lines[2].strip() if len(lines) >= 3 else None
|
||||
_list_filter = "\n".join(lines[1:]).strip()
|
||||
|
||||
if not action:
|
||||
return {"error": "Missing action (rename|archive|delete|important|truncate|fork|list|switch)"}
|
||||
|
||||
# `list` alias - dispatch to list_sessions so the agent's natural
|
||||
# first guess (every other manage_* tool has a `list` action) works.
|
||||
if action == "list":
|
||||
return await list_sessions(_list_filter, session_id, owner=owner)
|
||||
|
||||
if not target_sid:
|
||||
return {"error": "Need a session_id (or 'current' for the active chat)"}
|
||||
|
||||
# Allow "current" to refer to the active session
|
||||
if target_sid.lower() == "current" and session_id:
|
||||
target_sid = session_id
|
||||
|
||||
# `switch` / `open` / `select` / `view` - the agent reaches for
|
||||
# these when the user asks to "open" or "switch to" a session.
|
||||
# There's no server-side way to make the browser navigate, so we
|
||||
# just return a clickable anchor link the user can click. The
|
||||
# frontend's chat-history click delegate routes `#session-<id>`
|
||||
# to selectSession(). The agent's reply naturally embeds this
|
||||
# result so the user sees a single clickable line.
|
||||
def _session_query(db):
|
||||
query = db.query(DbSession).filter(DbSession.id == target_sid)
|
||||
if owner is not None:
|
||||
query = query.filter(DbSession.owner == owner)
|
||||
return query
|
||||
|
||||
if action in ("switch", "open", "select", "view"):
|
||||
db = SessionLocal()
|
||||
try:
|
||||
db_sess = _session_query(db).first()
|
||||
if not db_sess:
|
||||
return {"error": f"Session '{target_sid}' not found. Use list_sessions and pass the exact id it returned."}
|
||||
name = db_sess.name or target_sid
|
||||
finally:
|
||||
db.close()
|
||||
return {
|
||||
"action": action,
|
||||
"session_id": target_sid,
|
||||
"name": name,
|
||||
"results": f"[{name}](#session-{target_sid}) - click to open.",
|
||||
}
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
if action == "rename":
|
||||
if not value:
|
||||
return {"error": "rename needs a new name (the `value` arg, or line 3 in the legacy format)"}
|
||||
new_name = value
|
||||
db_sess = _session_query(db).first()
|
||||
if not db_sess:
|
||||
return {"error": f"Session '{target_sid}' not found. Use list_sessions and pass the exact id it returned."}
|
||||
db_sess.name = new_name
|
||||
db.commit()
|
||||
_session_manager.update_session_name(target_sid, new_name)
|
||||
return {"action": "rename", "session_id": target_sid, "name": new_name,
|
||||
"results": f"Session renamed to '{new_name}'"}
|
||||
|
||||
elif action == "archive":
|
||||
db_sess = _session_query(db).first()
|
||||
if not db_sess:
|
||||
return {"error": f"Session '{target_sid}' not found. Use list_sessions and pass the exact id it returned."}
|
||||
db_sess.archived = True
|
||||
db.commit()
|
||||
return {"action": "archive", "session_id": target_sid,
|
||||
"results": f"Session '{db_sess.name}' archived"}
|
||||
|
||||
elif action == "unarchive":
|
||||
db_sess = _session_query(db).first()
|
||||
if not db_sess:
|
||||
return {"error": f"Session '{target_sid}' not found. Use list_sessions and pass the exact id it returned."}
|
||||
db_sess.archived = False
|
||||
db.commit()
|
||||
return {"action": "unarchive", "session_id": target_sid,
|
||||
"results": f"Session '{db_sess.name}' unarchived"}
|
||||
|
||||
elif action == "delete":
|
||||
if target_sid == session_id:
|
||||
return {"error": "Cannot delete the current session while chatting in it. Delete other sessions first."}
|
||||
db_sess = _session_query(db).first()
|
||||
if not db_sess:
|
||||
return {"error": f"Session '{target_sid}' not found. Refusing to delete an unknown chat id; use the exact id from list_sessions."}
|
||||
if db_sess and db_sess.is_important:
|
||||
return {"error": f"Session '{db_sess.name}' is starred/favorited. Unstar it first before deleting."}
|
||||
try:
|
||||
ok = _session_manager.delete_session(target_sid)
|
||||
if not ok:
|
||||
return {"error": f"Session '{target_sid}' was not deleted because it no longer exists."}
|
||||
return {"action": "delete", "session_id": target_sid,
|
||||
"results": f"Session '{db_sess.name or target_sid}' deleted"}
|
||||
except Exception as e:
|
||||
return {"error": f"Failed to delete session: {e}"}
|
||||
|
||||
elif action in ("important", "unimportant"):
|
||||
is_important = action == "important"
|
||||
db_sess = _session_query(db).first()
|
||||
if not db_sess:
|
||||
return {"error": f"Session '{target_sid}' not found. Use list_sessions and pass the exact id it returned."}
|
||||
# Prevent AI from unstarring sessions - only the user can do that manually
|
||||
if not is_important and db_sess.is_important:
|
||||
return {"error": f"Session '{db_sess.name}' is starred by the user. Only the user can unstar sessions manually."}
|
||||
db_sess.is_important = is_important
|
||||
db.commit()
|
||||
status = "marked as important" if is_important else "unmarked as important"
|
||||
return {"action": action, "session_id": target_sid,
|
||||
"results": f"Session '{db_sess.name}' {status}"}
|
||||
|
||||
elif action == "truncate":
|
||||
db_sess = _session_query(db).first()
|
||||
if not db_sess:
|
||||
return {"error": f"Session '{target_sid}' not found. Use list_sessions and pass the exact id it returned."}
|
||||
keep_count = 10
|
||||
if value:
|
||||
try:
|
||||
keep_count = int(value)
|
||||
except ValueError:
|
||||
pass
|
||||
success = _session_manager.truncate_messages(target_sid, keep_count)
|
||||
if success:
|
||||
return {"action": "truncate", "session_id": target_sid,
|
||||
"results": f"Session truncated to last {keep_count} messages"}
|
||||
return {"error": f"Failed to truncate session '{target_sid}'"}
|
||||
|
||||
elif action == "fork":
|
||||
db_sess = _session_query(db).first()
|
||||
if not db_sess:
|
||||
return {"error": f"Session '{target_sid}' not found. Use list_sessions and pass the exact id it returned."}
|
||||
keep_count = 0 # 0 = all messages
|
||||
if value:
|
||||
try:
|
||||
keep_count = int(value)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
source = _session_manager.get_session(target_sid)
|
||||
if not source:
|
||||
return {"error": f"Session '{target_sid}' not found"}
|
||||
|
||||
new_sid = str(uuid.uuid4())[:8]
|
||||
_session_manager.create_session(
|
||||
session_id=new_sid,
|
||||
name=f"Fork: {source.name}",
|
||||
endpoint_url=source.endpoint_url,
|
||||
model=source.model,
|
||||
rag=False,
|
||||
owner=owner,
|
||||
)
|
||||
# Copy messages
|
||||
history = source.get_context_messages()
|
||||
if keep_count > 0:
|
||||
history = history[:keep_count]
|
||||
from core.models import ChatMessage as InMemoryMsg
|
||||
new_sess = _session_manager.get_session(new_sid)
|
||||
for msg in history:
|
||||
new_sess.add_message(InMemoryMsg(msg["role"], msg["content"]))
|
||||
try:
|
||||
from src.event_bus import fire_event
|
||||
fire_event("session_created", owner)
|
||||
except Exception:
|
||||
logger.debug("session_created event dispatch failed", exc_info=True)
|
||||
|
||||
return {"action": "fork", "session_id": new_sid,
|
||||
"source_session": target_sid, "messages_copied": len(history),
|
||||
"results": f"Forked session '{source.name}' -> new session {new_sid} ({len(history)} messages)"}
|
||||
|
||||
else:
|
||||
return {"error": f"Unknown action '{action}'. Use: list, switch, rename, archive, unarchive, delete, important, unimportant, truncate, fork"}
|
||||
except Exception as e:
|
||||
logger.error(f"manage_session failed: {e}")
|
||||
return {"error": str(e)}
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Handler classes registered in TOOL_HANDLERS
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class CreateSessionTool:
|
||||
async def execute(self, content: str, ctx: dict) -> Dict:
|
||||
return await create_session(content, ctx.get("session_id"), owner=ctx.get("owner"))
|
||||
|
||||
|
||||
class ListSessionsTool:
|
||||
async def execute(self, content: str, ctx: dict) -> Dict:
|
||||
return await list_sessions(content, ctx.get("session_id"), owner=ctx.get("owner"))
|
||||
|
||||
|
||||
class SendToSessionTool:
|
||||
async def execute(self, content: str, ctx: dict) -> Dict:
|
||||
return await send_to_session(content, ctx.get("session_id"), owner=ctx.get("owner"))
|
||||
|
||||
|
||||
class ManageSessionTool:
|
||||
async def execute(self, content: str, ctx: dict) -> Dict:
|
||||
return await manage_session(content, ctx.get("session_id"), owner=ctx.get("owner"))
|
||||
@@ -57,13 +57,23 @@ class WebSearchTool:
|
||||
class WebFetchTool:
|
||||
async def execute(self, content: str, ctx: dict) -> dict:
|
||||
from src.search.content import fetch_webpage_content
|
||||
from src.constants import WEB_FETCH_HARD_MAX_BYTES
|
||||
raw = content.strip()
|
||||
url = ""
|
||||
max_bytes = None
|
||||
if raw.startswith("{"):
|
||||
try:
|
||||
parsed = json.loads(raw)
|
||||
if isinstance(parsed, dict):
|
||||
url = str(parsed.get("url") or "").strip()
|
||||
# Download-budget override (#3812): "full": true raises the
|
||||
# budget to the hard cap; an explicit max_bytes is clamped
|
||||
# to the hard cap downstream. Default stays the soft cap.
|
||||
if parsed.get("full") is True:
|
||||
max_bytes = WEB_FETCH_HARD_MAX_BYTES
|
||||
mb = parsed.get("max_bytes")
|
||||
if isinstance(mb, int) and mb > 0:
|
||||
max_bytes = mb
|
||||
except json.JSONDecodeError:
|
||||
url = ""
|
||||
if not url:
|
||||
@@ -78,7 +88,7 @@ class WebFetchTool:
|
||||
loop = asyncio.get_running_loop()
|
||||
try:
|
||||
result = await asyncio.wait_for(
|
||||
loop.run_in_executor(None, lambda: fetch_webpage_content(url, timeout=10)),
|
||||
loop.run_in_executor(None, lambda: fetch_webpage_content(url, timeout=10, max_bytes=max_bytes)),
|
||||
timeout=30,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
@@ -94,8 +104,28 @@ class WebFetchTool:
|
||||
return {"error": f"web_fetch: {url}: {err}", "exit_code": 1}
|
||||
return {"error": f"web_fetch: {url}: no readable text content (not HTML, or the page needs JS/login)", "exit_code": 1}
|
||||
|
||||
# Tell the model when the download budget cut the body short and how
|
||||
# to get the rest, instead of silently presenting a partial page as
|
||||
# the whole thing.
|
||||
size_note = ""
|
||||
if result.get("truncated"):
|
||||
fetched = result.get("fetched_bytes") or 0
|
||||
total = result.get("total_bytes")
|
||||
total_txt = f" of {total:,} bytes" if total else ""
|
||||
size_note = (
|
||||
f"[partial content: download stopped at {fetched:,} bytes{total_txt}. "
|
||||
f'Re-call with {{"url": "{url}", "full": true}} to fetch up to '
|
||||
f"{WEB_FETCH_HARD_MAX_BYTES:,} bytes.]\n\n"
|
||||
)
|
||||
|
||||
# The notice must lead the output so the MAX_OUTPUT_CHARS trim below can
|
||||
# never drop it. The title is untrusted, uncapped page content, so a
|
||||
# giant title ahead of the notice could push it out of range; keep the
|
||||
# notice first and cap the title as a second guard.
|
||||
if len(title) > 300:
|
||||
title = title[:300] + "..."
|
||||
header = (f"# {title}\n" if title else "") + f"Source: {url}\n\n"
|
||||
output = header + text
|
||||
output = size_note + header + text
|
||||
if len(output) > MAX_OUTPUT_CHARS:
|
||||
output = output[:MAX_OUTPUT_CHARS] + "\n\n[...truncated]"
|
||||
return {"output": output, "exit_code": 0}
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
"""
|
||||
ai_interaction.py
|
||||
|
||||
AI-to-AI interaction tools: chat_with_model, create_session, list_sessions,
|
||||
send_to_session, pipeline.
|
||||
AI-to-AI interaction tools: pipeline and manage_memory, plus shared model
|
||||
resolution (_resolve_model), the session-manager singleton, and dispatch_ai_tool.
|
||||
|
||||
As part of the tool -> registry migration (#3629), chat_with_model, ask_teacher
|
||||
and list_models moved to src/agent_tools/model_interaction_tools.py, and
|
||||
create_session, list_sessions, send_to_session and manage_session moved to
|
||||
src/agent_tools/session_tools.py. Those modules reuse get_session_manager /
|
||||
_resolve_model / AI_CHAT_TIMEOUT from here.
|
||||
|
||||
These are agent tools — the LLM writes fenced code blocks and they execute
|
||||
through the standard agent_tools.py pipeline.
|
||||
@@ -159,440 +165,6 @@ def _resolve_model(spec: str, owner: Optional[str] = None) -> Tuple[str, str, Di
|
||||
# Tool implementations
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
async def do_chat_with_model(content: str, session_id: Optional[str] = None, owner: Optional[str] = None) -> Dict:
|
||||
"""Send a message to a specific model and return its response.
|
||||
|
||||
Content format:
|
||||
Line 1: model_name (or model_name@endpoint_name)
|
||||
Line 2+: the message to send
|
||||
"""
|
||||
from src.llm_core import llm_call_async
|
||||
|
||||
lines = content.strip().split("\n", 1)
|
||||
if not lines or not lines[0].strip():
|
||||
return {"error": "First line must be the model name"}
|
||||
|
||||
model_spec = lines[0].strip()
|
||||
message = lines[1].strip() if len(lines) > 1 else ""
|
||||
if not message:
|
||||
return {"error": "No message provided (line 2+ is the message)"}
|
||||
|
||||
try:
|
||||
url, model, headers = _resolve_model(model_spec, owner=owner)
|
||||
except ValueError as e:
|
||||
return {"error": str(e)}
|
||||
|
||||
try:
|
||||
response = await llm_call_async(
|
||||
url, model,
|
||||
[{"role": "user", "content": message}],
|
||||
headers=headers,
|
||||
timeout=AI_CHAT_TIMEOUT,
|
||||
)
|
||||
# Truncate very long responses
|
||||
if len(response) > 10000:
|
||||
response = response[:10000] + "\n... (truncated)"
|
||||
return {"model": model, "response": response}
|
||||
except Exception as e:
|
||||
logger.error(f"chat_with_model failed: {e}")
|
||||
return {"error": f"Failed to get response from {model_spec}: {e}"}
|
||||
|
||||
|
||||
_TEACHER_SYSTEM_PROMPT = (
|
||||
"You are a senior AI mentor. A less capable model is stuck on a problem and asking for help. "
|
||||
"Provide clear, actionable guidance:\n"
|
||||
"1. Brief analysis of the problem\n"
|
||||
"2. Recommended approach (step by step)\n"
|
||||
"3. Key things to watch out for\n\n"
|
||||
"Be concise and practical. No preamble."
|
||||
)
|
||||
|
||||
|
||||
async def do_ask_teacher(content: str, session_id: Optional[str] = None, owner: Optional[str] = None) -> Dict:
|
||||
"""Ask a more capable model for help.
|
||||
|
||||
Content format:
|
||||
Line 1: model_name (or 'auto')
|
||||
Line 2+: the problem description
|
||||
"""
|
||||
from src.llm_core import llm_call_async
|
||||
from src.settings import get_setting
|
||||
|
||||
lines = content.strip().split("\n", 1)
|
||||
model_spec = lines[0].strip() if lines else "auto"
|
||||
problem = lines[1].strip() if len(lines) > 1 else ""
|
||||
|
||||
if not problem:
|
||||
return {"error": "No problem description provided"}
|
||||
|
||||
if model_spec.lower() in ("auto", ""):
|
||||
model_spec = get_setting("teacher_model", "")
|
||||
if not model_spec:
|
||||
return {"error": "No teacher model configured. Specify a model name or set teacher_model in settings."}
|
||||
|
||||
try:
|
||||
url, model, headers = _resolve_model(model_spec, owner=owner)
|
||||
except ValueError as e:
|
||||
return {"error": str(e)}
|
||||
|
||||
try:
|
||||
response = await llm_call_async(
|
||||
url, model,
|
||||
[
|
||||
{"role": "system", "content": _TEACHER_SYSTEM_PROMPT},
|
||||
{"role": "user", "content": f"Problem:\n{problem}"},
|
||||
],
|
||||
headers=headers,
|
||||
timeout=AI_CHAT_TIMEOUT,
|
||||
)
|
||||
if len(response) > 8000:
|
||||
response = response[:8000] + "\n... (truncated)"
|
||||
return {"model": model, "response": response, "teacher": True}
|
||||
except Exception as e:
|
||||
logger.error(f"ask_teacher failed: {e}")
|
||||
return {"error": f"Teacher call failed ({model_spec}): {e}"}
|
||||
|
||||
|
||||
async def do_second_opinion(content: str, session_id: Optional[str] = None, owner: Optional[str] = None) -> Dict:
|
||||
"""Get a second opinion from another model, then have the original model
|
||||
evaluate the feedback and produce a unified version.
|
||||
|
||||
Content format:
|
||||
Line 1: model_name (or model_name@endpoint_name)
|
||||
Line 2+ (optional): specific question or focus area
|
||||
|
||||
Flow:
|
||||
1. Pull recent conversation context
|
||||
2. Send to reviewer model → get honest feedback
|
||||
3. Send feedback back to the session's own model → evaluate & unify
|
||||
4. Return both the review and the unified response
|
||||
"""
|
||||
from src.llm_core import llm_call_async
|
||||
|
||||
lines = content.strip().split("\n", 1)
|
||||
if not lines or not lines[0].strip():
|
||||
return {"error": "First line must be the model name"}
|
||||
|
||||
model_spec = lines[0].strip()
|
||||
focus = lines[1].strip() if len(lines) > 1 else ""
|
||||
|
||||
try:
|
||||
reviewer_url, reviewer_model, reviewer_headers = _resolve_model(model_spec, owner=owner)
|
||||
except ValueError as e:
|
||||
return {"error": str(e)}
|
||||
|
||||
# Pull recent conversation context from current session
|
||||
context_text = ""
|
||||
sess = None
|
||||
if session_id and _session_manager:
|
||||
sess = _session_manager.get_session(session_id)
|
||||
if sess:
|
||||
messages = sess.get_context_messages()
|
||||
recent = messages[-15:] if len(messages) > 15 else messages
|
||||
parts = []
|
||||
for m in recent:
|
||||
role = m.get("role", "unknown").upper()
|
||||
text = m.get("content", "")
|
||||
if isinstance(text, list):
|
||||
text = " ".join(
|
||||
p.get("text", "") for p in text if isinstance(p, dict)
|
||||
)
|
||||
if text:
|
||||
parts.append(f"[{role}]: {text[:2000]}")
|
||||
context_text = "\n\n".join(parts)
|
||||
|
||||
if not context_text:
|
||||
return {"error": "No conversation context found to review"}
|
||||
|
||||
# ── Step 1: Get the reviewer's feedback ──
|
||||
reviewer_system = (
|
||||
"You are giving a second opinion on a conversation between a user and an AI assistant. "
|
||||
"Your job is to be genuinely helpful and honest — not a yes-man, but not a contrarian either.\n\n"
|
||||
"Guidelines:\n"
|
||||
"- If the plan/idea is solid, say so clearly. Don't manufacture problems that aren't there.\n"
|
||||
"- If you spot a real flaw, blind spot, or simpler approach — call it out directly.\n"
|
||||
"- Be practical. Don't over-engineer or over-analyze. Real-world tradeoffs matter.\n"
|
||||
"- If there's a meaningfully better way to do something, suggest it concretely.\n"
|
||||
"- Give credit where it's due — highlight what's working well.\n"
|
||||
"- Keep it concise and actionable. No fluff.\n"
|
||||
"- You're a second pair of eyes, not a professor grading a paper."
|
||||
)
|
||||
|
||||
reviewer_message = f"Here's the conversation so far:\n\n{context_text}"
|
||||
if focus:
|
||||
reviewer_message += f"\n\n---\nSpecifically, I want your take on: {focus}"
|
||||
else:
|
||||
reviewer_message += "\n\n---\nGive me your honest second opinion on what's being discussed."
|
||||
|
||||
try:
|
||||
review = await llm_call_async(
|
||||
reviewer_url, reviewer_model,
|
||||
[
|
||||
{"role": "system", "content": reviewer_system},
|
||||
{"role": "user", "content": reviewer_message},
|
||||
],
|
||||
headers=reviewer_headers,
|
||||
timeout=AI_CHAT_TIMEOUT,
|
||||
)
|
||||
if len(review) > 8000:
|
||||
review = review[:8000] + "\n... (truncated)"
|
||||
except Exception as e:
|
||||
logger.error(f"second_opinion reviewer call failed: {e}")
|
||||
return {"error": f"Failed to get second opinion from {model_spec}: {e}"}
|
||||
|
||||
# ── Step 2: Send review back to session's own model for evaluation ──
|
||||
unified = ""
|
||||
original_model = "unknown"
|
||||
if sess:
|
||||
original_url = sess.endpoint_url
|
||||
original_model = sess.model
|
||||
original_headers = getattr(sess, "headers", None) or {}
|
||||
|
||||
unify_system = (
|
||||
"Another AI model just reviewed the conversation you've been having with the user. "
|
||||
"Read their feedback carefully, then respond with:\n\n"
|
||||
"1. **What you agree with** — acknowledge valid points honestly.\n"
|
||||
"2. **What you disagree with** — explain why, briefly.\n"
|
||||
"3. **Unified version** — produce an updated/refined version of whatever was being discussed, "
|
||||
"incorporating the feedback you found valid. Don't accept every note blindly — "
|
||||
"use your judgment on what actually improves things vs what's unnecessary.\n\n"
|
||||
"Be concise and practical. The user wants a better result, not a meta-discussion."
|
||||
)
|
||||
|
||||
unify_message = (
|
||||
f"Here's the conversation context:\n\n{context_text}\n\n"
|
||||
f"---\n\n"
|
||||
f"**Review from {reviewer_model}:**\n\n{review}\n\n"
|
||||
f"---\n\n"
|
||||
f"Evaluate this feedback and produce a unified improved version."
|
||||
)
|
||||
|
||||
try:
|
||||
unified = await llm_call_async(
|
||||
original_url, original_model,
|
||||
[
|
||||
{"role": "system", "content": unify_system},
|
||||
{"role": "user", "content": unify_message},
|
||||
],
|
||||
headers=original_headers,
|
||||
timeout=AI_CHAT_TIMEOUT,
|
||||
)
|
||||
if len(unified) > 10000:
|
||||
unified = unified[:10000] + "\n... (truncated)"
|
||||
except Exception as e:
|
||||
logger.error(f"second_opinion unify call failed: {e}")
|
||||
unified = f"(Failed to get unified response: {e})"
|
||||
|
||||
# Build combined result
|
||||
combined = (
|
||||
f"## Second Opinion from {reviewer_model}\n\n{review}"
|
||||
f"\n\n---\n\n"
|
||||
f"## {original_model}'s Response\n\n{unified}"
|
||||
)
|
||||
|
||||
return {
|
||||
"model": reviewer_model,
|
||||
"response": combined,
|
||||
"instruction": "Present these results to the user exactly as they are. Do NOT call second_opinion again. The user can continue the conversation from here.",
|
||||
}
|
||||
|
||||
|
||||
async def do_create_session(content: str, session_id: Optional[str] = None, owner: Optional[str] = None) -> Dict:
|
||||
"""Create a new chat session.
|
||||
|
||||
Content format:
|
||||
Line 1: session name
|
||||
Line 2: model_name (or model_name@endpoint_name)
|
||||
"""
|
||||
if not _session_manager:
|
||||
return {"error": "Session manager not available"}
|
||||
|
||||
lines = content.strip().split("\n")
|
||||
if len(lines) < 2:
|
||||
return {"error": "Need 2 lines: session name, then model spec"}
|
||||
|
||||
name = lines[0].strip()
|
||||
model_spec = lines[1].strip()
|
||||
|
||||
if not name:
|
||||
return {"error": "Session name cannot be empty"}
|
||||
|
||||
try:
|
||||
url, model, headers = _resolve_model(model_spec, owner=owner)
|
||||
except ValueError as e:
|
||||
return {"error": str(e)}
|
||||
|
||||
sid = str(uuid.uuid4())[:8]
|
||||
try:
|
||||
_session_manager.create_session(
|
||||
session_id=sid,
|
||||
name=name,
|
||||
endpoint_url=url,
|
||||
model=model,
|
||||
rag=False,
|
||||
owner=owner,
|
||||
)
|
||||
# Store headers on session for future calls
|
||||
sess = _session_manager.get_session(sid)
|
||||
if sess and headers:
|
||||
sess.headers = headers
|
||||
try:
|
||||
from src.event_bus import fire_event
|
||||
fire_event("session_created", owner)
|
||||
except Exception:
|
||||
logger.debug("session_created event dispatch failed", exc_info=True)
|
||||
|
||||
return {"session_id": sid, "name": name, "model": model, "endpoint_url": url}
|
||||
except Exception as e:
|
||||
logger.error(f"create_session failed: {e}")
|
||||
return {"error": f"Failed to create session: {e}"}
|
||||
|
||||
|
||||
async def do_list_sessions(content: str, session_id: Optional[str] = None, owner: Optional[str] = None) -> Dict:
|
||||
"""List sessions sorted by most-recently-active first.
|
||||
|
||||
Output includes a relative "last active" timestamp per row so the
|
||||
agent can answer "open my last chat" without guessing from titles.
|
||||
The most-recent session is always first in the list.
|
||||
|
||||
Content = optional filter keyword (matches session name).
|
||||
"""
|
||||
if not _session_manager:
|
||||
return {"error": "Session manager not available"}
|
||||
|
||||
keyword = content.strip().lower() if content.strip() else None
|
||||
|
||||
try:
|
||||
from core.database import SessionLocal, Session as DbSession
|
||||
from datetime import datetime, timezone
|
||||
|
||||
# Pull every session's last_accessed from the DB so we can sort
|
||||
# by recency. In-memory sessions hold name + model + msg_count;
|
||||
# the DB row holds the timestamps.
|
||||
db = SessionLocal()
|
||||
try:
|
||||
db_rows = {r.id: r for r in db.query(DbSession).all()}
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
# SECURITY: scope to the caller's sessions. Passing None returned
|
||||
# every user's sessions, which the agent tool then exposed via the
|
||||
# "list my chats" reply.
|
||||
sessions = _session_manager.get_sessions_for_user(owner)
|
||||
rows = []
|
||||
for sid, sess in sessions.items():
|
||||
if keyword and keyword not in (sess.name or "").lower():
|
||||
continue
|
||||
db_row = db_rows.get(sid)
|
||||
# Prefer last_accessed; fall back to updated_at, then created_at.
|
||||
ts = None
|
||||
if db_row:
|
||||
ts = getattr(db_row, 'last_accessed', None) or getattr(db_row, 'updated_at', None) or getattr(db_row, 'created_at', None)
|
||||
rows.append((ts, sid, sess))
|
||||
|
||||
# Sort by timestamp DESC; rows without a timestamp sink to the bottom.
|
||||
rows.sort(key=lambda r: r[0] or datetime.min, reverse=True)
|
||||
|
||||
def _rel(ts):
|
||||
if not ts:
|
||||
return 'never'
|
||||
now = datetime.utcnow()
|
||||
try:
|
||||
if ts.tzinfo is not None:
|
||||
now = datetime.now(timezone.utc)
|
||||
diff = (now - ts).total_seconds()
|
||||
except Exception:
|
||||
return 'unknown'
|
||||
if diff < 60: return 'just now'
|
||||
if diff < 3600: return f'{int(diff / 60)}m ago'
|
||||
if diff < 86400: return f'{int(diff / 3600)}h ago'
|
||||
if diff < 86400 * 7: return f'{int(diff / 86400)}d ago'
|
||||
return ts.strftime('%Y-%m-%d')
|
||||
|
||||
lines = []
|
||||
for i, (ts, sid, sess) in enumerate(rows):
|
||||
if i >= 50:
|
||||
lines.append(f"... and {len(rows) - 50} more (showing first 50)")
|
||||
break
|
||||
safe_name = (sess.name or "Untitled").replace("[", "\\[").replace("]", "\\]")
|
||||
msg_count = getattr(sess, "message_count", 0) or 0
|
||||
model = getattr(sess, "model", "unknown")
|
||||
marker = " ← most recent" if i == 0 else ""
|
||||
lines.append(f"- **[{safe_name}](#session-{sid})** (id: `{sid}`, model: {model}, {msg_count} msgs, last active {_rel(ts)}){marker}")
|
||||
|
||||
if not lines:
|
||||
return {"results": "No sessions found" + (f" matching '{keyword}'" if keyword else "") + "."}
|
||||
|
||||
return {
|
||||
"results": (
|
||||
f"Found {len(rows)} session(s), sorted most-recent first:\n"
|
||||
+ "\n".join(lines)
|
||||
+ "\n\nAssistant: when replying to the user, preserve the chat-title markdown links exactly as shown, e.g. `[Chat](#session-id)`. Do not rewrite this as a plain, non-clickable table."
|
||||
)
|
||||
}
|
||||
except Exception as e:
|
||||
logger.error(f"list_sessions failed: {e}")
|
||||
return {"error": str(e)}
|
||||
|
||||
|
||||
async def do_send_to_session(content: str, session_id: Optional[str] = None, owner: Optional[str] = None) -> Dict:
|
||||
"""Send a message to an existing session and get a response.
|
||||
|
||||
Content format:
|
||||
Line 1: session_id
|
||||
Line 2+: message
|
||||
"""
|
||||
from src.llm_core import llm_call_async
|
||||
from core.models import ChatMessage
|
||||
|
||||
if not _session_manager:
|
||||
return {"error": "Session manager not available"}
|
||||
|
||||
lines = content.strip().split("\n", 1)
|
||||
if len(lines) < 2:
|
||||
return {"error": "Need 2 lines: session_id, then message"}
|
||||
|
||||
target_sid = lines[0].strip()
|
||||
message = lines[1].strip()
|
||||
|
||||
sess = _session_manager.get_session(target_sid)
|
||||
if not sess:
|
||||
return {"error": f"Session '{target_sid}' not found"}
|
||||
|
||||
# Owner-scope: reject access to another user's session
|
||||
if owner and getattr(sess, "owner", None) and sess.owner != owner:
|
||||
return {"error": f"Session '{target_sid}' not found"}
|
||||
|
||||
if not message:
|
||||
return {"error": "No message provided"}
|
||||
|
||||
try:
|
||||
# Build context from session history
|
||||
context = sess.get_context_messages()
|
||||
context.append({"role": "user", "content": message})
|
||||
|
||||
response = await llm_call_async(
|
||||
sess.endpoint_url, sess.model, context,
|
||||
headers=sess.headers,
|
||||
timeout=AI_CHAT_TIMEOUT,
|
||||
)
|
||||
|
||||
# Save both messages to session
|
||||
sess.add_message(ChatMessage("user", message))
|
||||
sess.add_message(ChatMessage("assistant", response))
|
||||
|
||||
# Truncate for tool output
|
||||
if len(response) > 10000:
|
||||
response = response[:10000] + "\n... (truncated)"
|
||||
|
||||
return {
|
||||
"session_id": target_sid,
|
||||
"session_name": sess.name,
|
||||
"response": response,
|
||||
}
|
||||
except Exception as e:
|
||||
logger.error(f"send_to_session failed: {e}")
|
||||
return {"error": f"Failed to send to session: {e}"}
|
||||
|
||||
|
||||
async def stream_ai_tool(tool: str, content: str, session_id: Optional[str] = None, owner: Optional[str] = None):
|
||||
@@ -715,229 +287,6 @@ async def do_pipeline(content: str, session_id: Optional[str] = None, owner: Opt
|
||||
# Session management tool
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
async def do_manage_session(content: str, session_id: Optional[str] = None, owner: Optional[str] = None) -> Dict:
|
||||
"""Manage sessions: rename, archive, delete, important, truncate, fork.
|
||||
|
||||
Content format:
|
||||
Line 1: action (rename|archive|unarchive|delete|important|unimportant|truncate|fork)
|
||||
Line 2: target session_id (or "current" to use the active session)
|
||||
Line 3+: action-specific params (e.g. new name for rename, keep_count for truncate)
|
||||
"""
|
||||
if not _session_manager:
|
||||
return {"error": "Session manager not available"}
|
||||
|
||||
from src.database import SessionLocal, Session as DbSession
|
||||
|
||||
# Accept BOTH the structured JSON args the tool schema advertises
|
||||
# ({action, session_id, value}) AND the legacy line-based format
|
||||
# (line1=action, line2=session_id, line3=value). Native function-calling
|
||||
# models send JSON; fenced-block callers send lines. Previously only the
|
||||
# line format was parsed, so a model that followed the schema (JSON) got
|
||||
# "Need at least 2 lines" / "Rename needs line 3" and couldn't drive it.
|
||||
_raw = (content or "").strip()
|
||||
action = ""
|
||||
target_sid = ""
|
||||
value = None # the action param: new name (rename) / keep_count (truncate, fork)
|
||||
_list_filter = ""
|
||||
_parsed = None
|
||||
if _raw.startswith("{"):
|
||||
try:
|
||||
_parsed = json.loads(_raw)
|
||||
except Exception:
|
||||
_parsed = None
|
||||
if isinstance(_parsed, dict):
|
||||
action = str(_parsed.get("action") or "").strip().lower()
|
||||
target_sid = str(_parsed.get("session_id") or _parsed.get("session") or _parsed.get("id") or "").strip()
|
||||
_v = _parsed.get("value")
|
||||
if _v is None:
|
||||
_v = (_parsed.get("name") or _parsed.get("new_name")
|
||||
or _parsed.get("title") or _parsed.get("keep_count"))
|
||||
value = None if _v is None else str(_v).strip()
|
||||
_list_filter = str(_parsed.get("filter") or "").strip()
|
||||
else:
|
||||
lines = _raw.split("\n")
|
||||
if not lines or not lines[0].strip():
|
||||
return {"error": "Missing action (rename|archive|delete|important|truncate|fork|list|switch)"}
|
||||
action = lines[0].strip().lower()
|
||||
target_sid = lines[1].strip() if len(lines) >= 2 else ""
|
||||
value = lines[2].strip() if len(lines) >= 3 else None
|
||||
_list_filter = "\n".join(lines[1:]).strip()
|
||||
|
||||
if not action:
|
||||
return {"error": "Missing action (rename|archive|delete|important|truncate|fork|list|switch)"}
|
||||
|
||||
# `list` alias — dispatch to do_list_sessions so the agent's natural
|
||||
# first guess (every other manage_* tool has a `list` action) works.
|
||||
if action == "list":
|
||||
return await do_list_sessions(_list_filter, session_id, owner=owner)
|
||||
|
||||
if not target_sid:
|
||||
return {"error": "Need a session_id (or 'current' for the active chat)"}
|
||||
|
||||
# Allow "current" to refer to the active session
|
||||
if target_sid.lower() == "current" and session_id:
|
||||
target_sid = session_id
|
||||
|
||||
# `switch` / `open` / `select` / `view` — the agent reaches for
|
||||
# these when the user asks to "open" or "switch to" a session.
|
||||
# There's no server-side way to make the browser navigate, so we
|
||||
# just return a clickable anchor link the user can click. The
|
||||
# frontend's chat-history click delegate routes `#session-<id>`
|
||||
# to selectSession(). The agent's reply naturally embeds this
|
||||
# result so the user sees a single clickable line.
|
||||
def _session_query(db):
|
||||
query = db.query(DbSession).filter(DbSession.id == target_sid)
|
||||
if owner is not None:
|
||||
query = query.filter(DbSession.owner == owner)
|
||||
return query
|
||||
|
||||
if action in ("switch", "open", "select", "view"):
|
||||
db = SessionLocal()
|
||||
try:
|
||||
db_sess = _session_query(db).first()
|
||||
if not db_sess:
|
||||
return {"error": f"Session '{target_sid}' not found. Use list_sessions and pass the exact id it returned."}
|
||||
name = db_sess.name or target_sid
|
||||
finally:
|
||||
db.close()
|
||||
return {
|
||||
"action": action,
|
||||
"session_id": target_sid,
|
||||
"name": name,
|
||||
"results": f"[{name}](#session-{target_sid}) — click to open.",
|
||||
}
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
if action == "rename":
|
||||
if not value:
|
||||
return {"error": "rename needs a new name (the `value` arg, or line 3 in the legacy format)"}
|
||||
new_name = value
|
||||
db_sess = _session_query(db).first()
|
||||
if not db_sess:
|
||||
return {"error": f"Session '{target_sid}' not found. Use list_sessions and pass the exact id it returned."}
|
||||
db_sess.name = new_name
|
||||
db.commit()
|
||||
_session_manager.update_session_name(target_sid, new_name)
|
||||
return {"action": "rename", "session_id": target_sid, "name": new_name,
|
||||
"results": f"Session renamed to '{new_name}'"}
|
||||
|
||||
elif action == "archive":
|
||||
db_sess = _session_query(db).first()
|
||||
if not db_sess:
|
||||
return {"error": f"Session '{target_sid}' not found. Use list_sessions and pass the exact id it returned."}
|
||||
db_sess.archived = True
|
||||
db.commit()
|
||||
return {"action": "archive", "session_id": target_sid,
|
||||
"results": f"Session '{db_sess.name}' archived"}
|
||||
|
||||
elif action == "unarchive":
|
||||
db_sess = _session_query(db).first()
|
||||
if not db_sess:
|
||||
return {"error": f"Session '{target_sid}' not found. Use list_sessions and pass the exact id it returned."}
|
||||
db_sess.archived = False
|
||||
db.commit()
|
||||
return {"action": "unarchive", "session_id": target_sid,
|
||||
"results": f"Session '{db_sess.name}' unarchived"}
|
||||
|
||||
elif action == "delete":
|
||||
if target_sid == session_id:
|
||||
return {"error": "Cannot delete the current session while chatting in it. Delete other sessions first."}
|
||||
db_sess = _session_query(db).first()
|
||||
if not db_sess:
|
||||
return {"error": f"Session '{target_sid}' not found. Refusing to delete an unknown chat id; use the exact id from list_sessions."}
|
||||
if db_sess and db_sess.is_important:
|
||||
return {"error": f"Session '{db_sess.name}' is starred/favorited. Unstar it first before deleting."}
|
||||
try:
|
||||
ok = _session_manager.delete_session(target_sid)
|
||||
if not ok:
|
||||
return {"error": f"Session '{target_sid}' was not deleted because it no longer exists."}
|
||||
return {"action": "delete", "session_id": target_sid,
|
||||
"results": f"Session '{db_sess.name or target_sid}' deleted"}
|
||||
except Exception as e:
|
||||
return {"error": f"Failed to delete session: {e}"}
|
||||
|
||||
elif action in ("important", "unimportant"):
|
||||
is_important = action == "important"
|
||||
db_sess = _session_query(db).first()
|
||||
if not db_sess:
|
||||
return {"error": f"Session '{target_sid}' not found. Use list_sessions and pass the exact id it returned."}
|
||||
# Prevent AI from unstarring sessions — only the user can do that manually
|
||||
if not is_important and db_sess.is_important:
|
||||
return {"error": f"Session '{db_sess.name}' is starred by the user. Only the user can unstar sessions manually."}
|
||||
db_sess.is_important = is_important
|
||||
db.commit()
|
||||
status = "marked as important" if is_important else "unmarked as important"
|
||||
return {"action": action, "session_id": target_sid,
|
||||
"results": f"Session '{db_sess.name}' {status}"}
|
||||
|
||||
elif action == "truncate":
|
||||
db_sess = _session_query(db).first()
|
||||
if not db_sess:
|
||||
return {"error": f"Session '{target_sid}' not found. Use list_sessions and pass the exact id it returned."}
|
||||
keep_count = 10
|
||||
if value:
|
||||
try:
|
||||
keep_count = int(value)
|
||||
except ValueError:
|
||||
pass
|
||||
success = _session_manager.truncate_messages(target_sid, keep_count)
|
||||
if success:
|
||||
return {"action": "truncate", "session_id": target_sid,
|
||||
"results": f"Session truncated to last {keep_count} messages"}
|
||||
return {"error": f"Failed to truncate session '{target_sid}'"}
|
||||
|
||||
elif action == "fork":
|
||||
db_sess = _session_query(db).first()
|
||||
if not db_sess:
|
||||
return {"error": f"Session '{target_sid}' not found. Use list_sessions and pass the exact id it returned."}
|
||||
keep_count = 0 # 0 = all messages
|
||||
if value:
|
||||
try:
|
||||
keep_count = int(value)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
source = _session_manager.get_session(target_sid)
|
||||
if not source:
|
||||
return {"error": f"Session '{target_sid}' not found"}
|
||||
|
||||
new_sid = str(uuid.uuid4())[:8]
|
||||
_session_manager.create_session(
|
||||
session_id=new_sid,
|
||||
name=f"Fork: {source.name}",
|
||||
endpoint_url=source.endpoint_url,
|
||||
model=source.model,
|
||||
rag=False,
|
||||
owner=owner,
|
||||
)
|
||||
# Copy messages
|
||||
history = source.get_context_messages()
|
||||
if keep_count > 0:
|
||||
history = history[:keep_count]
|
||||
from core.models import ChatMessage as InMemoryMsg
|
||||
new_sess = _session_manager.get_session(new_sid)
|
||||
for msg in history:
|
||||
new_sess.add_message(InMemoryMsg(msg["role"], msg["content"]))
|
||||
try:
|
||||
from src.event_bus import fire_event
|
||||
fire_event("session_created", owner)
|
||||
except Exception:
|
||||
logger.debug("session_created event dispatch failed", exc_info=True)
|
||||
|
||||
return {"action": "fork", "session_id": new_sid,
|
||||
"source_session": target_sid, "messages_copied": len(history),
|
||||
"results": f"Forked session '{source.name}' -> new session {new_sid} ({len(history)} messages)"}
|
||||
|
||||
else:
|
||||
return {"error": f"Unknown action '{action}'. Use: list, switch, rename, archive, unarchive, delete, important, unimportant, truncate, fork"}
|
||||
except Exception as e:
|
||||
logger.error(f"manage_session failed: {e}")
|
||||
return {"error": str(e)}
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Memory management tool
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -1104,83 +453,6 @@ async def do_manage_memory(content: str, session_id: Optional[str] = None, owner
|
||||
return {"error": f"Unknown action '{action}'. Use: list, add, edit, delete, search"}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# List models tool
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
async def do_list_models(content: str, session_id: Optional[str] = None, owner: Optional[str] = None) -> Dict:
|
||||
"""List all available models across configured endpoints.
|
||||
|
||||
Content = optional filter keyword.
|
||||
"""
|
||||
import httpx
|
||||
from src.database import SessionLocal, ModelEndpoint
|
||||
from src.llm_core import _detect_provider, ANTHROPIC_MODELS
|
||||
from src.auth_helpers import owner_filter
|
||||
|
||||
keyword = content.strip().lower() if content.strip() else None
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
query = db.query(ModelEndpoint).filter(ModelEndpoint.is_enabled == True)
|
||||
if owner:
|
||||
query = owner_filter(query, ModelEndpoint, owner)
|
||||
endpoints = query.all()
|
||||
if not endpoints:
|
||||
return {"results": "No enabled model endpoints configured."}
|
||||
|
||||
result_lines = []
|
||||
total_models = 0
|
||||
|
||||
for ep in endpoints:
|
||||
try:
|
||||
base, api_key = resolve_endpoint_runtime(ep, owner=owner)
|
||||
except Exception:
|
||||
continue
|
||||
provider = _detect_provider(base)
|
||||
headers = build_headers(api_key, base)
|
||||
|
||||
model_ids = []
|
||||
if provider == "anthropic":
|
||||
model_ids = list(ANTHROPIC_MODELS)
|
||||
else:
|
||||
try:
|
||||
models_url = build_models_url(base)
|
||||
if models_url:
|
||||
r = httpx.get(models_url, headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
data = r.json()
|
||||
model_ids = [m.get("id") for m in (data.get("data") or []) if m.get("id")]
|
||||
if not model_ids:
|
||||
model_ids = [
|
||||
m.get("name") or m.get("model")
|
||||
for m in (data.get("models") or [])
|
||||
if m.get("name") or m.get("model")
|
||||
]
|
||||
else:
|
||||
model_ids = json.loads(ep.cached_models or "[]")
|
||||
except Exception:
|
||||
model_ids = ["(endpoint offline)"]
|
||||
|
||||
if keyword:
|
||||
model_ids = [m for m in model_ids if keyword in m.lower() or keyword in (ep.name or "").lower()]
|
||||
|
||||
if model_ids:
|
||||
result_lines.append(f"\n**{ep.name or base}** ({provider}):")
|
||||
for mid in model_ids:
|
||||
result_lines.append(f" - `{mid}`")
|
||||
total_models += 1
|
||||
|
||||
if not result_lines:
|
||||
return {"results": "No models found" + (f" matching '{keyword}'" if keyword else "") + "."}
|
||||
|
||||
header = f"Available models ({total_models} total):"
|
||||
return {"results": header + "\n".join(result_lines)}
|
||||
except Exception as e:
|
||||
logger.error(f"list_models failed: {e}")
|
||||
return {"error": str(e)}
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -1292,7 +564,7 @@ async def do_ui_control(content: str, session_id: Optional[str] = None, owner: O
|
||||
set_theme <preset> — Apply a built-in theme preset (dark, light, midnight, paper, cyberpunk, retrowave, forest, ocean, ume, copper, terminal, organs, lavender, gpt, claude, cute)
|
||||
create_theme <name> <bg> <fg> <panel> <border> <accent> [key=val ...] — Create custom theme. Optional key=val: advanced color overrides AND background effects: bgPattern=<none|dots|synapse|rain|constellations|perlin-flow|petals|sparkles|embers>, bgEffectColor=#RRGGBB, bgEffectIntensity=<num>, bgEffectSize=<num>, frosted=true|false
|
||||
open_panel <name> — Open a panel (documents, gallery, email, sessions, notes, memories, skills, settings, cookbook)
|
||||
open_email_reply <uid> [folder] [reply|reply-all|ai-reply] — Open a reply draft document for an email; does not send
|
||||
open_email_reply <uid> [folder] [reply|reply-all|ai-reply] [body text] — Open a reply draft document for an email; does not send. ALWAYS append the body text when the user told you what to say (one-shot draft); only omit body when the user just asked to "open a reply" without content.
|
||||
get_toggles — Return current toggle states (server-side knowledge)
|
||||
"""
|
||||
lines = content.strip().split("\n")
|
||||
@@ -1536,21 +808,54 @@ async def do_ui_control(content: str, session_id: Optional[str] = None, owner: O
|
||||
}
|
||||
|
||||
elif action == "open_email_reply":
|
||||
reply_parts = lines[0].strip().split()
|
||||
uid = reply_parts[1].strip() if len(reply_parts) > 1 else ""
|
||||
folder = reply_parts[2].strip() if len(reply_parts) > 2 else "INBOX"
|
||||
mode = reply_parts[3].strip().lower() if len(reply_parts) > 3 else "reply"
|
||||
# Two forms supported:
|
||||
# open_email_reply <uid> [folder] [reply|reply-all|ai-reply]
|
||||
# open_email_reply <uid> [folder] [reply|reply-all|ai-reply]
|
||||
# <body text on subsequent lines or after the mode token>
|
||||
# The body text (if any) gets pre-filled into the reply draft so the
|
||||
# agent can compose-and-open in one tool call instead of opening an
|
||||
# empty draft and leaving the user to wonder what happened.
|
||||
first_line = lines[0].strip()
|
||||
parts = first_line.split(maxsplit=4)
|
||||
uid = parts[1].strip() if len(parts) > 1 else ""
|
||||
folder = parts[2].strip() if len(parts) > 2 else "INBOX"
|
||||
mode = parts[3].strip().lower() if len(parts) > 3 else "reply"
|
||||
# Body: everything on the first line after the mode token, plus any
|
||||
# subsequent lines. Allows multi-line bodies.
|
||||
inline_body = parts[4] if len(parts) > 4 else ""
|
||||
rest_lines = "\n".join(lines[1:]).strip() if len(lines) > 1 else ""
|
||||
body = (inline_body + ("\n" + rest_lines if rest_lines else "")).strip()
|
||||
if not uid:
|
||||
return {"error": "open_email_reply needs: open_email_reply <uid> [folder] [reply|reply-all|ai-reply]"}
|
||||
return {"error": "open_email_reply needs: open_email_reply <uid> [folder] [reply|reply-all|ai-reply] [body text]"}
|
||||
if mode not in ("reply", "reply-all", "ai-reply"):
|
||||
mode = "reply"
|
||||
return {
|
||||
# Body is REQUIRED for the agent path. Opening an empty draft is what
|
||||
# users do by clicking the Reply button — they don't ask the agent
|
||||
# for that. Every agent invocation of open_email_reply MUST include
|
||||
# the body. Reject empty so the agent retries with the content the
|
||||
# user asked for. Exception: ai-reply mode triggers the existing
|
||||
# AI-Reply path on the frontend which generates its own body.
|
||||
if not body and mode != "ai-reply":
|
||||
return {
|
||||
"error": (
|
||||
"open_email_reply called without body. The agent path REQUIRES a body — "
|
||||
"opening an empty draft is the wrong response when the user asked you to write. "
|
||||
"Re-call with the reply text included: "
|
||||
f"`open_email_reply {uid} {folder or 'INBOX'} {mode} <your reply text here>`. "
|
||||
"Compose the reply now based on the open email's content and the user's request, "
|
||||
"then call this tool again with the body. Do NOT call create_document instead."
|
||||
),
|
||||
}
|
||||
result = {
|
||||
"ui_event": "open_email_reply",
|
||||
"uid": uid,
|
||||
"folder": folder or "INBOX",
|
||||
"mode": mode,
|
||||
"results": f"Opening reply draft for email UID {uid}",
|
||||
"results": f"Opening reply draft for email UID {uid}" + (" with pre-filled body" if body else ""),
|
||||
}
|
||||
if body:
|
||||
result["body"] = body
|
||||
return result
|
||||
|
||||
elif action == "get_toggles":
|
||||
return {
|
||||
@@ -1580,7 +885,9 @@ async def do_generate_image(content: str, session_id: Optional[str] = None, owne
|
||||
"""
|
||||
import base64
|
||||
import httpx
|
||||
import os
|
||||
from pathlib import Path
|
||||
from src.url_safety import check_outbound_url
|
||||
|
||||
lines = content.strip().split("\n")
|
||||
prompt = lines[0].strip() if lines else ""
|
||||
@@ -1746,8 +1053,15 @@ async def do_generate_image(content: str, session_id: Optional[str] = None, owne
|
||||
|
||||
elif img.get("url"):
|
||||
# Download external URL and save locally (DALL-E returns temp URLs)
|
||||
result_url = img["url"]
|
||||
ok, reason = check_outbound_url(
|
||||
result_url,
|
||||
block_private=os.getenv("IMAGE_BLOCK_PRIVATE_IPS", "false").lower() == "true",
|
||||
)
|
||||
if not ok:
|
||||
return {"error": f"Image API returned unsafe image URL: {reason}"}
|
||||
try:
|
||||
dl_resp = httpx.get(img["url"], timeout=60)
|
||||
dl_resp = httpx.get(result_url, timeout=60)
|
||||
if dl_resp.status_code == 200:
|
||||
img_dir = Path(GENERATED_IMAGES_DIR)
|
||||
img_dir.mkdir(parents=True, exist_ok=True)
|
||||
@@ -1757,10 +1071,10 @@ async def do_generate_image(content: str, session_id: Optional[str] = None, owne
|
||||
image_url = f"/api/generated-image/{filename}"
|
||||
image_id = _save_to_gallery(filename)
|
||||
else:
|
||||
image_url = img["url"] # fallback to external URL
|
||||
image_url = result_url # fallback to external URL
|
||||
except Exception as _dl_e:
|
||||
logger.warning(f"Failed to download DALL-E image: {_dl_e}")
|
||||
image_url = img["url"] # fallback to external URL
|
||||
image_url = result_url # fallback to external URL
|
||||
else:
|
||||
return {"error": "Image API returned unexpected format (no b64_json or url)"}
|
||||
|
||||
@@ -1789,55 +1103,20 @@ async def dispatch_ai_tool(
|
||||
) -> Tuple[str, Dict]:
|
||||
"""Dispatch an AI interaction tool. Returns (description, result_dict)."""
|
||||
|
||||
if tool == "chat_with_model":
|
||||
model_spec = content.split("\n")[0].strip()[:60]
|
||||
desc = f"chat_with_model: {model_spec}"
|
||||
result = await do_chat_with_model(content, session_id, owner=owner)
|
||||
|
||||
elif tool == "create_session":
|
||||
name = content.split("\n")[0].strip()[:60]
|
||||
desc = f"create_session: {name}"
|
||||
result = await do_create_session(content, session_id, owner=owner)
|
||||
|
||||
elif tool == "list_sessions":
|
||||
keyword = content.strip()[:40]
|
||||
desc = f"list_sessions{': ' + keyword if keyword else ''}"
|
||||
result = await do_list_sessions(content, session_id, owner=owner)
|
||||
|
||||
elif tool == "send_to_session":
|
||||
sid = content.split("\n")[0].strip()[:20]
|
||||
desc = f"send_to_session: {sid}"
|
||||
result = await do_send_to_session(content, session_id, owner=owner)
|
||||
|
||||
elif tool == "pipeline":
|
||||
if tool == "pipeline":
|
||||
desc = "pipeline: running steps"
|
||||
result = await do_pipeline(content, session_id, owner=owner)
|
||||
|
||||
elif tool == "manage_session":
|
||||
action = content.split("\n")[0].strip()[:40]
|
||||
desc = f"manage_session: {action}"
|
||||
result = await do_manage_session(content, session_id, owner=owner)
|
||||
|
||||
elif tool == "manage_memory":
|
||||
action = content.split("\n")[0].strip()[:40]
|
||||
desc = f"manage_memory: {action}"
|
||||
result = await do_manage_memory(content, session_id, owner=owner)
|
||||
|
||||
elif tool == "list_models":
|
||||
keyword = content.strip()[:40]
|
||||
desc = f"list_models{': ' + keyword if keyword else ''}"
|
||||
result = await do_list_models(content, session_id, owner=owner)
|
||||
|
||||
elif tool == "ui_control":
|
||||
action = content.split("\n")[0].strip()[:60]
|
||||
desc = f"ui_control: {action}"
|
||||
result = await do_ui_control(content, session_id, owner=owner)
|
||||
|
||||
elif tool == "ask_teacher":
|
||||
problem = content.split("\n", 1)[-1].strip()[:60]
|
||||
desc = f"ask_teacher: {problem}"
|
||||
result = await do_ask_teacher(content, session_id, owner=owner)
|
||||
|
||||
else:
|
||||
desc = f"unknown ai tool: {tool}"
|
||||
result = {"error": f"Unknown AI interaction tool: {tool}"}
|
||||
|
||||
@@ -263,10 +263,32 @@ def list_for_session(session_id: str) -> List[Dict[str, Any]]:
|
||||
return [r for r in refresh().values() if r.get("session_id") == session_id]
|
||||
|
||||
|
||||
def kill(job_id: str) -> Optional[Dict[str, Any]]:
|
||||
"""Terminate a running job's process tree and mark it killed. Returns the
|
||||
updated record, or None if the id is unknown. Idempotent: a job that already
|
||||
finished is returned unchanged. Sets followed_up so the monitor does not also
|
||||
fire an auto-continue for a job the agent deliberately stopped."""
|
||||
jobs = _load()
|
||||
rec = jobs.get(job_id)
|
||||
if rec is None:
|
||||
return None
|
||||
if rec.get("status") == "running":
|
||||
_kill(rec.get("pid"))
|
||||
rec["status"] = "failed"
|
||||
rec["exit_code"] = -1
|
||||
rec["ended_at"] = time.time()
|
||||
rec["killed"] = True
|
||||
rec["followed_up"] = True
|
||||
_save(jobs)
|
||||
return rec
|
||||
|
||||
|
||||
def result_text(rec: Dict[str, Any]) -> str:
|
||||
"""Human/agent-readable summary of a finished job, for the follow-up."""
|
||||
out = _read_output(rec)
|
||||
if rec.get("timed_out"):
|
||||
if rec.get("killed"):
|
||||
head = "Background job was killed."
|
||||
elif rec.get("timed_out"):
|
||||
head = f"Background job timed out after {rec.get('max_runtime_s')}s."
|
||||
elif rec.get("died"):
|
||||
head = "Background job process died unexpectedly (no exit code)."
|
||||
|
||||
@@ -14,6 +14,7 @@ import subprocess
|
||||
import sys
|
||||
|
||||
from core.platform_compat import IS_WINDOWS, which_tool
|
||||
from src.runtime_paths import get_app_root
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -81,7 +82,7 @@ _BUILTIN_NPX_SERVERS = {
|
||||
"name": "Built-in: Browser",
|
||||
"command": "npx",
|
||||
"args": ["-y", "@playwright/mcp@latest", "--headless", "--caps", "vision"],
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
# Global flag to disable MCP if there are compatibility issues
|
||||
@@ -94,7 +95,7 @@ async def register_builtin_servers(mcp_manager):
|
||||
logger.info("Built-in MCP servers disabled via ODYSSEUS_DISABLE_MCP")
|
||||
return
|
||||
|
||||
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
base_dir = get_app_root()
|
||||
python = sys.executable
|
||||
|
||||
async def _connect_python_server(server_id: str, script_path: str, name: str):
|
||||
|
||||
@@ -5,6 +5,7 @@ from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
from pydantic import Field, field_validator
|
||||
|
||||
from src.constants import DATA_DIR as _DATA_DIR_CONST
|
||||
from src.runtime_paths import get_app_root
|
||||
|
||||
# Cross-platform OS flag, exposed here so callers can `from src.config import
|
||||
# IS_WINDOWS`. Defined locally (a trivial `os.name == "nt"`) rather than imported
|
||||
@@ -19,7 +20,7 @@ IS_WINDOWS = os.name == "nt"
|
||||
class DataConfig(BaseSettings):
|
||||
"""Configuration for data storage and file handling."""
|
||||
# Base directory
|
||||
base_dir: Path = Field(default=Path(__file__).parent.parent, description="Base directory for the application")
|
||||
base_dir: Path = Field(default=Path(get_app_root()), description="Base directory for the application")
|
||||
|
||||
# Data paths
|
||||
data_dir: Path = Field(default=Path(_DATA_DIR_CONST), description="Main data directory")
|
||||
@@ -138,7 +139,7 @@ class AppConfig(BaseSettings):
|
||||
if isinstance(v, dict) and "base_dir" in v:
|
||||
base_dir = v["base_dir"]
|
||||
else:
|
||||
base_dir = Path(__file__).parent.parent
|
||||
base_dir = Path(get_app_root())
|
||||
|
||||
# Convert string paths to Path objects relative to base_dir
|
||||
data_dir = Path(_DATA_DIR_CONST)
|
||||
|
||||
@@ -2,12 +2,14 @@
|
||||
"""Application-wide constants and configuration values."""
|
||||
import os
|
||||
|
||||
from src.runtime_paths import get_app_root, get_default_data_dir
|
||||
|
||||
APP_VERSION = "1.0.0"
|
||||
|
||||
# Base paths
|
||||
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + "/"
|
||||
BASE_DIR = os.path.join(get_app_root(), "")
|
||||
STATIC_DIR = os.path.join(BASE_DIR, "static")
|
||||
DATA_DIR = os.getenv("ODYSSEUS_DATA_DIR", os.path.join(BASE_DIR, "data"))
|
||||
DATA_DIR = os.getenv("ODYSSEUS_DATA_DIR", get_default_data_dir())
|
||||
|
||||
# Data file paths
|
||||
# Single source of truth: every persisted file/dir lives under DATA_DIR, which
|
||||
@@ -55,7 +57,13 @@ MEMORY_VECTORS_DIR = os.path.join(DATA_DIR, "memory_vectors")
|
||||
|
||||
# Paths with an intentional dedicated env override, defaulting under DATA_DIR.
|
||||
MAIL_ATTACHMENTS_DIR = os.getenv("ODYSSEUS_MAIL_ATTACHMENTS_DIR", os.path.join(DATA_DIR, "mail-attachments"))
|
||||
FASTEMBED_CACHE_DIR = os.getenv("FASTEMBED_CACHE_PATH", os.path.join(DATA_DIR, "fastembed_cache"))
|
||||
# `or` (not os.getenv's default arg) so a PRESENT-but-EMPTY value falls back to
|
||||
# the default. docker-compose.yml injects `FASTEMBED_CACHE_PATH=${FASTEMBED_CACHE_PATH:-}`,
|
||||
# which sets the var to "" when the host hasn't defined it. os.getenv(name, default)
|
||||
# only returns the default when the var is ABSENT, so the empty string would win →
|
||||
# os.makedirs("") raises [Errno 2] No such file or directory: '' → FastEmbed fails to
|
||||
# init and all vector features (RAG, semantic memory, tool index) silently degrade.
|
||||
FASTEMBED_CACHE_DIR = os.getenv("FASTEMBED_CACHE_PATH") or os.path.join(DATA_DIR, "fastembed_cache")
|
||||
|
||||
# Agent tool output limits (single source of truth — imported by tool_execution.py,
|
||||
# tool_implementations.py, agent_tools.py, and any other module that needs them)
|
||||
@@ -63,11 +71,26 @@ MAX_OUTPUT_CHARS = 10_000 # cap for bash/python/web_search/web_fetch outpu
|
||||
MAX_READ_CHARS = 20_000 # cap for read_file / document preview
|
||||
MAX_DIFF_LINES = 400 # cap for edit_file unified-diff display
|
||||
|
||||
# web_fetch response-size policy (#3812). MAX_OUTPUT_CHARS above only trims
|
||||
# what the agent SEES; these caps bound what the server downloads, parses,
|
||||
# and writes to the content cache. The soft cap is the default download
|
||||
# budget; the agent can raise it per call (full/max_bytes) but never past
|
||||
# the hard cap, so a model can't decide to pull a multi-GB file.
|
||||
WEB_FETCH_SOFT_MAX_BYTES = 2_000_000 # default download budget (2 MB)
|
||||
WEB_FETCH_HARD_MAX_BYTES = 20_000_000 # absolute ceiling, even with override (20 MB)
|
||||
|
||||
# API Configuration
|
||||
MAX_CONTEXT_MESSAGES = 90
|
||||
REQUEST_TIMEOUT = 20
|
||||
OPENAI_COMPAT_PATH = "/v1/chat/completions"
|
||||
|
||||
# Outbound UA for web_fetch / web_search scraping; common desktop UA so pages serve normal HTML.
|
||||
WEB_FETCH_USER_AGENT = os.environ.get(
|
||||
"WEB_FETCH_USER_AGENT",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"(KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36",
|
||||
)
|
||||
|
||||
# Environment variables with defaults
|
||||
DEFAULT_HOST = os.getenv("LLM_HOST", "localhost")
|
||||
LLM_HOSTS = [h.strip() for h in os.getenv("LLM_HOSTS", "").split(",") if h.strip()]
|
||||
@@ -79,6 +102,9 @@ SEARXNG_INSTANCE = os.getenv("SEARXNG_INSTANCE", "http://localhost:8080")
|
||||
CLEANUP_ENABLED = os.getenv("CLEANUP_ENABLED", "True").lower() == "true"
|
||||
CLEANUP_INTERVAL_HOURS = int(os.getenv("CLEANUP_INTERVAL_HOURS", "24"))
|
||||
|
||||
# Auth policy
|
||||
PASSWORD_MIN_LENGTH = 8
|
||||
|
||||
# Default parameters
|
||||
DEFAULT_TEMPERATURE = 1.0
|
||||
DEFAULT_MAX_TOKENS = 0
|
||||
|
||||
@@ -161,11 +161,13 @@ async def _tick() -> None:
|
||||
# Re-read state once before writing so we capture any updates from
|
||||
# concurrent UI syncs.
|
||||
stopped_any = False
|
||||
successfully_stopped_sids = set()
|
||||
for sid, host, port in to_stop:
|
||||
ok = await _stop_serve(sid, host, port)
|
||||
logger.info(f"cookbook_serve_lifecycle: stop {sid} (host={host or 'local'}): {'ok' if ok else 'failed'}")
|
||||
if ok:
|
||||
stopped_any = True
|
||||
successfully_stopped_sids.add(sid)
|
||||
# Drop the auto-registered endpoint so the model picker and
|
||||
# the chat router don't keep pointing at a dead server.
|
||||
for t in tasks:
|
||||
@@ -188,12 +190,11 @@ async def _tick() -> None:
|
||||
except Exception:
|
||||
fresh = state
|
||||
fresh_tasks = tasks
|
||||
stopped_sids = {sid for sid, _, _ in to_stop}
|
||||
for ft in fresh_tasks:
|
||||
if not isinstance(ft, dict):
|
||||
continue
|
||||
ft_sid = ft.get("sessionId") or ft.get("id")
|
||||
if ft_sid in stopped_sids:
|
||||
if ft_sid in successfully_stopped_sids:
|
||||
ft["status"] = "stopped"
|
||||
ft["_scheduledStopAtMs"] = None
|
||||
ft["_lastStatusFlipAt"] = now_ms
|
||||
|
||||
@@ -199,11 +199,20 @@ def _fit_inline_attachment_text(
|
||||
return text[:remaining] + marker, 0
|
||||
|
||||
|
||||
def _process_office_document(path: str, display_name: str) -> str:
|
||||
def _process_office_document(
|
||||
path: str,
|
||||
display_name: str,
|
||||
session_id: str | None = None,
|
||||
auto_opened_docs: list[Dict[str, Any]] | None = None,
|
||||
owner: str | None = None,
|
||||
) -> str:
|
||||
"""Extract an Office/EPUB document to Markdown via the optional markitdown dep.
|
||||
|
||||
Falls back to a friendly banner when markitdown is unavailable or finds no
|
||||
text, so a missing optional dependency never breaks the chat path.
|
||||
text, so a missing optional dependency never breaks the chat path. When a
|
||||
session_id is provided AND the extraction succeeded, the FULL text is also
|
||||
saved as a Document so the agent can page through it via
|
||||
`manage_documents action=read offset=…` after the inline copy is capped.
|
||||
"""
|
||||
from src.markitdown_runtime import (
|
||||
is_markitdown_format,
|
||||
@@ -218,6 +227,46 @@ def _process_office_document(path: str, display_name: str) -> str:
|
||||
if markdown and markdown.strip():
|
||||
title = os.path.splitext(os.path.basename(path))[0]
|
||||
body, marker = _truncate_inline(markdown)
|
||||
|
||||
# Persist the full extracted text as a Document. The agent's existing
|
||||
# manage_documents tool can then read past the inline cap with offset.
|
||||
doc_id = None
|
||||
if session_id:
|
||||
try:
|
||||
from src.office_doc import create_office_document
|
||||
doc_id = create_office_document(
|
||||
session_id=session_id,
|
||||
upload_id=os.path.basename(path),
|
||||
title=title,
|
||||
body_text=markdown,
|
||||
)
|
||||
if doc_id and auto_opened_docs is not None:
|
||||
from src.database import SessionLocal, Document
|
||||
_db = SessionLocal()
|
||||
try:
|
||||
_d = _db.query(Document).filter(Document.id == doc_id).first()
|
||||
if _d:
|
||||
auto_opened_docs.append({
|
||||
"doc_id": _d.id,
|
||||
"title": _d.title,
|
||||
"language": _d.language,
|
||||
"content": _d.current_content,
|
||||
"version": _d.version_count,
|
||||
})
|
||||
finally:
|
||||
_db.close()
|
||||
except Exception as e:
|
||||
logger.warning("Office auto-doc creation failed for %s: %s", path, e)
|
||||
|
||||
# Upgrade the truncation marker with a hint pointing at the full doc so
|
||||
# the agent knows it can read the rest.
|
||||
if doc_id and marker:
|
||||
marker = (
|
||||
f"\n[…truncated for inline context — full {len(markdown):,} chars "
|
||||
f"saved as document `{doc_id}`. Use `manage_documents` with "
|
||||
f"action=read, document_id={doc_id}, offset=<N> to page through.]"
|
||||
)
|
||||
|
||||
return f"\n\n[Document content — {title}]:\n{body}{marker}"
|
||||
|
||||
# No content: tell the user whether to install the optional dep or whether
|
||||
@@ -521,7 +570,13 @@ def build_user_content(
|
||||
elif mime.startswith("text/") or _is_text_file(path):
|
||||
extracted_text = _process_text_file(path)
|
||||
else:
|
||||
extracted_text = _process_office_document(path, display_name)
|
||||
extracted_text = _process_office_document(
|
||||
path,
|
||||
display_name,
|
||||
session_id=session_id,
|
||||
auto_opened_docs=auto_opened_docs,
|
||||
owner=owner,
|
||||
)
|
||||
|
||||
extracted_text, inline_attachment_remaining = _fit_inline_attachment_text(
|
||||
extracted_text,
|
||||
|
||||
@@ -31,6 +31,8 @@ import numpy as np
|
||||
import httpx
|
||||
from typing import List, Optional
|
||||
|
||||
from src.runtime_paths import get_app_root
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_DEFAULT_MODEL = "all-minilm:l6-v2"
|
||||
|
||||
@@ -161,6 +161,32 @@ def normalize_base(url: str) -> str:
|
||||
return url
|
||||
|
||||
|
||||
def _validated_endpoint_base(url: str) -> str:
|
||||
"""Return a base URL that is safe for endpoint path appends."""
|
||||
base = (url or "").strip().rstrip("/")
|
||||
if "?" in base or "#" in base:
|
||||
raise ValueError("Endpoint base URL must not include query or fragment")
|
||||
return urlunparse(urlparse(base)._replace(query="", fragment="")).rstrip("/")
|
||||
|
||||
|
||||
def _prepare_endpoint_base(base: str) -> str:
|
||||
base = _validated_endpoint_base(normalize_base(base))
|
||||
return _validated_endpoint_base(normalize_base(resolve_url(base)))
|
||||
|
||||
|
||||
def _append_endpoint_path(base: str, suffix: str) -> str:
|
||||
parsed = urlparse(base)
|
||||
current = (parsed.path or "").rstrip("/")
|
||||
extra = "/" + suffix.lstrip("/")
|
||||
path = f"{current}{extra}" if current else extra
|
||||
return urlunparse(parsed._replace(path=path, query="", fragment=""))
|
||||
|
||||
|
||||
def _pathless_host(base: str, host: str) -> bool:
|
||||
parsed = urlparse(base)
|
||||
return (parsed.hostname or "").lower() == host and not (parsed.path or "").strip("/")
|
||||
|
||||
|
||||
def _anthropic_api_root(base: str) -> str:
|
||||
"""Return Anthropic's API root, preserving /v1 for OpenAI-compatible APIs elsewhere."""
|
||||
base = (base or "").strip().rstrip("/")
|
||||
@@ -171,15 +197,17 @@ def _anthropic_api_root(base: str) -> str:
|
||||
|
||||
def build_chat_url(base: str) -> str:
|
||||
"""Return the correct chat endpoint URL for a given base."""
|
||||
base = resolve_url(base)
|
||||
base = _prepare_endpoint_base(base)
|
||||
provider = _detect_provider(base)
|
||||
if provider == "anthropic":
|
||||
return _anthropic_api_root(base) + "/v1/messages"
|
||||
return _append_endpoint_path(_anthropic_api_root(base), "/v1/messages")
|
||||
if provider == "ollama":
|
||||
return _ollama_api_root(base) + "/chat"
|
||||
return _append_endpoint_path(_ollama_api_root(base), "/chat")
|
||||
if provider == "chatgpt-subscription":
|
||||
return base.rstrip("/") + "/responses"
|
||||
return base + "/chat/completions"
|
||||
return _append_endpoint_path(base, "/responses")
|
||||
if _pathless_host(base, "api.openai.com"):
|
||||
base = _append_endpoint_path(base, "/v1")
|
||||
return _append_endpoint_path(base, "/chat/completions")
|
||||
|
||||
|
||||
def build_models_url(base: str) -> Optional[str]:
|
||||
@@ -193,21 +221,25 @@ def build_models_url(base: str) -> Optional[str]:
|
||||
untouched (so custom prefixes like ``/openai`` or ``/api/openai/v1`` keep
|
||||
their semantics).
|
||||
"""
|
||||
base = normalize_base(resolve_url(base))
|
||||
base = _prepare_endpoint_base(base)
|
||||
provider = _detect_provider(base)
|
||||
if provider == "anthropic":
|
||||
return _anthropic_api_root(base) + "/v1/models"
|
||||
return _append_endpoint_path(_anthropic_api_root(base), "/v1/models")
|
||||
if provider == "ollama":
|
||||
return _ollama_api_root(base) + "/tags"
|
||||
return _append_endpoint_path(_ollama_api_root(base), "/tags")
|
||||
if provider == "chatgpt-subscription":
|
||||
return None
|
||||
# Generic OpenAI-compatible fallback: ensure the path lands on /v1/models
|
||||
# when the user omitted a path entirely. If a non-empty path is already
|
||||
# present (e.g. /openai, /api/openai/v1, /v1), trust the caller — the
|
||||
# /models suffix is appended as-is and the caller's prefix is preserved.
|
||||
if not urlparse(base).path:
|
||||
base = base + "/v1"
|
||||
return base + "/models"
|
||||
# Generic OpenAI-compatible fallback: local model servers with no explicit
|
||||
# path conventionally expose `/v1/models` (LM Studio, llama.cpp, vLLM).
|
||||
# For non-local unknown hosts, do not invent `/v1`; append `/models` to the
|
||||
# caller's base so look-alike provider hosts stay generic.
|
||||
parsed = urlparse(base)
|
||||
host = (parsed.hostname or "").lower()
|
||||
is_local = host in {"localhost", "127.0.0.1", "::1", "host.docker.internal"}
|
||||
uses_v1_models_by_default = is_local or host in {"api.deepseek.com", "api.openai.com"}
|
||||
if not parsed.path and uses_v1_models_by_default:
|
||||
base = _append_endpoint_path(base, "/v1")
|
||||
return _append_endpoint_path(base, "/models")
|
||||
|
||||
|
||||
def build_headers(api_key: Optional[str], base: str) -> Dict[str, str]:
|
||||
|
||||
@@ -4,6 +4,7 @@ import uuid
|
||||
import logging
|
||||
import re
|
||||
from typing import Dict, List, Optional, Any
|
||||
from urllib.parse import urljoin, urlparse, urlunparse
|
||||
|
||||
import httpx
|
||||
from fastapi import HTTPException
|
||||
@@ -202,6 +203,22 @@ def mask_integration_secret(integration: Dict[str, Any]) -> Dict[str, Any]:
|
||||
return safe
|
||||
|
||||
|
||||
def _normalize_integration_base_url(base_url: Any) -> str:
|
||||
if not isinstance(base_url, str) or not base_url.strip():
|
||||
raise ValueError("Integration base URL is required")
|
||||
cleaned = base_url.strip().rstrip("/")
|
||||
if "?" in cleaned or "#" in cleaned:
|
||||
raise ValueError("Integration base URL must not include query or fragment")
|
||||
parsed = urlparse(cleaned)
|
||||
if parsed.scheme.lower() not in ("http", "https") or not parsed.hostname:
|
||||
raise ValueError("Integration base URL must be an HTTP(S) URL")
|
||||
return urlunparse(parsed._replace(scheme=parsed.scheme.lower(), query="", fragment="")).rstrip("/")
|
||||
|
||||
|
||||
def _join_integration_url(base_url: str, path: str) -> str:
|
||||
return urljoin(base_url.rstrip("/") + "/", path.lstrip("/"))
|
||||
|
||||
|
||||
def load_integrations() -> List[Dict[str, Any]]:
|
||||
"""Load all integrations from disk with secrets decrypted for runtime use."""
|
||||
if not os.path.exists(DATA_FILE):
|
||||
@@ -261,8 +278,10 @@ def add_integration(data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
|
||||
if not isinstance(integration.get("name"), str) or not integration["name"].strip():
|
||||
raise HTTPException(400, "Integration name is required")
|
||||
if not isinstance(integration.get("base_url"), str) or not integration["base_url"].strip():
|
||||
raise HTTPException(400, "Integration base URL is required")
|
||||
try:
|
||||
integration["base_url"] = _normalize_integration_base_url(integration.get("base_url"))
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, str(exc)) from exc
|
||||
|
||||
integrations = load_integrations()
|
||||
integrations.append(integration)
|
||||
@@ -272,10 +291,14 @@ def add_integration(data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
|
||||
def update_integration(integration_id: str, data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
||||
"""Update fields on an existing integration. Returns updated integration or None."""
|
||||
data = dict(data)
|
||||
if "name" in data and (not isinstance(data["name"], str) or not data["name"].strip()):
|
||||
raise HTTPException(400, "Integration name is required")
|
||||
if "base_url" in data and (not isinstance(data["base_url"], str) or not data["base_url"].strip()):
|
||||
raise HTTPException(400, "Integration base URL is required")
|
||||
if "base_url" in data:
|
||||
try:
|
||||
data["base_url"] = _normalize_integration_base_url(data["base_url"])
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, str(exc)) from exc
|
||||
|
||||
integrations = load_integrations()
|
||||
for item in integrations:
|
||||
@@ -341,9 +364,10 @@ async def execute_api_call(
|
||||
if not integration.get("enabled", True):
|
||||
return {"error": f"Integration '{integration.get('name')}' is disabled", "exit_code": 1}
|
||||
|
||||
base_url = integration.get("base_url", "").rstrip("/")
|
||||
if not base_url:
|
||||
return {"error": "Integration has no base_url configured", "exit_code": 1}
|
||||
try:
|
||||
base_url = _normalize_integration_base_url(integration.get("base_url", ""))
|
||||
except ValueError as exc:
|
||||
return {"error": str(exc), "exit_code": 1}
|
||||
|
||||
# Strip common API path suffixes users might accidentally include
|
||||
# (e.g. "http://host/v1/" → "http://host"). The integration's preset
|
||||
@@ -366,7 +390,10 @@ async def execute_api_call(
|
||||
if re.search(r"^https?://", path) or "://" in path:
|
||||
return {"error": "Path must not contain a protocol scheme", "exit_code": 1}
|
||||
|
||||
url = base_url + path
|
||||
if "#" in path:
|
||||
return {"error": "Path must not contain a fragment", "exit_code": 1}
|
||||
|
||||
url = _join_integration_url(base_url, path)
|
||||
method = method.upper()
|
||||
|
||||
# Build headers
|
||||
|
||||
@@ -87,7 +87,7 @@ _host_health_lock = threading.Lock()
|
||||
_model_activity: Dict[str, float] = {}
|
||||
|
||||
_HARMONY_MARKER_RE = re.compile(
|
||||
r"<\|channel\|>(analysis|final)"
|
||||
r"<\|channel\|>(analysis|commentary|final)"
|
||||
r"|<\|start\|>(?:assistant|system|user|tool)?"
|
||||
r"|<\|message\|>"
|
||||
r"|<\|end\|>"
|
||||
@@ -96,6 +96,7 @@ _HARMONY_MARKER_RE = re.compile(
|
||||
)
|
||||
_HARMONY_MARKERS = (
|
||||
"<|channel|>analysis",
|
||||
"<|channel|>commentary",
|
||||
"<|channel|>final",
|
||||
"<|start|>assistant",
|
||||
"<|start|>system",
|
||||
@@ -145,7 +146,10 @@ class _HarmonyStreamRouter:
|
||||
out.append((text, False))
|
||||
return
|
||||
if self._in_message:
|
||||
out.append((text, self._channel == "analysis"))
|
||||
# analysis + commentary (tool-call preambles / function-arg bodies)
|
||||
# are internal, not user-facing — route them to thinking so they
|
||||
# don't leak into the visible answer; only `final` is visible.
|
||||
out.append((text, self._channel in ("analysis", "commentary")))
|
||||
|
||||
def _handle_marker(self, match: re.Match[str]) -> None:
|
||||
marker = match.group(0)
|
||||
@@ -283,7 +287,8 @@ def _is_ollama_native_url(url: str) -> bool:
|
||||
"""Return True for native Ollama API URLs, including Ollama Cloud."""
|
||||
try:
|
||||
parsed = urlparse(url or "")
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
logger.warning("Failed to parse URL for Ollama detection", exc_info=e)
|
||||
return False
|
||||
host = parsed.hostname or ""
|
||||
path = (parsed.path or "").rstrip("/")
|
||||
@@ -1345,8 +1350,8 @@ def list_model_ids(
|
||||
r = httpx.get(root + "/api/tags", timeout=timeout)
|
||||
r.raise_for_status()
|
||||
return [m.get("name") or m.get("model") for m in (r.json().get("models") or []) if m.get("name") or m.get("model")]
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
logger.warning("Failed to fetch model list from configured endpoint", exc_info=e)
|
||||
return []
|
||||
|
||||
def normalize_model_id(
|
||||
|
||||
@@ -40,15 +40,59 @@ def load_markitdown():
|
||||
return MarkItDown
|
||||
|
||||
|
||||
def _extract_docx_native(path: str) -> str | None:
|
||||
"""Pure-Python .docx text extractor — no external deps.
|
||||
|
||||
A .docx file is just a zip of XML. The body prose lives in <w:t> runs
|
||||
inside <w:p> paragraphs. Iterating with ElementTree (rather than
|
||||
re.findall) keeps paragraph breaks intact and lets the XML parser handle
|
||||
namespaces + entity unescaping. Loses tables, footnotes, images and
|
||||
list bullets — keeps ~95% of "summarize this doc" content, which is the
|
||||
case people hit when markitdown isn't installed.
|
||||
"""
|
||||
import zipfile
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
ns = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"
|
||||
try:
|
||||
with zipfile.ZipFile(path) as z:
|
||||
xml_bytes = z.read("word/document.xml")
|
||||
except (zipfile.BadZipFile, KeyError, OSError):
|
||||
return None
|
||||
try:
|
||||
root = ET.fromstring(xml_bytes)
|
||||
except ET.ParseError:
|
||||
return None
|
||||
paragraphs: list[str] = []
|
||||
for para in root.iter(f"{ns}p"):
|
||||
runs = [t.text or "" for t in para.iter(f"{ns}t")]
|
||||
line = "".join(runs).strip()
|
||||
if line:
|
||||
paragraphs.append(line)
|
||||
return "\n\n".join(paragraphs) if paragraphs else None
|
||||
|
||||
|
||||
def convert_to_markdown(path: str) -> str | None:
|
||||
"""Convert a document to Markdown text via markitdown.
|
||||
|
||||
Returns the extracted Markdown, or ``None`` if markitdown is unavailable or
|
||||
the conversion fails — callers degrade gracefully rather than erroring.
|
||||
|
||||
Fallback: when markitdown isn't installed and the file is a .docx, run
|
||||
the bundled pure-Python extractor so the most common case (Word docs)
|
||||
works out of the box. Other Office/EPUB formats still need markitdown.
|
||||
"""
|
||||
try:
|
||||
markitdown_cls = load_markitdown()
|
||||
except RuntimeError:
|
||||
if isinstance(path, str) and path.lower().endswith(".docx"):
|
||||
text = _extract_docx_native(path)
|
||||
if text:
|
||||
logger.info(
|
||||
"markitdown not installed — used native .docx extractor for %s",
|
||||
path,
|
||||
)
|
||||
return text
|
||||
logger.warning("markitdown not installed; cannot extract %s", path)
|
||||
return None
|
||||
try:
|
||||
|
||||
@@ -11,6 +11,8 @@ import os
|
||||
import re
|
||||
from typing import Any, Dict, List, Optional, Set, Tuple
|
||||
|
||||
from src.runtime_paths import get_app_root
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def _format_mcp_connection_error(name: str, command: str = "", args: Optional[List[str]] = None, error: Exception = None) -> str:
|
||||
@@ -508,7 +510,7 @@ class McpManager:
|
||||
return False
|
||||
|
||||
script_rel, name = _BUILTIN_SERVERS[server_id]
|
||||
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
base_dir = get_app_root()
|
||||
script_path = os.path.join(base_dir, script_rel)
|
||||
|
||||
# Clean up old connection
|
||||
|
||||
@@ -17,10 +17,11 @@ import httpx
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_LOCAL_HOSTS = {"localhost", "127.0.0.1", "0.0.0.0", "::1", "host.docker.internal"}
|
||||
_PRIVATE_PREFIXES = ("10.", "172.16.", "172.17.", "172.18.", "172.19.",
|
||||
"172.20.", "172.21.", "172.22.", "172.23.", "172.24.",
|
||||
"172.25.", "172.26.", "172.27.", "172.28.", "172.29.",
|
||||
"172.30.", "172.31.", "192.168.")
|
||||
_PRIVATE_NETWORKS = (
|
||||
ipaddress.ip_network("10.0.0.0/8"),
|
||||
ipaddress.ip_network("172.16.0.0/12"),
|
||||
ipaddress.ip_network("192.168.0.0/16"),
|
||||
)
|
||||
|
||||
# Tailscale uses the CGNAT range 100.64.0.0/10, NOT all of 100.0.0.0/8.
|
||||
# A bare "100." prefix would classify public addresses (e.g. AWS ranges
|
||||
@@ -36,6 +37,14 @@ def _in_tailscale_range(host: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _is_private_ip_literal(host: str) -> bool:
|
||||
try:
|
||||
ip = ipaddress.ip_address(host)
|
||||
except ValueError:
|
||||
return False
|
||||
return any(ip in network for network in _PRIVATE_NETWORKS)
|
||||
|
||||
|
||||
def _normalize_base_for_compare(url: str) -> str:
|
||||
url = (url or "").strip().rstrip("/")
|
||||
for suffix in ("/chat/completions", "/models", "/completions", "/v1/messages"):
|
||||
@@ -87,7 +96,7 @@ def is_local_endpoint(url: str) -> bool:
|
||||
return True
|
||||
try:
|
||||
host = urlparse(url).hostname or ""
|
||||
return host in _LOCAL_HOSTS or host.startswith(_PRIVATE_PREFIXES) or _in_tailscale_range(host)
|
||||
return host in _LOCAL_HOSTS or _is_private_ip_literal(host) or _in_tailscale_range(host)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||