owui-deploy 0.1.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- owui_deploy/__init__.py +10 -0
- owui_deploy/__main__.py +5 -0
- owui_deploy/applier.py +96 -0
- owui_deploy/cli.py +324 -0
- owui_deploy/client.py +101 -0
- owui_deploy/config.py +190 -0
- owui_deploy/errors.py +41 -0
- owui_deploy/fake.py +353 -0
- owui_deploy/frontmatter.py +28 -0
- owui_deploy/i18n.py +60 -0
- owui_deploy/lint.py +246 -0
- owui_deploy/locales/en.json +107 -0
- owui_deploy/locales/ko.json +107 -0
- owui_deploy/normalize.py +22 -0
- owui_deploy/planner.py +124 -0
- owui_deploy/pull.py +100 -0
- owui_deploy/render.py +111 -0
- owui_deploy-0.1.2.dist-info/METADATA +374 -0
- owui_deploy-0.1.2.dist-info/RECORD +22 -0
- owui_deploy-0.1.2.dist-info/WHEEL +4 -0
- owui_deploy-0.1.2.dist-info/entry_points.txt +3 -0
- owui_deploy-0.1.2.dist-info/licenses/LICENSE +21 -0
owui_deploy/lint.py
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
"""Static checks for Open WebUI Tools and Functions (OWD001-OWD009).
|
|
2
|
+
|
|
3
|
+
Nothing is imported or executed: files are only read as text and parsed with ``ast``.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import ast
|
|
9
|
+
import re
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from .frontmatter import parse_frontmatter
|
|
14
|
+
from .normalize import REPLACEMENTS
|
|
15
|
+
|
|
16
|
+
FUNCTION_CLASSES = ("Pipe", "Filter", "Action", "Event") # server picks in this order
|
|
17
|
+
VALVES_CLASSES = ("Valves", "UserValves")
|
|
18
|
+
_SECRET_NAME = re.compile(r"(key|token|secret|passw(or)?d|passwd)", re.IGNORECASE)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True)
|
|
22
|
+
class Finding:
|
|
23
|
+
"""One lint result. ``msg_key`` indexes the locale tables."""
|
|
24
|
+
|
|
25
|
+
path: str
|
|
26
|
+
line: int
|
|
27
|
+
col: int
|
|
28
|
+
code: str
|
|
29
|
+
level: str # "error" | "warning"
|
|
30
|
+
msg_key: str
|
|
31
|
+
params: dict = field(default_factory=dict)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _top_level_names(tree: ast.Module) -> dict[str, ast.AST]:
|
|
35
|
+
"""Names bound at module level (class, import, assignment) - what ``hasattr(module, X)`` sees."""
|
|
36
|
+
names: dict[str, ast.AST] = {}
|
|
37
|
+
for node in tree.body:
|
|
38
|
+
if isinstance(node, ast.ClassDef):
|
|
39
|
+
names[node.name] = node
|
|
40
|
+
elif isinstance(node, (ast.Import, ast.ImportFrom)):
|
|
41
|
+
for alias in node.names:
|
|
42
|
+
names[(alias.asname or alias.name).split(".")[0]] = node
|
|
43
|
+
elif isinstance(node, ast.Assign):
|
|
44
|
+
for target in node.targets:
|
|
45
|
+
if isinstance(target, ast.Name):
|
|
46
|
+
names[target.id] = node
|
|
47
|
+
return names
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _derives_basemodel(cls: ast.ClassDef, classes: dict[str, ast.ClassDef], seen: set[str]) -> bool | None:
|
|
51
|
+
"""True if it derives BaseModel, False if it certainly does not, None if unknown (imported base)."""
|
|
52
|
+
if not cls.bases:
|
|
53
|
+
return False
|
|
54
|
+
unknown = False
|
|
55
|
+
for base in cls.bases:
|
|
56
|
+
if isinstance(base, ast.Name):
|
|
57
|
+
if base.id == "BaseModel":
|
|
58
|
+
return True
|
|
59
|
+
if base.id == "object":
|
|
60
|
+
continue
|
|
61
|
+
local = classes.get(base.id)
|
|
62
|
+
if local is not None and base.id not in seen:
|
|
63
|
+
verdict = _derives_basemodel(local, classes, seen | {base.id})
|
|
64
|
+
if verdict:
|
|
65
|
+
return True
|
|
66
|
+
if verdict is None:
|
|
67
|
+
unknown = True
|
|
68
|
+
else:
|
|
69
|
+
unknown = True
|
|
70
|
+
elif isinstance(base, ast.Attribute) and base.attr == "BaseModel":
|
|
71
|
+
return True
|
|
72
|
+
else:
|
|
73
|
+
unknown = True
|
|
74
|
+
return None if unknown else False
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _all_params(args: ast.arguments) -> list[ast.arg]:
|
|
78
|
+
return [*args.posonlyargs, *args.args, *args.kwonlyargs]
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _default_string(value: ast.expr | None) -> str | None:
|
|
82
|
+
"""The string default of ``x: str = "v"`` or ``x: str = Field(default="v")``."""
|
|
83
|
+
if isinstance(value, ast.Constant) and isinstance(value.value, str):
|
|
84
|
+
return value.value
|
|
85
|
+
if isinstance(value, ast.Call):
|
|
86
|
+
for kw in value.keywords:
|
|
87
|
+
if kw.arg == "default":
|
|
88
|
+
return _default_string(kw.value)
|
|
89
|
+
if value.args:
|
|
90
|
+
return _default_string(value.args[0])
|
|
91
|
+
return None
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def lint_source(path: str, kind: str, source: str, file_stem: str | None = None) -> list[Finding]:
|
|
95
|
+
"""Check one file. ``kind`` is ``"tools"`` or ``"functions"``."""
|
|
96
|
+
findings: list[Finding] = []
|
|
97
|
+
stem = file_stem if file_stem is not None else Path(path).stem
|
|
98
|
+
|
|
99
|
+
def add(line: int, col: int, code: str, level: str, key: str | None = None, **params: object) -> None:
|
|
100
|
+
findings.append(Finding(path, line, col, code, level, key or f"lint.{code}", dict(params)))
|
|
101
|
+
|
|
102
|
+
# OWD004 - file name becomes the id
|
|
103
|
+
if not stem.isidentifier():
|
|
104
|
+
add(1, 1, "OWD004", "error", name=stem)
|
|
105
|
+
elif stem != stem.lower():
|
|
106
|
+
add(1, 1, "OWD004", "warning", "lint.OWD004.case", name=stem, lowered=stem.lower())
|
|
107
|
+
|
|
108
|
+
# OWD005 - frontmatter (text based, works even if the code does not parse)
|
|
109
|
+
manifest = parse_frontmatter(source)
|
|
110
|
+
first = source.splitlines()[0].strip() if source.splitlines() else ""
|
|
111
|
+
if first != '"""':
|
|
112
|
+
add(1, 1, "OWD005", "warning", "lint.OWD005.first_line")
|
|
113
|
+
else:
|
|
114
|
+
missing = [k for k in ("title", "version") if not manifest.get(k)]
|
|
115
|
+
if missing:
|
|
116
|
+
add(1, 1, "OWD005", "warning", "lint.OWD005.missing", keys=", ".join(missing))
|
|
117
|
+
|
|
118
|
+
# OWD007 - server-side string replacement of imports (text based, same rule as the server)
|
|
119
|
+
for number, text in enumerate(source.splitlines(), start=1):
|
|
120
|
+
for old, new in REPLACEMENTS:
|
|
121
|
+
index = text.find(old)
|
|
122
|
+
if index < 0:
|
|
123
|
+
continue
|
|
124
|
+
following = text[index + len(old) : index + len(old) + 1]
|
|
125
|
+
weird = bool(following) and (following.isalnum() or following == "_")
|
|
126
|
+
add(
|
|
127
|
+
number,
|
|
128
|
+
index + 1,
|
|
129
|
+
"OWD007",
|
|
130
|
+
"warning",
|
|
131
|
+
"lint.OWD007.weird" if weird else "lint.OWD007",
|
|
132
|
+
old=old,
|
|
133
|
+
new=new,
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
# OWD001 - syntax
|
|
137
|
+
try:
|
|
138
|
+
tree = ast.parse(source)
|
|
139
|
+
except SyntaxError as exc:
|
|
140
|
+
add(exc.lineno or 1, exc.offset or 1, "OWD001", "error", detail=exc.msg)
|
|
141
|
+
return sorted(findings, key=lambda f: (f.line, f.col, f.code))
|
|
142
|
+
|
|
143
|
+
names = _top_level_names(tree)
|
|
144
|
+
classes = {n.name: n for n in tree.body if isinstance(n, ast.ClassDef)}
|
|
145
|
+
main_class: ast.ClassDef | None = None
|
|
146
|
+
|
|
147
|
+
# OWD002 / OWD003 - required classes
|
|
148
|
+
if kind == "tools":
|
|
149
|
+
if "Tools" not in names:
|
|
150
|
+
add(1, 1, "OWD002", "error", "lint.OWD002.tools")
|
|
151
|
+
else:
|
|
152
|
+
main_class = classes.get("Tools")
|
|
153
|
+
else:
|
|
154
|
+
present = [name for name in FUNCTION_CLASSES if name in names]
|
|
155
|
+
if not present:
|
|
156
|
+
add(1, 1, "OWD002", "error", "lint.OWD002.functions")
|
|
157
|
+
else:
|
|
158
|
+
main_class = classes.get(present[0])
|
|
159
|
+
if len(present) > 1:
|
|
160
|
+
node = names[present[0]]
|
|
161
|
+
add(
|
|
162
|
+
getattr(node, "lineno", 1),
|
|
163
|
+
1,
|
|
164
|
+
"OWD003",
|
|
165
|
+
"warning",
|
|
166
|
+
chosen=present[0],
|
|
167
|
+
ignored=", ".join(present[1:]),
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
if main_class is not None:
|
|
171
|
+
for member in main_class.body:
|
|
172
|
+
# OWD006 - Valves / UserValves must be pydantic models
|
|
173
|
+
if isinstance(member, ast.ClassDef) and member.name in VALVES_CLASSES:
|
|
174
|
+
if _derives_basemodel(member, classes, {member.name}) is False:
|
|
175
|
+
add(member.lineno, member.col_offset + 1, "OWD006", "error", name=member.name)
|
|
176
|
+
# OWD009 - suspicious hard-coded secret defaults
|
|
177
|
+
if member.name == "Valves":
|
|
178
|
+
for field_node in member.body:
|
|
179
|
+
if isinstance(field_node, ast.AnnAssign) and isinstance(field_node.target, ast.Name):
|
|
180
|
+
default = _default_string(field_node.value)
|
|
181
|
+
if default and _SECRET_NAME.search(field_node.target.id):
|
|
182
|
+
add(field_node.lineno, field_node.col_offset + 1, "OWD009", "warning", name=field_node.target.id)
|
|
183
|
+
# OWD008 - Tool method quality (the model sees docstring and type hints as the spec)
|
|
184
|
+
if kind == "tools" and isinstance(member, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
185
|
+
if member.name.startswith("_"):
|
|
186
|
+
continue
|
|
187
|
+
if not ast.get_docstring(member):
|
|
188
|
+
add(member.lineno, member.col_offset + 1, "OWD008", "warning", "lint.OWD008.doc", name=member.name)
|
|
189
|
+
untyped = [
|
|
190
|
+
a.arg
|
|
191
|
+
for a in _all_params(member.args)
|
|
192
|
+
if a.arg != "self" and not (a.arg.startswith("__") and a.arg.endswith("__")) and a.annotation is None
|
|
193
|
+
]
|
|
194
|
+
if untyped or member.returns is None:
|
|
195
|
+
add(
|
|
196
|
+
member.lineno,
|
|
197
|
+
member.col_offset + 1,
|
|
198
|
+
"OWD008",
|
|
199
|
+
"warning",
|
|
200
|
+
"lint.OWD008.hints",
|
|
201
|
+
name=member.name,
|
|
202
|
+
missing=", ".join(untyped + ([] if member.returns is not None else ["return"])),
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
return sorted(findings, key=lambda f: (f.line, f.col, f.code))
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def detect_kind(path: Path, source: str) -> str:
|
|
209
|
+
"""Infer tools/functions for a single file from its parent folder or its content."""
|
|
210
|
+
parent = path.resolve().parent.name
|
|
211
|
+
if parent in ("tools", "functions"):
|
|
212
|
+
return parent
|
|
213
|
+
return "tools" if re.search(r"^class\s+Tools\b", source, re.MULTILINE) else "functions"
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def lint_file(path: Path, kind: str, display: str | None = None) -> list[Finding]:
|
|
217
|
+
"""Read ``path`` as UTF-8 text and lint it (never imports it)."""
|
|
218
|
+
source = path.read_text(encoding="utf-8", errors="replace")
|
|
219
|
+
return lint_source(display or str(path), kind, source, file_stem=path.stem)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def collect_files(root: Path) -> list[tuple[Path, str, str]]:
|
|
223
|
+
"""Return ``(file, kind, display path)`` for a folder or a single file."""
|
|
224
|
+
if root.is_file():
|
|
225
|
+
kind = detect_kind(root, root.read_text(encoding="utf-8", errors="replace"))
|
|
226
|
+
return [(root, kind, root.name)]
|
|
227
|
+
result: list[tuple[Path, str, str]] = []
|
|
228
|
+
subdirs = [(name, root / name) for name in ("tools", "functions") if (root / name).is_dir()]
|
|
229
|
+
if not subdirs and root.name in ("tools", "functions"):
|
|
230
|
+
subdirs = [(root.name, root)]
|
|
231
|
+
for kind, folder in subdirs:
|
|
232
|
+
for file in sorted(folder.glob("*.py")):
|
|
233
|
+
if file.name.startswith("__"):
|
|
234
|
+
continue
|
|
235
|
+
display = file.relative_to(root).as_posix() if folder != root else file.name
|
|
236
|
+
result.append((file, kind, display))
|
|
237
|
+
return result
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def lint_path(root: Path) -> tuple[list[Finding], int]:
|
|
241
|
+
"""Lint everything under ``root``; return findings and the number of files checked."""
|
|
242
|
+
files = collect_files(root)
|
|
243
|
+
findings: list[Finding] = []
|
|
244
|
+
for file, kind, display in files:
|
|
245
|
+
findings.extend(lint_file(file, kind, display))
|
|
246
|
+
return findings, len(files)
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
{
|
|
2
|
+
"help.description": "Lint, plan and apply Open WebUI Tools and Functions from a git folder.\nThe folder is the source of truth: `plan` shows the difference, `apply` makes the server match.",
|
|
3
|
+
"help.epilog": "exit codes:\n 0 no difference / no problem found\n 1 difference or problem found (plan drift, lint error, server rejected an item)\n 2 tool error (missing config or token, cannot connect, 401/403, bad usage)",
|
|
4
|
+
"help.help": "show this help message and exit",
|
|
5
|
+
"help.version": "show the version and exit",
|
|
6
|
+
"help.lang": "output language: en or ko (also OWUI_DEPLOY_LANG, LC_ALL, LANG)",
|
|
7
|
+
"help.config": "configuration file (default: ./{name})",
|
|
8
|
+
"help.url": "Open WebUI base URL (overrides OWUI_URL and server.url)",
|
|
9
|
+
"help.fake": "use the built-in practice mock server instead of a real Open WebUI",
|
|
10
|
+
"help.lint": "check Tools and Functions statically (nothing is executed)",
|
|
11
|
+
"help.lint_path": "folder with tools/ and functions/ (or one .py file); default: the folders of the config file",
|
|
12
|
+
"help.json": "machine readable JSON output",
|
|
13
|
+
"help.strict": "exit 1 on warnings too",
|
|
14
|
+
"help.plan": "show what apply would change on the server",
|
|
15
|
+
"help.diff": "also print unified diffs of changed content",
|
|
16
|
+
"help.prune_plan": "show server-only items as deletions instead of unmanaged",
|
|
17
|
+
"help.fail_on_unmanaged": "exit 1 when the server has items that are not in the folder",
|
|
18
|
+
"help.apply": "make the server match the folder (create, update, toggle, optionally delete)",
|
|
19
|
+
"help.yes": "do not ask for confirmation (required when stdin is not a terminal)",
|
|
20
|
+
"help.prune_apply": "also delete server-only items (never happens without this flag)",
|
|
21
|
+
"help.message": "commit message stored in the server history (default: short git hash)",
|
|
22
|
+
"help.pull": "download Tools and Functions into files (valves values are never written)",
|
|
23
|
+
"help.out": "target folder (default: current folder)",
|
|
24
|
+
"help.force": "overwrite local files that differ from the server",
|
|
25
|
+
|
|
26
|
+
"err.prefix": "error",
|
|
27
|
+
"err.interrupted": "interrupted",
|
|
28
|
+
"err.internal": "unexpected problem ({detail}). Set OWUI_DEPLOY_DEBUG=1 to see the traceback.",
|
|
29
|
+
"err.connect": "cannot connect to {url}: {detail}. Is Open WebUI running and the URL correct?",
|
|
30
|
+
"err.auth": "the server refused the token (HTTP {status}: {detail}). Use an admin login token (JWT) or an API key; API keys need ENABLE_API_KEYS=true on the server.",
|
|
31
|
+
"err.bad_url": "invalid server URL: {url}. Use a full URL such as http://localhost:8080.",
|
|
32
|
+
"err.not_json": "{url} did not answer {path} with JSON. Is this an Open WebUI server?",
|
|
33
|
+
"err.unexpected": "{url} answered with an unexpected shape. Tested with Open WebUI 0.13.3; check the server version.",
|
|
34
|
+
"err.no_url": "no server URL. Set server.url in the config file, export OWUI_URL, pass --url, or try --fake.",
|
|
35
|
+
"err.no_token": "no token. Export OWUI_TOKEN with an admin login token (JWT) or an API key, or try --fake.",
|
|
36
|
+
|
|
37
|
+
"config.missing": "config file not found: {path}. Create it (see the README) or pass --config PATH.",
|
|
38
|
+
"config.invalid_toml": "cannot read {path}: {detail}",
|
|
39
|
+
"config.unknown_key": "unknown key(s) in {where}: {keys}",
|
|
40
|
+
"config.bad_type": "{where} must be {expected}",
|
|
41
|
+
"config.duplicate_key": "{where} declares \"{first}\" and \"{second}\", which are the same id \"{id}\" (ids are lowercased). Keep only one of them.",
|
|
42
|
+
"config.not_table": "{where} must be a table",
|
|
43
|
+
|
|
44
|
+
"field.content": "content",
|
|
45
|
+
"field.name": "name",
|
|
46
|
+
"field.description": "description",
|
|
47
|
+
"field.active": "active",
|
|
48
|
+
"field.global": "global",
|
|
49
|
+
|
|
50
|
+
"lint.OWD001": "syntax error: {detail}",
|
|
51
|
+
"lint.OWD002.tools": "no `class Tools` found (the server would answer only \"[ERROR: Error creating tool]\")",
|
|
52
|
+
"lint.OWD002.functions": "no Pipe/Filter/Action/Event class found (the server would answer only \"[ERROR: Error creating function]\")",
|
|
53
|
+
"lint.OWD003": "several Function classes in one file; the server uses only {chosen} and ignores {ignored}",
|
|
54
|
+
"lint.OWD004": "file name \"{name}\" is not a valid id (letters, digits and underscores only, not starting with a digit)",
|
|
55
|
+
"lint.OWD004.case": "file name \"{name}\" has upper case letters; the server lowercases the id to \"{lowered}\"",
|
|
56
|
+
"lint.OWD005.first_line": "first line is not exactly three double quotes; the server ignores the frontmatter",
|
|
57
|
+
"lint.OWD005.missing": "frontmatter has no value for: {keys}",
|
|
58
|
+
"lint.OWD006": "{name} does not inherit from pydantic BaseModel",
|
|
59
|
+
"lint.OWD007": "the server rewrites \"{old}\" to \"{new}\" when saving",
|
|
60
|
+
"lint.OWD007.weird": "the server rewrites the text \"{old}\" inside a longer word to \"{new}\"; this is probably not what you want",
|
|
61
|
+
"lint.OWD008.doc": "tool method {name} has no docstring (the model reads it as the description)",
|
|
62
|
+
"lint.OWD008.hints": "tool method {name} is missing type hints for: {missing}",
|
|
63
|
+
"lint.OWD009": "valve {name} looks like a secret but has a non-empty default in the source",
|
|
64
|
+
"lint.summary": "Lint: {files} file(s), {errors} error(s), {warnings} warning(s).",
|
|
65
|
+
"lint.clean": "Lint: no problems in {files} files.",
|
|
66
|
+
"lint.path_missing": "path not found: {path}",
|
|
67
|
+
"lint.no_files": "no .py files found under {path} (expected tools/ and functions/ folders)",
|
|
68
|
+
|
|
69
|
+
"fake.banner": "Server: fake server (practice mock, not a real Open WebUI). State file: {state}",
|
|
70
|
+
"plan.server": "Server: {url}",
|
|
71
|
+
"plan.summary": "Plan: {parts}.",
|
|
72
|
+
"plan.none": "Plan: no changes.",
|
|
73
|
+
"plan.part.create": "{n} to create",
|
|
74
|
+
"plan.part.update": "{n} to update",
|
|
75
|
+
"plan.part.state": "{n} to change state",
|
|
76
|
+
"plan.part.delete": "{n} to delete",
|
|
77
|
+
"plan.part.unmanaged": "{n} unmanaged",
|
|
78
|
+
"plan.part.skipped": "{n} skipped",
|
|
79
|
+
"plan.unmanaged_note": "only on the server; left alone without --prune",
|
|
80
|
+
"plan.delete_note": "only on the server; will be deleted because of --prune",
|
|
81
|
+
|
|
82
|
+
"skip.bad_id": "file name \"{name}\" is not a valid id; see lint OWD004",
|
|
83
|
+
"skip.duplicate": "id \"{id}\" is already used by {other}",
|
|
84
|
+
"skip.folder_missing": "the configured folder does not exist: {folder}. Check [paths] in owui-deploy.toml",
|
|
85
|
+
"config.not_utf8": "{path} is not valid UTF-8. Save it as UTF-8 or run `owui-deploy lint` to see the problem.",
|
|
86
|
+
"skip.config_without_file": "the config declares \"{id}\" but there is no such file",
|
|
87
|
+
|
|
88
|
+
"apply.nothing": "No changes.",
|
|
89
|
+
"apply.need_yes": "stdin is not a terminal and --yes was not given; nothing was changed. Re-run with --yes to apply.",
|
|
90
|
+
"apply.confirm": "Apply these changes? [y/N] ",
|
|
91
|
+
"apply.cancelled": "Cancelled. Nothing was changed.",
|
|
92
|
+
"apply.done_line": "applied: {action} {kind} {id}",
|
|
93
|
+
"apply.rejected_line": "rejected by the server: {action} {kind} {id} (HTTP {status}: {detail})",
|
|
94
|
+
"apply.hint_line": " hint: {text}",
|
|
95
|
+
"apply.hint_generic": " hint: run `owui-deploy lint` for {kind} {id}; the server log has the real reason.",
|
|
96
|
+
"apply.summary": "Apply: {done} requests applied, {rejected} rejected.",
|
|
97
|
+
|
|
98
|
+
"pull.written": "wrote {item}",
|
|
99
|
+
"pull.kept": "kept local file (differs from the server, use --force to overwrite): {item}",
|
|
100
|
+
"pull.invalid_id": "skipped (id is not a valid file name): {item}",
|
|
101
|
+
"pull.summary": "Pull: {written} written, {unchanged} unchanged, {kept} kept.",
|
|
102
|
+
"pull.config_written": "wrote config file {path}",
|
|
103
|
+
"pull.config_kept": "kept existing config file {path} (not overwritten)",
|
|
104
|
+
"pull.state_diff": "config differs from the server: {item} ({field}: config {want}, server {have})",
|
|
105
|
+
"pull.valves_dropped": "{n} valves values were not written (secrets stay on the server).",
|
|
106
|
+
"pull.valves_note": "Valves (settings and secrets) are not exported; they stay on the server."
|
|
107
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
{
|
|
2
|
+
"help.description": "git 폴더의 Open WebUI Tools·Functions 를 점검(lint)하고, 차이를 계획(plan)하고, 서버에 반영(apply)합니다.\n폴더가 원본입니다. `plan` 은 차이를 보여 주고 `apply` 는 서버를 폴더에 맞춥니다.",
|
|
3
|
+
"help.epilog": "종료 코드:\n 0 차이 없음 / 문제 없음\n 1 차이 또는 문제 발견 (plan 드리프트, lint 오류, 서버가 항목을 거부함)\n 2 도구 오류 (설정 파일·토큰 없음, 연결 실패, 401/403, 잘못된 사용법)",
|
|
4
|
+
"help.help": "도움말을 보여 주고 종료합니다",
|
|
5
|
+
"help.version": "버전을 보여 주고 종료합니다",
|
|
6
|
+
"help.lang": "출력 언어: en 또는 ko (OWUI_DEPLOY_LANG, LC_ALL, LANG 도 사용합니다)",
|
|
7
|
+
"help.config": "설정 파일 (기본값: ./{name})",
|
|
8
|
+
"help.url": "Open WebUI 주소 (OWUI_URL 과 server.url 보다 우선합니다)",
|
|
9
|
+
"help.fake": "실제 Open WebUI 대신 내장 연습용 목 서버를 사용합니다",
|
|
10
|
+
"help.lint": "Tools·Functions 를 정적으로 점검합니다 (코드를 실행하지 않습니다)",
|
|
11
|
+
"help.lint_path": "tools/·functions/ 폴더가 있는 폴더 (또는 .py 파일 하나). 기본값: 설정 파일의 폴더",
|
|
12
|
+
"help.json": "기계가 읽는 JSON 으로 출력합니다",
|
|
13
|
+
"help.strict": "경고가 있어도 종료 코드 1 을 반환합니다",
|
|
14
|
+
"help.plan": "apply 가 서버에서 무엇을 바꿀지 보여 줍니다",
|
|
15
|
+
"help.diff": "바뀐 내용의 unified diff 도 출력합니다",
|
|
16
|
+
"help.prune_plan": "서버에만 있는 항목을 미관리가 아니라 삭제로 보여 줍니다",
|
|
17
|
+
"help.fail_on_unmanaged": "서버에 폴더에 없는 항목이 있으면 종료 코드 1 을 반환합니다",
|
|
18
|
+
"help.apply": "서버를 폴더에 맞춥니다 (생성, 수정, 토글, 선택적 삭제)",
|
|
19
|
+
"help.yes": "확인을 묻지 않습니다 (stdin 이 터미널이 아니면 필수입니다)",
|
|
20
|
+
"help.prune_apply": "서버에만 있는 항목도 삭제합니다 (이 옵션 없이는 절대 삭제하지 않습니다)",
|
|
21
|
+
"help.message": "서버 이력에 남길 커밋 메시지 (기본값: git 짧은 해시)",
|
|
22
|
+
"help.pull": "Tools·Functions 를 파일로 내려받습니다 (valves 값은 절대 쓰지 않습니다)",
|
|
23
|
+
"help.out": "대상 폴더 (기본값: 현재 폴더)",
|
|
24
|
+
"help.force": "서버와 다른 로컬 파일을 덮어씁니다",
|
|
25
|
+
|
|
26
|
+
"err.prefix": "오류",
|
|
27
|
+
"err.interrupted": "중단되었습니다",
|
|
28
|
+
"err.internal": "예상하지 못한 문제가 생겼습니다 ({detail}). OWUI_DEPLOY_DEBUG=1 로 실행하면 트레이스백을 볼 수 있습니다.",
|
|
29
|
+
"err.connect": "{url} 에 연결할 수 없습니다: {detail}. Open WebUI 가 실행 중이고 주소가 맞는지 확인하십시오.",
|
|
30
|
+
"err.auth": "서버가 토큰을 거부했습니다 (HTTP {status}: {detail}). 관리자 로그인 토큰(JWT)이나 API 키를 사용하십시오. API 키는 서버에 ENABLE_API_KEYS=true 가 필요합니다.",
|
|
31
|
+
"err.bad_url": "서버 주소가 올바르지 않습니다: {url}. http://localhost:8080 처럼 전체 주소를 쓰십시오.",
|
|
32
|
+
"err.not_json": "{url} 이(가) {path} 에 JSON 으로 응답하지 않았습니다. Open WebUI 서버가 맞습니까?",
|
|
33
|
+
"err.unexpected": "{url} 의 응답 형태가 예상과 다릅니다. Open WebUI 0.13.3 에서 확인했으니 서버 버전을 확인하십시오.",
|
|
34
|
+
"err.no_url": "서버 주소가 없습니다. 설정 파일의 server.url 을 쓰거나, OWUI_URL 을 내보내거나, --url 을 주거나, --fake 를 써 보십시오.",
|
|
35
|
+
"err.no_token": "토큰이 없습니다. 관리자 로그인 토큰(JWT)이나 API 키를 OWUI_TOKEN 으로 내보내거나, --fake 를 써 보십시오.",
|
|
36
|
+
|
|
37
|
+
"config.missing": "설정 파일이 없습니다: {path}. README 를 보고 만들거나 --config PATH 를 주십시오.",
|
|
38
|
+
"config.invalid_toml": "{path} 을(를) 읽을 수 없습니다: {detail}",
|
|
39
|
+
"config.unknown_key": "{where} 에 알 수 없는 키가 있습니다: {keys}",
|
|
40
|
+
"config.bad_type": "{where} 은(는) {expected} 여야 합니다",
|
|
41
|
+
"config.duplicate_key": "{where} 에 \"{first}\" 와 \"{second}\" 가 모두 있는데 둘 다 id \"{id}\" 입니다(id 는 소문자로 바뀝니다). 하나만 남기십시오.",
|
|
42
|
+
"config.not_table": "{where} 은(는) 테이블이어야 합니다",
|
|
43
|
+
|
|
44
|
+
"field.content": "내용",
|
|
45
|
+
"field.name": "이름",
|
|
46
|
+
"field.description": "설명",
|
|
47
|
+
"field.active": "활성",
|
|
48
|
+
"field.global": "전역",
|
|
49
|
+
|
|
50
|
+
"lint.OWD001": "문법 오류: {detail}",
|
|
51
|
+
"lint.OWD002.tools": "`class Tools` 가 없습니다 (서버는 \"[ERROR: Error creating tool]\" 한 줄만 응답합니다)",
|
|
52
|
+
"lint.OWD002.functions": "Pipe/Filter/Action/Event 클래스가 없습니다 (서버는 \"[ERROR: Error creating function]\" 한 줄만 응답합니다)",
|
|
53
|
+
"lint.OWD003": "한 파일에 Function 클래스가 여러 개 있습니다. 서버는 {chosen} 만 쓰고 {ignored} 은(는) 무시합니다",
|
|
54
|
+
"lint.OWD004": "파일 이름 \"{name}\" 은(는) 올바른 id 가 아닙니다 (영문자·숫자·밑줄만 가능하고 숫자로 시작할 수 없습니다)",
|
|
55
|
+
"lint.OWD004.case": "파일 이름 \"{name}\" 에 대문자가 있습니다. 서버는 id 를 \"{lowered}\" 로 소문자 변환합니다",
|
|
56
|
+
"lint.OWD005.first_line": "첫 줄이 정확히 큰따옴표 세 개가 아니어서 서버가 frontmatter 를 무시합니다",
|
|
57
|
+
"lint.OWD005.missing": "frontmatter 에 값이 없는 항목: {keys}",
|
|
58
|
+
"lint.OWD006": "{name} 이(가) pydantic BaseModel 을 상속하지 않습니다",
|
|
59
|
+
"lint.OWD007": "서버가 저장할 때 \"{old}\" 을(를) \"{new}\" 로 다시 씁니다",
|
|
60
|
+
"lint.OWD007.weird": "서버가 더 긴 단어 안의 \"{old}\" 문자열을 \"{new}\" 로 바꿉니다. 의도한 동작이 아닐 가능성이 큽니다",
|
|
61
|
+
"lint.OWD008.doc": "Tool 메서드 {name} 에 docstring 이 없습니다 (모델이 설명으로 읽습니다)",
|
|
62
|
+
"lint.OWD008.hints": "Tool 메서드 {name} 에 타입 힌트가 없습니다: {missing}",
|
|
63
|
+
"lint.OWD009": "valve {name} 은(는) 비밀처럼 보이는데 소스에 비어 있지 않은 기본값이 있습니다",
|
|
64
|
+
"lint.summary": "점검 결과: 파일 {files}개, 오류 {errors}건, 경고 {warnings}건입니다.",
|
|
65
|
+
"lint.clean": "점검 결과: 파일 {files}개에서 문제가 없습니다.",
|
|
66
|
+
"lint.path_missing": "경로를 찾을 수 없습니다: {path}",
|
|
67
|
+
"lint.no_files": "{path} 아래에 .py 파일이 없습니다 (tools/·functions/ 폴더가 필요합니다)",
|
|
68
|
+
|
|
69
|
+
"fake.banner": "서버: 가짜 서버 (practice mock, 연습용 목이며 실제 Open WebUI 가 아닙니다). 상태 파일: {state}",
|
|
70
|
+
"plan.server": "서버: {url}",
|
|
71
|
+
"plan.summary": "Plan: {parts}입니다.",
|
|
72
|
+
"plan.none": "Plan: 변경 사항이 없습니다.",
|
|
73
|
+
"plan.part.create": "생성 {n}건",
|
|
74
|
+
"plan.part.update": "수정 {n}건",
|
|
75
|
+
"plan.part.state": "상태 변경 {n}건",
|
|
76
|
+
"plan.part.delete": "삭제 {n}건",
|
|
77
|
+
"plan.part.unmanaged": "미관리 {n}건",
|
|
78
|
+
"plan.part.skipped": "건너뜀 {n}건",
|
|
79
|
+
"plan.unmanaged_note": "서버에만 있음. --prune 없이는 건드리지 않습니다",
|
|
80
|
+
"plan.delete_note": "서버에만 있음. --prune 때문에 삭제합니다",
|
|
81
|
+
|
|
82
|
+
"skip.bad_id": "파일 이름 \"{name}\" 은(는) 올바른 id 가 아닙니다. lint OWD004 를 확인하십시오",
|
|
83
|
+
"skip.duplicate": "id \"{id}\" 은(는) 이미 {other} 이(가) 사용합니다",
|
|
84
|
+
"skip.folder_missing": "설정한 폴더가 없습니다: {folder}. owui-deploy.toml 의 [paths] 를 확인하십시오",
|
|
85
|
+
"config.not_utf8": "{path} 이(가) UTF-8 이 아닙니다. UTF-8 로 저장하거나 `owui-deploy lint` 로 문제를 확인하십시오.",
|
|
86
|
+
"skip.config_without_file": "설정에 \"{id}\" 이(가) 있지만 해당 파일이 없습니다",
|
|
87
|
+
|
|
88
|
+
"apply.nothing": "변경 사항이 없습니다.",
|
|
89
|
+
"apply.need_yes": "stdin 이 터미널이 아니고 --yes 도 없어서 아무것도 바꾸지 않았습니다. 반영하려면 --yes 를 붙여 다시 실행하십시오.",
|
|
90
|
+
"apply.confirm": "이 변경을 반영합니까? [y/N] ",
|
|
91
|
+
"apply.cancelled": "취소했습니다. 아무것도 바꾸지 않았습니다.",
|
|
92
|
+
"apply.done_line": "반영함: {action} {kind} {id}",
|
|
93
|
+
"apply.rejected_line": "서버가 거부함: {action} {kind} {id} (HTTP {status}: {detail})",
|
|
94
|
+
"apply.hint_line": " 힌트: {text}",
|
|
95
|
+
"apply.hint_generic": " 힌트: {kind} {id} 에 `owui-deploy lint` 를 실행해 보십시오. 실제 원인은 서버 로그에 있습니다.",
|
|
96
|
+
"apply.summary": "반영 결과: 요청 {done}건 반영, {rejected}건 거부되었습니다.",
|
|
97
|
+
|
|
98
|
+
"pull.written": "파일을 썼습니다: {item}",
|
|
99
|
+
"pull.kept": "로컬 파일을 유지했습니다 (서버와 다릅니다. 덮어쓰려면 --force): {item}",
|
|
100
|
+
"pull.invalid_id": "건너뛰었습니다 (id 가 올바른 파일 이름이 아닙니다): {item}",
|
|
101
|
+
"pull.summary": "내려받기: {written}건 썼고, {unchanged}건은 같고, {kept}건은 유지했습니다.",
|
|
102
|
+
"pull.config_written": "설정 파일을 만들었습니다: {path}",
|
|
103
|
+
"pull.config_kept": "기존 설정 파일을 유지했습니다 (덮어쓰지 않습니다): {path}",
|
|
104
|
+
"pull.state_diff": "설정이 서버와 다릅니다: {item} ({field}: 설정 {want}, 서버 {have})",
|
|
105
|
+
"pull.valves_dropped": "valves 값 {n}개를 쓰지 않았습니다 (비밀은 서버에만 남습니다).",
|
|
106
|
+
"pull.valves_note": "Valves(설정과 비밀)는 내려받지 않습니다. 서버에만 남습니다."
|
|
107
|
+
}
|
owui_deploy/normalize.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Reproduce the server's import rewriting so that plan does not report fake diffs.
|
|
2
|
+
|
|
3
|
+
Open WebUI 0.13.3 runs a plain ``str.replace`` over the uploaded source before it
|
|
4
|
+
stores it (``utils/plugin.py::replace_imports``). The same replacement is applied
|
|
5
|
+
to the local file before comparing.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
REPLACEMENTS: tuple[tuple[str, str], ...] = (
|
|
11
|
+
("from utils", "from open_webui.utils"),
|
|
12
|
+
("from apps", "from open_webui.apps"),
|
|
13
|
+
("from main", "from open_webui.main"),
|
|
14
|
+
("from config", "from open_webui.config"),
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def normalize(content: str) -> str:
|
|
19
|
+
"""Apply the server's import rewriting (idempotent)."""
|
|
20
|
+
for old, new in REPLACEMENTS:
|
|
21
|
+
content = content.replace(old, new)
|
|
22
|
+
return content
|
owui_deploy/planner.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""Compare the desired state (local files) with the remote state (export)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import difflib
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
|
|
8
|
+
from .config import DesiredItem, Skipped
|
|
9
|
+
from .normalize import normalize
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass
|
|
13
|
+
class Change:
|
|
14
|
+
"""One line of the plan.
|
|
15
|
+
|
|
16
|
+
``action``: create | update | state | delete | unmanaged | skip.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
kind: str
|
|
20
|
+
id: str
|
|
21
|
+
action: str
|
|
22
|
+
fields: list[str] = field(default_factory=list)
|
|
23
|
+
detail: dict = field(default_factory=dict)
|
|
24
|
+
diff: str = ""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class Plan:
|
|
29
|
+
changes: list[Change]
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def summary(self) -> dict[str, int]:
|
|
33
|
+
counts = {"create": 0, "update": 0, "state": 0, "delete": 0, "unmanaged": 0, "skipped": 0}
|
|
34
|
+
for change in self.changes:
|
|
35
|
+
counts["skipped" if change.action == "skip" else change.action] += 1
|
|
36
|
+
return counts
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def writes(self) -> list[Change]:
|
|
40
|
+
"""Changes that would send write requests."""
|
|
41
|
+
return [c for c in self.changes if c.action in ("create", "update", "state", "delete")]
|
|
42
|
+
|
|
43
|
+
def has_drift(self, fail_on_unmanaged: bool = False) -> bool:
|
|
44
|
+
counts = self.summary
|
|
45
|
+
drift = counts["create"] + counts["update"] + counts["state"] + counts["delete"] + counts["skipped"]
|
|
46
|
+
if fail_on_unmanaged:
|
|
47
|
+
drift += counts["unmanaged"]
|
|
48
|
+
return drift > 0
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def remote_description(entry: dict) -> str:
|
|
52
|
+
meta = entry.get("meta") or {}
|
|
53
|
+
return meta.get("description") or ""
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def make_diff(item_id: str, remote: str, desired: str) -> str:
|
|
57
|
+
lines = difflib.unified_diff(
|
|
58
|
+
remote.splitlines(keepends=True),
|
|
59
|
+
desired.splitlines(keepends=True),
|
|
60
|
+
fromfile=f"server/{item_id}.py",
|
|
61
|
+
tofile=f"local/{item_id}.py",
|
|
62
|
+
)
|
|
63
|
+
return "".join(line if line.endswith("\n") else line + "\n" for line in lines)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def build_plan(
|
|
67
|
+
desired: list[DesiredItem],
|
|
68
|
+
skipped: list[Skipped],
|
|
69
|
+
remote: dict[str, list[dict]],
|
|
70
|
+
prune: bool = False,
|
|
71
|
+
) -> Plan:
|
|
72
|
+
"""``remote`` maps ``"tool"``/``"function"`` to the export lists."""
|
|
73
|
+
changes: list[Change] = []
|
|
74
|
+
remote_by_key = {(kind, e["id"]): e for kind, entries in remote.items() for e in entries}
|
|
75
|
+
desired_keys = {(d.kind, d.id) for d in desired}
|
|
76
|
+
|
|
77
|
+
for item in desired:
|
|
78
|
+
entry = remote_by_key.get((item.kind, item.id))
|
|
79
|
+
want = normalize(item.content)
|
|
80
|
+
if entry is None:
|
|
81
|
+
fields = ["content", "name", "description"]
|
|
82
|
+
# a new Function starts inactive and non-global; a new Tool starts active
|
|
83
|
+
start_active = item.kind == "tool"
|
|
84
|
+
if item.active != start_active:
|
|
85
|
+
fields.append("active")
|
|
86
|
+
if item.kind == "function" and item.is_global:
|
|
87
|
+
fields.append("global")
|
|
88
|
+
changes.append(Change(item.kind, item.id, "create", fields))
|
|
89
|
+
continue
|
|
90
|
+
|
|
91
|
+
update_fields = []
|
|
92
|
+
if entry.get("content") != want:
|
|
93
|
+
update_fields.append("content")
|
|
94
|
+
if entry.get("name") != item.name:
|
|
95
|
+
update_fields.append("name")
|
|
96
|
+
if remote_description(entry) != item.description:
|
|
97
|
+
update_fields.append("description")
|
|
98
|
+
if update_fields:
|
|
99
|
+
change = Change(item.kind, item.id, "update", update_fields)
|
|
100
|
+
if "content" in update_fields:
|
|
101
|
+
change.diff = make_diff(item.id, entry.get("content") or "", want)
|
|
102
|
+
changes.append(change)
|
|
103
|
+
|
|
104
|
+
state_fields = []
|
|
105
|
+
detail: dict = {}
|
|
106
|
+
if bool(entry.get("is_active")) != item.active:
|
|
107
|
+
state_fields.append("active")
|
|
108
|
+
detail["active"] = [bool(entry.get("is_active")), item.active]
|
|
109
|
+
if item.kind == "function" and bool(entry.get("is_global")) != item.is_global:
|
|
110
|
+
state_fields.append("global")
|
|
111
|
+
detail["global"] = [bool(entry.get("is_global")), item.is_global]
|
|
112
|
+
if state_fields:
|
|
113
|
+
changes.append(Change(item.kind, item.id, "state", state_fields, detail))
|
|
114
|
+
|
|
115
|
+
for (kind, item_id), entry in sorted(remote_by_key.items()):
|
|
116
|
+
if (kind, item_id) not in desired_keys:
|
|
117
|
+
changes.append(Change(kind, item_id, "delete" if prune else "unmanaged"))
|
|
118
|
+
|
|
119
|
+
for skip in skipped:
|
|
120
|
+
changes.append(Change(skip.kind, skip.path.stem, "skip", [], {"reason_key": skip.reason_key, "params": skip.params}))
|
|
121
|
+
|
|
122
|
+
order = {"create": 0, "update": 1, "state": 2, "delete": 3, "unmanaged": 4, "skip": 5}
|
|
123
|
+
changes.sort(key=lambda c: (order[c.action], c.kind, c.id))
|
|
124
|
+
return Plan(changes)
|