File size: 5,853 Bytes
9eff2c1
 
 
 
546d0f6
9391b1f
9eff2c1
546d0f6
 
2372d8d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
546d0f6
 
 
 
 
 
 
 
 
 
 
 
 
 
2372d8d
 
 
546d0f6
2372d8d
 
 
 
 
546d0f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2372d8d
 
 
 
546d0f6
 
2372d8d
546d0f6
 
2372d8d
 
 
 
 
 
 
 
546d0f6
 
 
 
 
2372d8d
 
 
 
 
546d0f6
 
 
2372d8d
 
 
546d0f6
 
 
 
 
2372d8d
 
 
 
 
 
546d0f6
2372d8d
 
 
 
 
 
 
 
 
 
546d0f6
2372d8d
 
 
 
 
 
546d0f6
 
 
 
2372d8d
 
 
546d0f6
 
 
 
 
 
2372d8d
9eff2c1
 
9391b1f
 
 
 
 
 
 
ef50eab
9391b1f
 
 
ef50eab
 
 
9391b1f
 
 
 
 
 
 
 
 
9eff2c1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
#!/bin/bash
set -e

SUGGESTIONS_FILE="/app/montaigne-config/prompt_suggestions.json"
POLICY_FILE="/app/montaigne-config/ui_policy.json"
MINIMAL_UI_PATCH_FILE="/app/montaigne-config/minimal_ui_patch.js"

if [ -f "$SUGGESTIONS_FILE" ] || [ -f "$POLICY_FILE" ]; then
    echo "Syncing Montaigne UI policy to OpenWebUI..."
    python3 - <<'PY'
import json
import os
import sqlite3
from pathlib import Path
from urllib.parse import unquote

from open_webui.env import DATA_DIR, DATABASE_URL


def load_suggestions(path: Path) -> list:
    payload = json.loads(path.read_text(encoding="utf-8"))
    suggestions = payload.get("default_prompt_suggestions", [])
    if not isinstance(suggestions, list):
        raise ValueError("default_prompt_suggestions must be a list")
    return suggestions


def load_policy(path: Path) -> dict:
    return json.loads(path.read_text(encoding="utf-8"))


def deep_update(target: dict, updates: dict) -> None:
    """Recursively update *target* with *updates*, creating missing keys."""
    for key, value in updates.items():
        if isinstance(value, dict) and isinstance(target.get(key), dict):
            deep_update(target[key], value)
        else:
            target[key] = value


def merge_config(config: dict, suggestions: list, policy: dict) -> dict:
    if not isinstance(config, dict):
        config = {}

    # Prompt suggestions
    ui = config.get("ui")
    if not isinstance(ui, dict):
        ui = {}
    ui["prompt_suggestions"] = suggestions
    config["ui"] = ui

    # Policy fields
    if "default_models" in policy:
        config["default_models"] = policy["default_models"]

    if "default_pinned_models" in policy:
        config["default_pinned_models"] = policy["default_pinned_models"]

    # Permissions
    if "permissions" in policy:
        perms = config.get("permissions")
        if not isinstance(perms, dict):
            perms = {}
        deep_update(perms, policy["permissions"])
        config["permissions"] = perms

    # Global features
    if "features" in policy:
        feats = config.get("features")
        if not isinstance(feats, dict):
            feats = {}
        deep_update(feats, policy["features"])
        config["features"] = feats

    config.setdefault("version", 0)
    return config


suggestions_file = Path("/app/montaigne-config/prompt_suggestions.json")
policy_file = Path("/app/montaigne-config/ui_policy.json")

suggestions = load_suggestions(suggestions_file) if suggestions_file.exists() else []
policy = load_policy(policy_file) if policy_file.exists() else {}

data_dir = Path(DATA_DIR)
database_url = str(DATABASE_URL)

if database_url.startswith("sqlite:///"):
    db_path = Path(unquote(database_url.replace("sqlite:///", "", 1)))

    if not db_path.exists():
        config = merge_config({}, suggestions, policy)
        config_path = data_dir / "config.json"
        config_path.parent.mkdir(parents=True, exist_ok=True)
        config_path.write_text(json.dumps(config, indent=2), encoding="utf-8")
        print(f"Wrote bootstrap config to {config_path}")
        raise SystemExit(0)

    conn = sqlite3.connect(db_path)
    try:
        cursor = conn.cursor()
        cursor.execute(
            "SELECT name FROM sqlite_master WHERE type='table' AND name='config'"
        )
        table_exists = cursor.fetchone() is not None

        if not table_exists:
            config = merge_config({}, suggestions, policy)
            config_path = data_dir / "config.json"
            config_path.parent.mkdir(parents=True, exist_ok=True)
            config_path.write_text(json.dumps(config, indent=2), encoding="utf-8")
            print(f"Wrote bootstrap config to {config_path}")
            raise SystemExit(0)

        cursor.execute("SELECT id, data FROM config ORDER BY id ASC LIMIT 1")
        row = cursor.fetchone()

        if row is None:
            config = merge_config({}, suggestions, policy)
            cursor.execute(
                "INSERT INTO config (data, version) VALUES (?, ?)",
                (json.dumps(config), int(config.get("version", 0))),
            )
        else:
            config_id, raw_data = row
            try:
                current = json.loads(raw_data) if raw_data else {}
            except json.JSONDecodeError:
                current = {}
            updated = merge_config(current, suggestions, policy)
            cursor.execute(
                "UPDATE config SET data = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?",
                (json.dumps(updated), config_id),
            )

        conn.commit()
        print(
            f"Applied {len(suggestions)} prompt suggestions "
            f"and {len(policy)} policy keys to sqlite config"
        )
    finally:
        conn.close()
else:
    if suggestions:
        os.environ["DEFAULT_PROMPT_SUGGESTIONS"] = json.dumps(
            suggestions, separators=(",", ":")
        )
        print("Non-sqlite database: exported DEFAULT_PROMPT_SUGGESTIONS fallback")
    print("Policy enforcement requires sqlite database; skipped.")
PY
fi

if [ -f "$MINIMAL_UI_PATCH_FILE" ] && [ -f "/app/build/index.html" ]; then
    cp "$MINIMAL_UI_PATCH_FILE" "/app/build/montaigne-minimal-ui.js"

    python3 - <<'PY'
from pathlib import Path

index_path = Path('/app/build/index.html')
script_tag = '<script src="/montaigne-minimal-ui.js"></script>'
html = index_path.read_text(encoding='utf-8')

if script_tag not in html:
    if '<script' in html:
        html = html.replace('<script', f'{script_tag}\n<script', 1)
    elif '</head>' in html:
        html = html.replace('</head>', f'    {script_tag}\n</head>', 1)
    elif '</body>' in html:
        html = html.replace('</body>', f'    {script_tag}\n</body>', 1)
    index_path.write_text(html, encoding='utf-8')
PY

    echo "Injected Montaigne minimal UI patch"
fi

exec "$@"