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/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""owui-deploy: lint, plan and apply Open WebUI Tools and Functions from a git folder."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
__version__ = version("owui-deploy")
|
|
7
|
+
except PackageNotFoundError: # running from a source tree without install
|
|
8
|
+
__version__ = "0.0.0+unknown"
|
|
9
|
+
|
|
10
|
+
__all__ = ["__version__"]
|
owui_deploy/__main__.py
ADDED
owui_deploy/applier.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""Run a plan against a server: create/update, toggle only when needed, delete only on request."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import subprocess
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from .client import OpenWebUIClient
|
|
10
|
+
from .config import DesiredItem
|
|
11
|
+
from .errors import ApiError
|
|
12
|
+
from .planner import Plan
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass
|
|
16
|
+
class Rejection:
|
|
17
|
+
kind: str
|
|
18
|
+
id: str
|
|
19
|
+
action: str
|
|
20
|
+
status: int
|
|
21
|
+
detail: str
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass
|
|
25
|
+
class ApplyResult:
|
|
26
|
+
done: list[tuple[str, str, str]] = field(default_factory=list) # (action, kind, id)
|
|
27
|
+
rejected: list[Rejection] = field(default_factory=list)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def git_short_hash(directory: Path) -> str | None:
|
|
31
|
+
"""Short hash of HEAD in ``directory``, or None when git or a repository is missing."""
|
|
32
|
+
try:
|
|
33
|
+
result = subprocess.run(
|
|
34
|
+
["git", "rev-parse", "--short", "HEAD"],
|
|
35
|
+
cwd=directory,
|
|
36
|
+
capture_output=True,
|
|
37
|
+
text=True,
|
|
38
|
+
timeout=10,
|
|
39
|
+
check=False,
|
|
40
|
+
)
|
|
41
|
+
except (OSError, subprocess.SubprocessError):
|
|
42
|
+
return None
|
|
43
|
+
value = result.stdout.strip()
|
|
44
|
+
return value if result.returncode == 0 and value else None
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _ensure_state(client: OpenWebUIClient, item: DesiredItem, result: ApplyResult) -> None:
|
|
48
|
+
"""Re-read the item and toggle only what differs (the toggle API flips, it does not set)."""
|
|
49
|
+
current = client.get(item.kind, item.id)
|
|
50
|
+
if bool(current.get("is_active")) != item.active:
|
|
51
|
+
client.toggle(item.kind, item.id)
|
|
52
|
+
result.done.append(("toggle", item.kind, item.id))
|
|
53
|
+
if item.kind == "function" and bool(current.get("is_global")) != item.is_global:
|
|
54
|
+
client.toggle_global(item.id)
|
|
55
|
+
result.done.append(("toggle_global", item.kind, item.id))
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def apply_plan(
|
|
59
|
+
client: OpenWebUIClient,
|
|
60
|
+
plan: Plan,
|
|
61
|
+
desired: list[DesiredItem],
|
|
62
|
+
message: str | None = None,
|
|
63
|
+
) -> ApplyResult:
|
|
64
|
+
"""Apply create/update/state/delete entries. One rejected item does not stop the others."""
|
|
65
|
+
by_key = {(d.kind, d.id): d for d in desired}
|
|
66
|
+
result = ApplyResult()
|
|
67
|
+
for change in plan.changes:
|
|
68
|
+
if change.action not in ("create", "update", "state", "delete"):
|
|
69
|
+
continue
|
|
70
|
+
item = by_key.get((change.kind, change.id))
|
|
71
|
+
try:
|
|
72
|
+
if change.action == "delete":
|
|
73
|
+
client.delete(change.kind, change.id)
|
|
74
|
+
result.done.append(("delete", change.kind, change.id))
|
|
75
|
+
continue
|
|
76
|
+
assert item is not None # create/update/state always come from a desired item
|
|
77
|
+
payload = {
|
|
78
|
+
"id": item.id,
|
|
79
|
+
"name": item.name,
|
|
80
|
+
"content": item.content,
|
|
81
|
+
"meta": {"description": item.description},
|
|
82
|
+
}
|
|
83
|
+
if change.action == "create":
|
|
84
|
+
client.create(item.kind, payload)
|
|
85
|
+
result.done.append(("create", item.kind, item.id))
|
|
86
|
+
_ensure_state(client, item, result)
|
|
87
|
+
elif change.action == "update":
|
|
88
|
+
if message:
|
|
89
|
+
payload["commit_message"] = message
|
|
90
|
+
client.update(item.kind, item.id, payload)
|
|
91
|
+
result.done.append(("update", item.kind, item.id))
|
|
92
|
+
else:
|
|
93
|
+
_ensure_state(client, item, result)
|
|
94
|
+
except ApiError as exc:
|
|
95
|
+
result.rejected.append(Rejection(change.kind, change.id, change.action, exc.status, exc.detail))
|
|
96
|
+
return result
|
owui_deploy/cli.py
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
"""Command line entry point: ``owui-deploy {lint,pull,plan,apply}``.
|
|
2
|
+
|
|
3
|
+
Exit codes: 0 = nothing to report, 1 = differences or problems found, 2 = tool error.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import argparse
|
|
9
|
+
import os
|
|
10
|
+
import sys
|
|
11
|
+
import traceback
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Sequence
|
|
14
|
+
|
|
15
|
+
from . import __version__, i18n
|
|
16
|
+
from .applier import apply_plan, git_short_hash
|
|
17
|
+
from .client import OpenWebUIClient
|
|
18
|
+
from .config import DEFAULT_CONFIG_NAME, Config, build_desired, load_config
|
|
19
|
+
from .errors import ToolError
|
|
20
|
+
from .fake import FakeOpenWebUI
|
|
21
|
+
from .i18n import t
|
|
22
|
+
from .lint import lint_path, lint_source
|
|
23
|
+
from .planner import Plan, build_plan
|
|
24
|
+
from .pull import pull as run_pull
|
|
25
|
+
from . import render
|
|
26
|
+
|
|
27
|
+
FAKE_STATE_NAME = ".owui-deploy-fake.json"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
# argparse's own fixed phrases come from gettext; map them to Korean so that `--lang ko` is complete.
|
|
31
|
+
_ARGPARSE_KO = {
|
|
32
|
+
"usage: ": "사용법: ",
|
|
33
|
+
"positional arguments": "위치 인자",
|
|
34
|
+
"options": "옵션",
|
|
35
|
+
"optional arguments": "옵션",
|
|
36
|
+
"%(prog)s: error: %(message)s\n": "%(prog)s: 오류: %(message)s\n",
|
|
37
|
+
"unrecognized arguments: %s": "인식할 수 없는 인자입니다: %s",
|
|
38
|
+
"the following arguments are required: %s": "다음 인자가 필요합니다: %s",
|
|
39
|
+
"invalid choice: %(value)r (choose from %(choices)s)": "잘못된 선택입니다: %(value)r (선택 가능: %(choices)s)",
|
|
40
|
+
"expected one argument": "값이 하나 필요합니다",
|
|
41
|
+
"show this help message and exit": "도움말을 보여 주고 종료합니다",
|
|
42
|
+
}
|
|
43
|
+
_ARGPARSE_ORIGINAL = argparse._
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _localize_argparse(lang: str) -> None:
|
|
47
|
+
"""Swap argparse's translator for the chosen language (English restores the original)."""
|
|
48
|
+
if lang == "ko":
|
|
49
|
+
argparse._ = lambda text: _ARGPARSE_KO.get(text, _ARGPARSE_ORIGINAL(text)) # type: ignore[attr-defined]
|
|
50
|
+
else:
|
|
51
|
+
argparse._ = _ARGPARSE_ORIGINAL # type: ignore[attr-defined]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _preparse_lang(argv: Sequence[str]) -> str | None:
|
|
55
|
+
"""Find ``--lang`` before argparse runs, so that the help text itself is translated."""
|
|
56
|
+
for index, arg in enumerate(argv):
|
|
57
|
+
if arg == "--lang" and index + 1 < len(argv):
|
|
58
|
+
return argv[index + 1]
|
|
59
|
+
if arg.startswith("--lang="):
|
|
60
|
+
return arg.split("=", 1)[1]
|
|
61
|
+
return None
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
65
|
+
"""Build the parser; every help string is looked up in the current language."""
|
|
66
|
+
common = argparse.ArgumentParser(add_help=False)
|
|
67
|
+
common.add_argument("--lang", choices=i18n.SUPPORTED, default=argparse.SUPPRESS, help=t("help.lang"))
|
|
68
|
+
|
|
69
|
+
server = argparse.ArgumentParser(add_help=False, parents=[common])
|
|
70
|
+
server.add_argument("--config", metavar="PATH", help=t("help.config", name=DEFAULT_CONFIG_NAME))
|
|
71
|
+
server.add_argument("--url", metavar="URL", help=t("help.url"))
|
|
72
|
+
server.add_argument("--fake", action="store_true", help=t("help.fake"))
|
|
73
|
+
|
|
74
|
+
parser = argparse.ArgumentParser(
|
|
75
|
+
prog="owui-deploy",
|
|
76
|
+
add_help=False,
|
|
77
|
+
description=t("help.description"),
|
|
78
|
+
epilog=t("help.epilog"),
|
|
79
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
80
|
+
)
|
|
81
|
+
parser.add_argument("-h", "--help", action="help", help=t("help.help"))
|
|
82
|
+
parser.add_argument("--version", action="version", version=f"owui-deploy {__version__}", help=t("help.version"))
|
|
83
|
+
parser.add_argument("--lang", choices=i18n.SUPPORTED, default=None, help=t("help.lang"))
|
|
84
|
+
sub = parser.add_subparsers(dest="command", metavar="{lint,pull,plan,apply}", required=True)
|
|
85
|
+
|
|
86
|
+
def add(name: str, parents: list[argparse.ArgumentParser], help_key: str) -> argparse.ArgumentParser:
|
|
87
|
+
p = sub.add_parser(name, parents=parents, add_help=False, help=t(help_key), description=t(help_key))
|
|
88
|
+
p.add_argument("-h", "--help", action="help", help=t("help.help"))
|
|
89
|
+
return p
|
|
90
|
+
|
|
91
|
+
p_lint = add("lint", [common, ], "help.lint")
|
|
92
|
+
p_lint.add_argument("--config", metavar="PATH", help=t("help.config", name=DEFAULT_CONFIG_NAME))
|
|
93
|
+
p_lint.add_argument("path", nargs="?", metavar="PATH", help=t("help.lint_path"))
|
|
94
|
+
p_lint.add_argument("--json", action="store_true", help=t("help.json"))
|
|
95
|
+
p_lint.add_argument("--strict", action="store_true", help=t("help.strict"))
|
|
96
|
+
|
|
97
|
+
p_plan = add("plan", [server], "help.plan")
|
|
98
|
+
p_plan.add_argument("--diff", action="store_true", help=t("help.diff"))
|
|
99
|
+
p_plan.add_argument("--json", action="store_true", help=t("help.json"))
|
|
100
|
+
p_plan.add_argument("--prune", action="store_true", help=t("help.prune_plan"))
|
|
101
|
+
p_plan.add_argument("--fail-on-unmanaged", action="store_true", help=t("help.fail_on_unmanaged"))
|
|
102
|
+
|
|
103
|
+
p_apply = add("apply", [server], "help.apply")
|
|
104
|
+
p_apply.add_argument("--yes", "-y", action="store_true", help=t("help.yes"))
|
|
105
|
+
p_apply.add_argument("--prune", action="store_true", help=t("help.prune_apply"))
|
|
106
|
+
p_apply.add_argument("--message", "-m", metavar="TEXT", help=t("help.message"))
|
|
107
|
+
|
|
108
|
+
p_pull = add("pull", [common], "help.pull")
|
|
109
|
+
p_pull.add_argument("--out", metavar="DIR", default=".", help=t("help.out"))
|
|
110
|
+
p_pull.add_argument("--url", metavar="URL", help=t("help.url"))
|
|
111
|
+
p_pull.add_argument("--fake", action="store_true", help=t("help.fake"))
|
|
112
|
+
p_pull.add_argument("--force", action="store_true", help=t("help.force"))
|
|
113
|
+
return parser
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
# -- helpers ---------------------------------------------------------------------------------
|
|
117
|
+
def _load_cfg(args: argparse.Namespace) -> Config:
|
|
118
|
+
path = Path(args.config) if args.config else Path.cwd() / DEFAULT_CONFIG_NAME
|
|
119
|
+
return load_config(path)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _open_client(args: argparse.Namespace, base_dir: Path, cfg_url: str | None) -> tuple[OpenWebUIClient, str, bool]:
|
|
123
|
+
"""Return ``(client, server label, is_mock)``; the mock needs no URL or token."""
|
|
124
|
+
if args.fake:
|
|
125
|
+
state_path = base_dir / FAKE_STATE_NAME
|
|
126
|
+
try:
|
|
127
|
+
shown = state_path.resolve().relative_to(Path.cwd().resolve())
|
|
128
|
+
except ValueError:
|
|
129
|
+
shown = state_path
|
|
130
|
+
fake = FakeOpenWebUI(state_path=state_path)
|
|
131
|
+
return OpenWebUIClient("http://fake.invalid", "fake", transport=fake.transport()), f"fake ({shown})", True
|
|
132
|
+
url = args.url or os.environ.get("OWUI_URL") or cfg_url
|
|
133
|
+
if not url:
|
|
134
|
+
raise ToolError(t("err.no_url"))
|
|
135
|
+
token = os.environ.get("OWUI_TOKEN")
|
|
136
|
+
if not token:
|
|
137
|
+
raise ToolError(t("err.no_token"))
|
|
138
|
+
return OpenWebUIClient(url, token), url, False
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _banner(label: str, mock: bool, to_stderr: bool = False) -> None:
|
|
142
|
+
stream = sys.stderr if to_stderr else sys.stdout
|
|
143
|
+
if mock:
|
|
144
|
+
print(t("fake.banner", state=label.removeprefix("fake (").removesuffix(")")), file=stream)
|
|
145
|
+
else:
|
|
146
|
+
print(t("plan.server", url=label), file=stream)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _remote(client: OpenWebUIClient) -> dict[str, list[dict]]:
|
|
150
|
+
return {kind: client.export_all(kind) for kind in ("tool", "function")}
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _plan(args: argparse.Namespace, prune: bool) -> tuple[Plan, list, OpenWebUIClient, str, bool, Config]:
|
|
154
|
+
cfg = _load_cfg(args)
|
|
155
|
+
desired, skipped = build_desired(cfg)
|
|
156
|
+
client, label, mock = _open_client(args, cfg.base_dir, cfg.url)
|
|
157
|
+
try:
|
|
158
|
+
plan = build_plan(desired, skipped, _remote(client), prune=prune)
|
|
159
|
+
except BaseException:
|
|
160
|
+
client.close() # do not leak the connection when the server cannot be read
|
|
161
|
+
raise
|
|
162
|
+
return plan, desired, client, label, mock, cfg
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
# -- commands --------------------------------------------------------------------------------
|
|
166
|
+
def cmd_lint(args: argparse.Namespace) -> int:
|
|
167
|
+
if args.path:
|
|
168
|
+
root = Path(args.path)
|
|
169
|
+
else:
|
|
170
|
+
config_path = Path(args.config) if args.config else Path.cwd() / DEFAULT_CONFIG_NAME
|
|
171
|
+
root = Path.cwd()
|
|
172
|
+
if args.config or config_path.is_file():
|
|
173
|
+
cfg = load_config(config_path)
|
|
174
|
+
return _lint_config(cfg, args)
|
|
175
|
+
if not root.exists():
|
|
176
|
+
raise ToolError(t("lint.path_missing", path=str(root)))
|
|
177
|
+
findings, files = lint_path(root)
|
|
178
|
+
if files == 0:
|
|
179
|
+
raise ToolError(t("lint.no_files", path=str(root)))
|
|
180
|
+
return _lint_report(findings, files, args)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _lint_config(cfg: Config, args: argparse.Namespace) -> int:
|
|
184
|
+
findings = []
|
|
185
|
+
files = 0
|
|
186
|
+
for folder, kind in ((cfg.tools_dir, "tools"), (cfg.functions_dir, "functions")):
|
|
187
|
+
if not folder.is_dir():
|
|
188
|
+
continue
|
|
189
|
+
for file in sorted(folder.glob("*.py")):
|
|
190
|
+
if file.name.startswith("__"):
|
|
191
|
+
continue
|
|
192
|
+
files += 1
|
|
193
|
+
display = file.relative_to(cfg.base_dir).as_posix() if file.is_relative_to(cfg.base_dir) else str(file)
|
|
194
|
+
source = file.read_text(encoding="utf-8", errors="replace")
|
|
195
|
+
findings.extend(lint_source(display, kind, source, file_stem=file.stem))
|
|
196
|
+
if files == 0:
|
|
197
|
+
raise ToolError(t("lint.no_files", path=str(cfg.base_dir)))
|
|
198
|
+
return _lint_report(findings, files, args)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _lint_report(findings: list, files: int, args: argparse.Namespace) -> int:
|
|
202
|
+
if args.json:
|
|
203
|
+
print(render.lint_json(findings, files))
|
|
204
|
+
else:
|
|
205
|
+
for finding in findings:
|
|
206
|
+
print(render.finding_text(finding))
|
|
207
|
+
print(render.lint_summary(findings, files))
|
|
208
|
+
errors = any(f.level == "error" for f in findings)
|
|
209
|
+
warnings = any(f.level == "warning" for f in findings)
|
|
210
|
+
return 1 if errors or (args.strict and warnings) else 0
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def cmd_plan(args: argparse.Namespace) -> int:
|
|
214
|
+
plan, _desired, client, label, mock, _cfg = _plan(args, prune=args.prune)
|
|
215
|
+
with client:
|
|
216
|
+
if args.json:
|
|
217
|
+
if mock:
|
|
218
|
+
_banner(label, mock, to_stderr=True)
|
|
219
|
+
print(render.plan_json(plan, mock, label, show_diff=args.diff))
|
|
220
|
+
else:
|
|
221
|
+
_banner(label, mock)
|
|
222
|
+
print(render.plan_text(plan, show_diff=args.diff))
|
|
223
|
+
return 1 if plan.has_drift(args.fail_on_unmanaged) else 0
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _confirm() -> bool:
|
|
227
|
+
answer = input(t("apply.confirm"))
|
|
228
|
+
return answer.strip().lower() in ("y", "yes")
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def cmd_apply(args: argparse.Namespace) -> int:
|
|
232
|
+
plan, desired, client, label, mock, cfg = _plan(args, prune=args.prune)
|
|
233
|
+
with client:
|
|
234
|
+
_banner(label, mock)
|
|
235
|
+
print(render.plan_text(plan))
|
|
236
|
+
skipped = plan.summary["skipped"]
|
|
237
|
+
if not plan.writes:
|
|
238
|
+
print(t("apply.nothing"))
|
|
239
|
+
return 1 if skipped else 0
|
|
240
|
+
if not args.yes:
|
|
241
|
+
if not sys.stdin.isatty():
|
|
242
|
+
raise ToolError(t("apply.need_yes"))
|
|
243
|
+
if not _confirm():
|
|
244
|
+
print(t("apply.cancelled"))
|
|
245
|
+
return 1
|
|
246
|
+
message = args.message or git_short_hash(cfg.base_dir)
|
|
247
|
+
result = apply_plan(client, plan, desired, message=message)
|
|
248
|
+
for line in render.apply_lines(result):
|
|
249
|
+
print(line)
|
|
250
|
+
for rejection in result.rejected:
|
|
251
|
+
item = next((d for d in desired if d.kind == rejection.kind and d.id == rejection.id), None)
|
|
252
|
+
hints = []
|
|
253
|
+
if item is not None:
|
|
254
|
+
kind_dir = "tools" if item.kind == "tool" else "functions"
|
|
255
|
+
hints = [f for f in lint_source(item.path.name, kind_dir, item.content, file_stem=item.path.stem) if f.level == "error"]
|
|
256
|
+
if hints:
|
|
257
|
+
for finding in hints:
|
|
258
|
+
print(t("apply.hint_line", text=render.finding_text(finding)))
|
|
259
|
+
else:
|
|
260
|
+
print(t("apply.hint_generic", kind=rejection.kind, id=rejection.id))
|
|
261
|
+
print(t("apply.summary", done=len(result.done), rejected=len(result.rejected)))
|
|
262
|
+
return 1 if result.rejected or skipped else 0
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def cmd_pull(args: argparse.Namespace) -> int:
|
|
266
|
+
out = Path(args.out)
|
|
267
|
+
config_path = out / DEFAULT_CONFIG_NAME
|
|
268
|
+
cfg_url = None
|
|
269
|
+
if config_path.is_file():
|
|
270
|
+
cfg_url = load_config(config_path).url
|
|
271
|
+
client, label, mock = _open_client(args, out, cfg_url)
|
|
272
|
+
with client:
|
|
273
|
+
_banner(label, mock)
|
|
274
|
+
result = run_pull(client, out, config_path, url=None if mock else (args.url or os.environ.get("OWUI_URL") or cfg_url), force=args.force)
|
|
275
|
+
for item in result.written:
|
|
276
|
+
print(t("pull.written", item=item))
|
|
277
|
+
for item in result.kept:
|
|
278
|
+
print(t("pull.kept", item=item))
|
|
279
|
+
for item in result.invalid_ids:
|
|
280
|
+
print(t("pull.invalid_id", item=item))
|
|
281
|
+
print(t("pull.summary", written=len(result.written), unchanged=len(result.unchanged), kept=len(result.kept)))
|
|
282
|
+
if result.config_written:
|
|
283
|
+
print(t("pull.config_written", path=str(result.config_written)))
|
|
284
|
+
if result.config_kept:
|
|
285
|
+
print(t("pull.config_kept", path=str(result.config_kept)))
|
|
286
|
+
for kind, item_id, field_name, want, have in result.state_differences:
|
|
287
|
+
print(t("pull.state_diff", item=f"{kind}:{item_id}", field=field_name,
|
|
288
|
+
want=str(want).lower(), have=str(have).lower()))
|
|
289
|
+
if result.valves_dropped:
|
|
290
|
+
print(t("pull.valves_dropped", n=result.valves_dropped))
|
|
291
|
+
else:
|
|
292
|
+
print(t("pull.valves_note"))
|
|
293
|
+
return 0
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
COMMANDS = {"lint": cmd_lint, "plan": cmd_plan, "apply": cmd_apply, "pull": cmd_pull}
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
300
|
+
"""Run the CLI and return the exit code (never raises for expected errors)."""
|
|
301
|
+
args_list = list(sys.argv[1:] if argv is None else argv)
|
|
302
|
+
i18n.set_lang(i18n.resolve_lang(_preparse_lang(args_list), os.environ))
|
|
303
|
+
_localize_argparse(i18n.get_lang())
|
|
304
|
+
try:
|
|
305
|
+
parser = build_parser()
|
|
306
|
+
args = parser.parse_args(args_list)
|
|
307
|
+
return COMMANDS[args.command](args)
|
|
308
|
+
except SystemExit as exc: # argparse: --help (0) or usage error (2)
|
|
309
|
+
return int(exc.code or 0)
|
|
310
|
+
except ToolError as exc:
|
|
311
|
+
print(f"owui-deploy: {t('err.prefix')}: {exc.message}", file=sys.stderr)
|
|
312
|
+
return 2
|
|
313
|
+
except KeyboardInterrupt:
|
|
314
|
+
print(f"owui-deploy: {t('err.interrupted')}", file=sys.stderr)
|
|
315
|
+
return 2
|
|
316
|
+
except Exception as exc: # noqa: BLE001 - last resort: a readable line instead of a traceback
|
|
317
|
+
if os.environ.get("OWUI_DEPLOY_DEBUG"):
|
|
318
|
+
traceback.print_exc()
|
|
319
|
+
print(f"owui-deploy: {t('err.prefix')}: {t('err.internal', detail=f'{type(exc).__name__}: {exc}')}", file=sys.stderr)
|
|
320
|
+
return 2
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
if __name__ == "__main__":
|
|
324
|
+
sys.exit(main())
|
owui_deploy/client.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""Thin Open WebUI admin API client (``/api/v1/tools`` and ``/api/v1/functions``)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import httpx
|
|
6
|
+
|
|
7
|
+
from .errors import ApiError, AuthError, OwuiConnectionError, ToolError
|
|
8
|
+
from .i18n import t
|
|
9
|
+
|
|
10
|
+
_REQUIRED = {"id", "name", "content", "is_active"}
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _detail(response: httpx.Response) -> str:
|
|
14
|
+
try:
|
|
15
|
+
body = response.json()
|
|
16
|
+
except ValueError:
|
|
17
|
+
return response.text[:200]
|
|
18
|
+
if isinstance(body, dict) and "detail" in body:
|
|
19
|
+
return str(body["detail"])
|
|
20
|
+
return str(body)[:200]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class OpenWebUIClient:
|
|
24
|
+
"""One method per endpoint the tool needs. It never calls ``/functions/sync``."""
|
|
25
|
+
|
|
26
|
+
def __init__(
|
|
27
|
+
self,
|
|
28
|
+
base_url: str,
|
|
29
|
+
token: str,
|
|
30
|
+
transport: httpx.BaseTransport | None = None,
|
|
31
|
+
timeout: float = 120.0,
|
|
32
|
+
) -> None:
|
|
33
|
+
self.base_url = base_url.rstrip("/")
|
|
34
|
+
self._http = httpx.Client(
|
|
35
|
+
base_url=self.base_url,
|
|
36
|
+
headers={"Authorization": f"Bearer {token}"},
|
|
37
|
+
transport=transport,
|
|
38
|
+
timeout=timeout,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
def close(self) -> None:
|
|
42
|
+
self._http.close()
|
|
43
|
+
|
|
44
|
+
def __enter__(self) -> "OpenWebUIClient":
|
|
45
|
+
return self
|
|
46
|
+
|
|
47
|
+
def __exit__(self, *exc: object) -> None:
|
|
48
|
+
self.close()
|
|
49
|
+
|
|
50
|
+
# -- low level ---------------------------------------------------------------------------
|
|
51
|
+
def _request(self, method: str, path: str, **kwargs: object) -> object:
|
|
52
|
+
try:
|
|
53
|
+
response = self._http.request(method, path, **kwargs) # type: ignore[arg-type]
|
|
54
|
+
except (httpx.InvalidURL, httpx.UnsupportedProtocol) as exc:
|
|
55
|
+
raise ToolError(t("err.bad_url", url=self.base_url)) from exc
|
|
56
|
+
except httpx.TransportError as exc:
|
|
57
|
+
raise OwuiConnectionError(t("err.connect", url=self.base_url, detail=str(exc) or type(exc).__name__)) from exc
|
|
58
|
+
if response.status_code in (401, 403):
|
|
59
|
+
raise AuthError(t("err.auth", status=response.status_code, detail=_detail(response)), response.status_code)
|
|
60
|
+
if response.status_code >= 400:
|
|
61
|
+
raise ApiError(response.status_code, _detail(response), method, path)
|
|
62
|
+
try:
|
|
63
|
+
return response.json()
|
|
64
|
+
except ValueError as exc:
|
|
65
|
+
raise ToolError(t("err.not_json", url=self.base_url, path=path)) from exc
|
|
66
|
+
|
|
67
|
+
@staticmethod
|
|
68
|
+
def _base(kind: str) -> str:
|
|
69
|
+
return "/api/v1/tools" if kind == "tool" else "/api/v1/functions"
|
|
70
|
+
|
|
71
|
+
# -- endpoints ---------------------------------------------------------------------------
|
|
72
|
+
def export_all(self, kind: str) -> list[dict]:
|
|
73
|
+
"""Every item of ``kind`` including its source (valves are not requested)."""
|
|
74
|
+
data = self._request("GET", f"{self._base(kind)}/export")
|
|
75
|
+
if not isinstance(data, list):
|
|
76
|
+
raise ToolError(t("err.unexpected", url=self.base_url))
|
|
77
|
+
for entry in data:
|
|
78
|
+
if not isinstance(entry, dict) or not _REQUIRED <= set(entry):
|
|
79
|
+
raise ToolError(t("err.unexpected", url=self.base_url))
|
|
80
|
+
return data
|
|
81
|
+
|
|
82
|
+
def get(self, kind: str, item_id: str) -> dict:
|
|
83
|
+
data = self._request("GET", f"{self._base(kind)}/id/{item_id}")
|
|
84
|
+
if not isinstance(data, dict):
|
|
85
|
+
raise ToolError(t("err.unexpected", url=self.base_url))
|
|
86
|
+
return data
|
|
87
|
+
|
|
88
|
+
def create(self, kind: str, payload: dict) -> dict:
|
|
89
|
+
return self._request("POST", f"{self._base(kind)}/create", json=payload) # type: ignore[return-value]
|
|
90
|
+
|
|
91
|
+
def update(self, kind: str, item_id: str, payload: dict) -> dict:
|
|
92
|
+
return self._request("POST", f"{self._base(kind)}/id/{item_id}/update", json=payload) # type: ignore[return-value]
|
|
93
|
+
|
|
94
|
+
def toggle(self, kind: str, item_id: str) -> dict:
|
|
95
|
+
return self._request("POST", f"{self._base(kind)}/id/{item_id}/toggle") # type: ignore[return-value]
|
|
96
|
+
|
|
97
|
+
def toggle_global(self, item_id: str) -> dict:
|
|
98
|
+
return self._request("POST", f"/api/v1/functions/id/{item_id}/toggle/global") # type: ignore[return-value]
|
|
99
|
+
|
|
100
|
+
def delete(self, kind: str, item_id: str) -> object:
|
|
101
|
+
return self._request("DELETE", f"{self._base(kind)}/id/{item_id}/delete")
|