writune 0.1.1__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.
Files changed (61) hide show
  1. writune/__init__.py +6 -0
  2. writune/__main__.py +7 -0
  3. writune/cli.py +750 -0
  4. writune/config.py +604 -0
  5. writune/files/__init__.py +7 -0
  6. writune/files/apply.py +270 -0
  7. writune/files/atomic.py +79 -0
  8. writune/files/docx.py +157 -0
  9. writune/files/temporary.py +17 -0
  10. writune/files/text.py +61 -0
  11. writune/files/workspace.py +71 -0
  12. writune/mcp_server.py +274 -0
  13. writune/polishing/__init__.py +18 -0
  14. writune/polishing/errors.py +9 -0
  15. writune/polishing/prompt.py +255 -0
  16. writune/polishing/prompts.py +5 -0
  17. writune/polishing/protect.py +435 -0
  18. writune/polishing/protected_spans.py +5 -0
  19. writune/polishing/segmentation.py +109 -0
  20. writune/polishing/validate.py +115 -0
  21. writune/polishing/validation.py +6 -0
  22. writune/providers/__init__.py +16 -0
  23. writune/providers/base.py +5 -0
  24. writune/providers/errors.py +42 -0
  25. writune/providers/registry.py +90 -0
  26. writune/providers/responses.py +592 -0
  27. writune/providers/tps.py +161 -0
  28. writune/runtime.py +65 -0
  29. writune/schemas.py +176 -0
  30. writune/service.py +420 -0
  31. writune/tasks/__init__.py +1 -0
  32. writune/tasks/artifacts.py +43 -0
  33. writune/tasks/database.py +141 -0
  34. writune/tasks/eta.py +111 -0
  35. writune/tasks/lifecycle.py +88 -0
  36. writune/tasks/process_lock.py +46 -0
  37. writune/tasks/protocol.py +13 -0
  38. writune/tasks/worker.py +259 -0
  39. writune/telemetry/__init__.py +1 -0
  40. writune/telemetry/metrics.py +29 -0
  41. writune/update-manifest.json +66 -0
  42. writune/updates.py +364 -0
  43. writune-0.1.1.data/data/share/writune/INSTALL_PROMPT.md +153 -0
  44. writune-0.1.1.data/data/share/writune/MANUAL_INSTALL.md +108 -0
  45. writune-0.1.1.data/data/share/writune/MANUAL_INSTALL.zh-CN.md +106 -0
  46. writune-0.1.1.data/data/share/writune/README.en.md +358 -0
  47. writune-0.1.1.data/data/share/writune/README.md +356 -0
  48. writune-0.1.1.data/data/share/writune/skills/writune-polish/SKILL.md +26 -0
  49. writune-0.1.1.data/data/share/writune/skills/writune-polish/agents/openai.yaml +2 -0
  50. writune-0.1.1.data/data/share/writune/skills/writune-polish/references/error-handling.md +30 -0
  51. writune-0.1.1.data/data/share/writune/skills/writune-polish/references/file-handoff.md +27 -0
  52. writune-0.1.1.data/data/share/writune/skills/writune-polish/references/sepia-license.md +26 -0
  53. writune-0.1.1.data/data/share/writune/skills/writune-polish/references/sepia-method.md +38 -0
  54. writune-0.1.1.data/data/share/writune/skills/writune-polish/references/style-profiles.md +36 -0
  55. writune-0.1.1.data/data/share/writune/skills/writune-polish/references/workflows.md +42 -0
  56. writune-0.1.1.dist-info/METADATA +385 -0
  57. writune-0.1.1.dist-info/RECORD +61 -0
  58. writune-0.1.1.dist-info/WHEEL +5 -0
  59. writune-0.1.1.dist-info/entry_points.txt +2 -0
  60. writune-0.1.1.dist-info/licenses/LICENSE +21 -0
  61. writune-0.1.1.dist-info/top_level.txt +1 -0
writune/cli.py ADDED
@@ -0,0 +1,750 @@
1
+ """Typer command-line interface backed by the shared Writune service."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import importlib.metadata
7
+ import json
8
+ import os
9
+ import sys
10
+ from pathlib import Path
11
+ from typing import Any
12
+ from urllib.parse import urlsplit, urlunsplit
13
+
14
+ import typer
15
+ from pydantic import SecretStr, ValidationError
16
+
17
+ from writune.config import ProviderConfig, Settings
18
+ from writune.service import Service, split_model
19
+
20
+ app = typer.Typer(name="writune", no_args_is_help=True, help="Asynchronous AI writing polisher")
21
+ config_app = typer.Typer(name="config", no_args_is_help=True, help="Inspect or update Writune settings")
22
+ app.add_typer(config_app, name="config")
23
+
24
+
25
+ def _settings(home: Path | None) -> Settings:
26
+ return Settings.load(home)
27
+
28
+
29
+ def _service(home: Path | None, *, start_worker: bool = True) -> Service:
30
+ from writune.updates import UpdatingService
31
+ return UpdatingService(_settings(home), start_worker=start_worker)
32
+
33
+
34
+ def _model_ref(provider_name: str, model_name: str) -> str:
35
+ if not model_name:
36
+ return ""
37
+ return model_name if "/" in model_name else f"{provider_name}/{model_name}"
38
+
39
+
40
+ def _url_with_port(value: str, port: int | None) -> str:
41
+ url = value.strip()
42
+ if not url:
43
+ return ""
44
+ parts = urlsplit(url)
45
+ if parts.scheme not in {"http", "https"} or not parts.hostname:
46
+ raise ValueError("provider URL must be an absolute http or https URL")
47
+ if port is None:
48
+ return url.rstrip("/")
49
+ host = parts.hostname
50
+ if ":" in host and not host.startswith("["):
51
+ host = f"[{host}]"
52
+ netloc = f"{host}:{port}"
53
+ return urlunsplit((parts.scheme, netloc, parts.path.rstrip("/"), parts.query, parts.fragment))
54
+
55
+
56
+ def _read_json(path: Path) -> dict[str, Any]:
57
+ try:
58
+ value = json.loads(path.read_text(encoding="utf-8"))
59
+ except (OSError, json.JSONDecodeError) as exc:
60
+ raise typer.BadParameter(f"could not read JSON config file: {exc}") from exc
61
+ if not isinstance(value, dict):
62
+ raise typer.BadParameter("config file must contain a JSON object")
63
+ return value
64
+
65
+
66
+ def _merge_dicts(base: dict[str, Any], update: dict[str, Any]) -> dict[str, Any]:
67
+ """Merge nested config objects so partial CLI config files keep defaults."""
68
+
69
+ merged = dict(base)
70
+ for key, value in update.items():
71
+ current = merged.get(key)
72
+ if isinstance(current, dict) and isinstance(value, dict):
73
+ merged[key] = _merge_dicts(current, value)
74
+ else:
75
+ merged[key] = value
76
+ return merged
77
+
78
+
79
+ def _init_settings(
80
+ *,
81
+ home: Path | None,
82
+ config_file: Path | None,
83
+ non_interactive: bool,
84
+ primary_url: str | None,
85
+ primary_port: int | None,
86
+ api_key: str | None,
87
+ backup_url: str | None,
88
+ backup_port: int | None,
89
+ backup_api_key: str | None,
90
+ zh_primary_model: str | None,
91
+ zh_fallback_model: str | None,
92
+ en_primary_model: str | None,
93
+ en_fallback_model: str | None,
94
+ default_style: str | None,
95
+ max_concurrency: int | None,
96
+ connect_timeout: float | None,
97
+ first_token_timeout: float | None,
98
+ min_tps: float | None,
99
+ inactivity_timeout: float | None,
100
+ total_timeout: float | None,
101
+ retry_count: int | None,
102
+ data_dir: Path | None,
103
+ task_ttl_hours: float | None,
104
+ allowed_workspaces: list[Path] | None,
105
+ ) -> Settings:
106
+ existing = Settings.load(home)
107
+ payload: dict[str, Any] = existing.model_dump(mode="python") if existing.config_path.exists() else {}
108
+ if config_file is not None:
109
+ payload = _merge_dicts(payload, _read_json(config_file))
110
+ # Preserve Settings.load's environment-over-JSON secret precedence even
111
+ # when the explicit input JSON is outside Writune's config directory.
112
+ providers = dict(payload.get("providers") or {})
113
+ for provider_name, configured in existing.providers.items():
114
+ secret = configured.api_key.get_secret_value()
115
+ if not secret:
116
+ continue
117
+ current = providers.get(provider_name)
118
+ current_data = current.model_dump(mode="python") if isinstance(current, ProviderConfig) else dict(current or {})
119
+ current_data["api_key"] = SecretStr(secret)
120
+ providers[provider_name] = current_data
121
+ payload["providers"] = providers
122
+
123
+ explicit = {
124
+ "default_style": default_style,
125
+ "max_concurrency": max_concurrency,
126
+ "connect_timeout": connect_timeout,
127
+ "first_token_timeout": first_token_timeout,
128
+ "min_tps": min_tps,
129
+ "inactivity_timeout": inactivity_timeout,
130
+ "total_timeout": total_timeout,
131
+ "retry_count": retry_count,
132
+ "data_dir": data_dir,
133
+ "task_ttl_hours": task_ttl_hours,
134
+ "allowed_workspaces": allowed_workspaces,
135
+ }
136
+ payload.update({key: value for key, value in explicit.items() if value is not None})
137
+
138
+ has_cli_provider_fields = any(
139
+ value is not None
140
+ for value in (primary_url, primary_port, api_key, backup_url, backup_port, backup_api_key)
141
+ )
142
+ if non_interactive:
143
+ if config_file is None and not (primary_url and api_key and zh_primary_model and en_primary_model):
144
+ raise typer.BadParameter(
145
+ "--non-interactive requires --config-file or --primary-url, --api-key, "
146
+ "--zh-primary-model, and --en-primary-model"
147
+ )
148
+ if has_cli_provider_fields:
149
+ current_primary = payload.get("providers", {}).get("primary", {})
150
+ if isinstance(current_primary, ProviderConfig):
151
+ current_primary = current_primary.model_dump(mode="python")
152
+ current_primary = dict(current_primary or {})
153
+ resolved_primary_url = primary_url or current_primary.get("base_url", "")
154
+ resolved_primary_key = api_key or current_primary.get("api_key", "")
155
+ if isinstance(resolved_primary_key, SecretStr):
156
+ resolved_primary_key = resolved_primary_key.get_secret_value()
157
+ if not (resolved_primary_url and resolved_primary_key):
158
+ raise typer.BadParameter(
159
+ "a primary URL and API key are required; use --primary-url/--api-key or provide them via config/.env"
160
+ )
161
+ current_backup = payload.get("providers", {}).get("backup", {})
162
+ if isinstance(current_backup, ProviderConfig):
163
+ current_backup = current_backup.model_dump(mode="python")
164
+ resolved_backup_url = backup_url
165
+ if resolved_backup_url is None and (backup_port is not None or backup_api_key is not None):
166
+ resolved_backup_url = dict(current_backup or {}).get("base_url")
167
+ _merge_provider_options(
168
+ payload,
169
+ resolved_primary_url,
170
+ primary_port,
171
+ resolved_primary_key,
172
+ resolved_backup_url,
173
+ backup_port,
174
+ backup_api_key,
175
+ )
176
+ for field, value in (
177
+ ("zh_primary", _model_ref("primary", zh_primary_model) if zh_primary_model else None),
178
+ ("zh_secondary", _model_ref("backup", zh_fallback_model) if zh_fallback_model is not None else None),
179
+ ("en_primary", _model_ref("primary", en_primary_model) if en_primary_model else None),
180
+ ("en_secondary", _model_ref("backup", en_fallback_model) if en_fallback_model is not None else None),
181
+ ):
182
+ if value is not None:
183
+ payload[field] = value
184
+ settings = Settings(**payload)
185
+ _require_initialized(settings)
186
+ settings.save(home)
187
+ return settings
188
+
189
+ if config_file is None:
190
+ primary_url = primary_url or typer.prompt("Primary upstream URL", default="http://127.0.0.1/v1")
191
+ parsed = urlsplit(primary_url)
192
+ default_primary_port = parsed.port or (443 if parsed.scheme == "https" else 8317)
193
+ primary_port = primary_port if primary_port is not None else typer.prompt(
194
+ "Primary upstream port", default=default_primary_port, type=int
195
+ )
196
+ api_key = api_key if api_key is not None else typer.prompt("Primary API key", hide_input=True)
197
+ backup_url = backup_url if backup_url is not None else typer.prompt(
198
+ "Backup upstream URL (leave blank to disable)", default=""
199
+ )
200
+ if backup_url:
201
+ backup_parts = urlsplit(backup_url)
202
+ backup_port = backup_port if backup_port is not None else typer.prompt(
203
+ "Backup upstream port", default=backup_parts.port or (443 if backup_parts.scheme == "https" else 8318), type=int
204
+ )
205
+ backup_api_key = backup_api_key if backup_api_key is not None else typer.prompt(
206
+ "Backup API key (blank to reuse primary key)", hide_input=True, default=""
207
+ )
208
+ zh_primary_model = zh_primary_model or typer.prompt("Chinese primary model")
209
+ zh_fallback_model = zh_fallback_model if zh_fallback_model is not None else typer.prompt(
210
+ "Chinese fallback model (blank to disable)", default=""
211
+ )
212
+ en_primary_model = en_primary_model or typer.prompt("English primary model")
213
+ en_fallback_model = en_fallback_model if en_fallback_model is not None else typer.prompt(
214
+ "English fallback model (blank to disable)", default=""
215
+ )
216
+ default_style = default_style or typer.prompt("Default polishing style", default="natural")
217
+ max_concurrency = max_concurrency if max_concurrency is not None else typer.prompt("Max concurrency", default=4, type=int)
218
+ connect_timeout = connect_timeout if connect_timeout is not None else typer.prompt("Connect timeout (seconds)", default=8.0, type=float)
219
+ first_token_timeout = first_token_timeout if first_token_timeout is not None else typer.prompt("First text token timeout (seconds)", default=25.0, type=float)
220
+ min_tps = min_tps if min_tps is not None else typer.prompt("Minimum TPS", default=6.0, type=float)
221
+ inactivity_timeout = inactivity_timeout if inactivity_timeout is not None else typer.prompt("Generation inactivity timeout (seconds)", default=20.0, type=float)
222
+ total_timeout = total_timeout if total_timeout is not None else typer.prompt("Total request timeout (seconds)", default=120.0, type=float)
223
+ retry_count = retry_count if retry_count is not None else typer.prompt("Retry count", default=1, type=int)
224
+ data_dir = data_dir or Path(typer.prompt("Queue and statistics directory (task files use OS temp)", default=str(existing.data_dir)))
225
+ task_ttl_hours = task_ttl_hours if task_ttl_hours is not None else typer.prompt("Task file retention (hours)", default=24.0, type=float)
226
+ workspace_text = typer.prompt(
227
+ "Allowed workspace directories (separate multiple paths with semicolons)",
228
+ default=";".join(str(path) for path in existing.allowed_workspaces),
229
+ )
230
+ allowed_workspaces = allowed_workspaces if allowed_workspaces is not None else [
231
+ Path(part.strip()) for part in workspace_text.split(";") if part.strip()
232
+ ]
233
+
234
+ if has_cli_provider_fields or config_file is None:
235
+ if not primary_url or not api_key:
236
+ raise typer.BadParameter("a primary URL and API key are required")
237
+ _merge_provider_options(payload, primary_url, primary_port, api_key, backup_url, backup_port, backup_api_key)
238
+ for field, value in (
239
+ ("zh_primary", _model_ref("primary", zh_primary_model or "")),
240
+ ("zh_secondary", _model_ref("backup", zh_fallback_model or "")),
241
+ ("en_primary", _model_ref("primary", en_primary_model or "")),
242
+ ("en_secondary", _model_ref("backup", en_fallback_model or "")),
243
+ ):
244
+ if value:
245
+ payload[field] = value
246
+ for key, value in (
247
+ ("default_style", default_style),
248
+ ("max_concurrency", max_concurrency),
249
+ ("connect_timeout", connect_timeout),
250
+ ("first_token_timeout", first_token_timeout),
251
+ ("min_tps", min_tps),
252
+ ("inactivity_timeout", inactivity_timeout),
253
+ ("total_timeout", total_timeout),
254
+ ("retry_count", retry_count),
255
+ ("data_dir", data_dir),
256
+ ("task_ttl_hours", task_ttl_hours),
257
+ ("allowed_workspaces", allowed_workspaces),
258
+ ):
259
+ if value is not None:
260
+ payload[key] = value
261
+ settings = Settings(**payload)
262
+ _require_initialized(settings)
263
+ settings.save(home)
264
+ return settings
265
+
266
+
267
+ def _merge_provider_options(
268
+ payload: dict[str, Any],
269
+ primary_url: str,
270
+ primary_port: int | None,
271
+ api_key: str,
272
+ backup_url: str | None,
273
+ backup_port: int | None,
274
+ backup_api_key: str | None,
275
+ ) -> None:
276
+ providers = dict(payload.get("providers") or {})
277
+
278
+ def provider_values(name: str) -> dict[str, Any]:
279
+ current = providers.get(name)
280
+ if isinstance(current, ProviderConfig):
281
+ return current.model_dump(mode="python")
282
+ if isinstance(current, dict):
283
+ return dict(current)
284
+ return {}
285
+
286
+ primary_values = provider_values("primary")
287
+ primary_values.update(base_url=_url_with_port(primary_url, primary_port), api_key=SecretStr(api_key))
288
+ providers["primary"] = ProviderConfig(**primary_values)
289
+ if backup_url:
290
+ backup_values = provider_values("backup")
291
+ backup_key: str | SecretStr | None
292
+ if backup_api_key is not None:
293
+ backup_key = backup_api_key or api_key
294
+ else:
295
+ backup_key = backup_values.get("api_key") or api_key
296
+ backup_values.update(
297
+ base_url=_url_with_port(backup_url, backup_port),
298
+ api_key=SecretStr(backup_key) if isinstance(backup_key, str) else backup_key,
299
+ )
300
+ providers["backup"] = ProviderConfig(**backup_values)
301
+ elif backup_url == "" and "backup" in providers:
302
+ providers.pop("backup")
303
+ payload["providers"] = providers
304
+
305
+
306
+ def _require_initialized(settings: Settings) -> None:
307
+ missing = []
308
+ if not settings.zh_primary:
309
+ missing.append("Chinese primary model")
310
+ if not settings.en_primary:
311
+ missing.append("English primary model")
312
+ for label, model_ref in (
313
+ ("Chinese primary", settings.zh_primary),
314
+ ("Chinese fallback", settings.zh_secondary),
315
+ ("English primary", settings.en_primary),
316
+ ("English fallback", settings.en_secondary),
317
+ ):
318
+ if not model_ref:
319
+ continue
320
+ try:
321
+ provider_name, _ = split_model(model_ref)
322
+ provider = settings.providers.get(provider_name)
323
+ except ValueError:
324
+ provider = None
325
+ provider_name = "unknown"
326
+ if not provider or not provider.base_url:
327
+ missing.append(f"{label} model provider URL ({provider_name})")
328
+ elif not provider.api_key.get_secret_value():
329
+ missing.append(f"{label} model provider API key ({provider_name})")
330
+ if missing:
331
+ raise typer.BadParameter("missing required initialization values: " + ", ".join(missing))
332
+
333
+
334
+ @app.command()
335
+ def init(
336
+ non_interactive: bool = typer.Option(False, "--non-interactive", help="Do not prompt; use a JSON config or options."),
337
+ home: Path | None = typer.Option(None, "--home", "--config-dir", help="Writune configuration directory."),
338
+ config_file: Path | None = typer.Option(None, "--config-file", help="Read settings from a JSON file."),
339
+ primary_url: str | None = typer.Option(None, "--primary-url", help="Primary Responses API base URL."),
340
+ primary_port: int | None = typer.Option(None, "--primary-port", min=1, max=65535),
341
+ api_key: str | None = typer.Option(None, "--api-key", help="Primary provider API key."),
342
+ backup_url: str | None = typer.Option(None, "--backup-url", help="Optional fallback provider base URL."),
343
+ backup_port: int | None = typer.Option(None, "--backup-port", min=1, max=65535),
344
+ backup_api_key: str | None = typer.Option(None, "--backup-api-key", help="Optional fallback provider API key."),
345
+ zh_primary_model: str | None = typer.Option(None, "--zh-primary-model"),
346
+ zh_fallback_model: str | None = typer.Option(None, "--zh-fallback-model"),
347
+ en_primary_model: str | None = typer.Option(None, "--en-primary-model"),
348
+ en_fallback_model: str | None = typer.Option(None, "--en-fallback-model"),
349
+ default_style: str | None = typer.Option(None, "--default-style"),
350
+ max_concurrency: int | None = typer.Option(None, "--max-concurrency", min=1),
351
+ connect_timeout: float | None = typer.Option(None, "--connect-timeout", min=0),
352
+ first_token_timeout: float | None = typer.Option(None, "--first-token-timeout", min=0),
353
+ min_tps: float | None = typer.Option(None, "--min-tps", min=0),
354
+ inactivity_timeout: float | None = typer.Option(None, "--inactivity-timeout", min=0),
355
+ total_timeout: float | None = typer.Option(None, "--total-timeout", min=0),
356
+ retry_count: int | None = typer.Option(None, "--retry-count", min=0),
357
+ data_dir: Path | None = typer.Option(None, "--data-dir"),
358
+ task_ttl_hours: float | None = typer.Option(None, "--task-ttl-hours", min=0),
359
+ allowed_workspaces: list[Path] | None = typer.Option(None, "--allowed-workspace", help="Repeat for each authorized workspace."),
360
+ ) -> None:
361
+ """Create the user configuration interactively or from explicit values."""
362
+
363
+ try:
364
+ settings = _init_settings(
365
+ home=home,
366
+ config_file=config_file,
367
+ non_interactive=non_interactive,
368
+ primary_url=primary_url,
369
+ primary_port=primary_port,
370
+ api_key=api_key,
371
+ backup_url=backup_url,
372
+ backup_port=backup_port,
373
+ backup_api_key=backup_api_key,
374
+ zh_primary_model=zh_primary_model,
375
+ zh_fallback_model=zh_fallback_model,
376
+ en_primary_model=en_primary_model,
377
+ en_fallback_model=en_fallback_model,
378
+ default_style=default_style,
379
+ max_concurrency=max_concurrency,
380
+ connect_timeout=connect_timeout,
381
+ first_token_timeout=first_token_timeout,
382
+ min_tps=min_tps,
383
+ inactivity_timeout=inactivity_timeout,
384
+ total_timeout=total_timeout,
385
+ retry_count=retry_count,
386
+ data_dir=data_dir,
387
+ task_ttl_hours=task_ttl_hours,
388
+ allowed_workspaces=allowed_workspaces,
389
+ )
390
+ except (ValueError, ValidationError) as exc:
391
+ raise typer.BadParameter(str(exc)) from exc
392
+ typer.echo("Writune configuration saved.")
393
+ typer.echo(f"Config: {settings.config_path}")
394
+ primary_names = list(
395
+ dict.fromkeys(
396
+ split_model(model_ref)[0]
397
+ for model_ref in (settings.zh_primary, settings.en_primary)
398
+ if model_ref
399
+ )
400
+ )
401
+ for provider_name in primary_names:
402
+ provider = settings.providers.get(provider_name)
403
+ typer.echo(f"Provider {provider_name}: {provider.base_url if provider else 'not configured'}")
404
+ typer.echo(f"Chinese models: {settings.zh_primary} / {settings.zh_secondary or 'disabled'}")
405
+ typer.echo(f"English models: {settings.en_primary} / {settings.en_secondary or 'disabled'}")
406
+
407
+
408
+ @config_app.command("show")
409
+ def config_show(home: Path | None = typer.Option(None, "--home", "--config-dir")) -> None:
410
+ """Print settings as JSON with credentials masked."""
411
+
412
+ settings = _settings(home)
413
+ typer.echo(json.dumps(settings.redacted_dict(), ensure_ascii=False, indent=2, default=str))
414
+
415
+
416
+ def _parse_config_value(key: str, raw: str) -> Any:
417
+ if key.rsplit(".", 1)[-1] == "api_key":
418
+ return SecretStr(raw)
419
+ try:
420
+ return json.loads(raw)
421
+ except json.JSONDecodeError:
422
+ return raw
423
+
424
+
425
+ @config_app.command("set")
426
+ def config_set(
427
+ key: str = typer.Argument(..., help="Setting name or dotted path such as providers.primary.base_url."),
428
+ value: str | None = typer.Argument(None, help="Value; API keys are prompted without echo when omitted."),
429
+ home: Path | None = typer.Option(None, "--home", "--config-dir"),
430
+ ) -> None:
431
+ """Update one setting and persist provider credentials in the private .env file."""
432
+
433
+ settings = _settings(home)
434
+ if key.split(".", 1)[0] not in Settings.model_fields:
435
+ raise typer.BadParameter(f"unknown setting: {key.split('.', 1)[0]}")
436
+ if value is None:
437
+ value = typer.prompt(f"Value for {key}", hide_input=key.rsplit(".", 1)[-1] == "api_key")
438
+ data = settings.model_dump(mode="python")
439
+ parts = key.split(".")
440
+ if not parts or any(not part for part in parts):
441
+ raise typer.BadParameter("setting path must not contain empty components")
442
+ target: dict[str, Any] = data
443
+ for part in parts[:-1]:
444
+ current = target.get(part)
445
+ if current is None:
446
+ current = {}
447
+ target[part] = current
448
+ if not isinstance(current, dict):
449
+ raise typer.BadParameter(f"{part} is not a nested setting")
450
+ target = current
451
+ target[parts[-1]] = _parse_config_value(key, value)
452
+ try:
453
+ updated = Settings(**data)
454
+ except ValidationError as exc:
455
+ raise typer.BadParameter(str(exc)) from exc
456
+ updated.save(settings.home_dir)
457
+ typer.echo(f"Updated {key}; saved {updated.config_path}")
458
+
459
+
460
+ def _check_writable(path: Path) -> bool:
461
+ try:
462
+ path.mkdir(parents=True, exist_ok=True)
463
+ probe = path / ".writune-doctor-probe"
464
+ probe.write_text("ok", encoding="utf-8")
465
+ probe.unlink()
466
+ return True
467
+ except OSError:
468
+ return False
469
+
470
+
471
+ def _provider_probe(settings: Settings) -> tuple[bool, str]:
472
+ """Perform a short Responses API request using a configured primary model."""
473
+
474
+ model_ref = settings.en_primary or settings.zh_primary
475
+ if not model_ref:
476
+ return False, "no primary model is configured"
477
+ try:
478
+ provider_name, model_name = split_model(model_ref)
479
+ provider = settings.providers[provider_name]
480
+ from writune.polishing.prompt import Prompt
481
+ from writune.providers.responses import ResponsesProvider
482
+
483
+ async def generate() -> Any:
484
+ return await ResponsesProvider(provider=provider, settings=settings).generate(
485
+ model_name,
486
+ Prompt(prefix="Return only the requested test phrase.", input="Reply with exactly: Writune provider connection OK"),
487
+ options={"max_output_tokens": 32},
488
+ )
489
+
490
+ result = asyncio.run(generate())
491
+ if not result.text.strip():
492
+ return False, "provider returned empty output"
493
+ return True, f"generation succeeded ({len(result.text)} output characters)"
494
+ except Exception as exc: # errors are already sanitized by the provider adapter
495
+ return False, f"{type(exc).__name__}: {exc}"
496
+
497
+
498
+ def _mcp_startup_probe(settings: Settings) -> tuple[bool, str]:
499
+ """Initialize the real stdio entry point without making a provider request."""
500
+ from mcp import ClientSession, StdioServerParameters
501
+ from mcp.client.stdio import stdio_client
502
+
503
+ async def check() -> int:
504
+ from writune.runtime import windowless_python
505
+ parameters=StdioServerParameters(command=windowless_python(),args=['-m','writune','serve','--home',str(settings.home_dir)],env=os.environ.copy())
506
+ with open(os.devnull,'w') as errlog:
507
+ async with asyncio.timeout(15):
508
+ async with stdio_client(parameters,errlog=errlog) as streams:
509
+ async with ClientSession(*streams) as session:
510
+ await session.initialize()
511
+ discovered=await session.list_tools()
512
+ names={tool.name for tool in discovered.tools}
513
+ if not {'writune_submit','writune_status','writune_result','writune_apply','writune_cancel'}.issubset(names):
514
+ raise ValueError('Required tools are missing')
515
+ return len(names)
516
+ try:
517
+ return True,f'real stdio initialized; {asyncio.run(check())} tools discovered'
518
+ except Exception:
519
+ return False,'stdio initialization or required tool discovery failed'
520
+
521
+
522
+ @app.command()
523
+ def doctor(
524
+ probe: bool = typer.Option(False, "--probe", help="Make a real, short Responses API request."),
525
+ home: Path | None = typer.Option(None, "--home", "--config-dir"),
526
+ ) -> None:
527
+ """Check Python, dependencies, settings, credentials, storage, provider, and skill."""
528
+
529
+ checks: list[tuple[str, bool, str]] = []
530
+ checks.append(("python", sys.version_info >= (3, 11), sys.version.split()[0]))
531
+ for package in ("mcp", "typer", "httpx", "pydantic", "pydantic-settings", "python-docx", "python-dotenv", "openai"):
532
+ try:
533
+ version = importlib.metadata.version(package)
534
+ checks.append((f"dependency:{package}", True, version))
535
+ except importlib.metadata.PackageNotFoundError:
536
+ checks.append((f"dependency:{package}", False, "not installed"))
537
+ try:
538
+ settings = _settings(home)
539
+ config_ok = settings.config_path.exists()
540
+ checks.append(("config", config_ok, str(settings.config_path)))
541
+ initialized = bool(settings.en_primary and settings.zh_primary)
542
+ checks.append(("models", initialized, "configured" if initialized else "primary models are missing"))
543
+ configured = bool(settings.providers and all(p.api_key.get_secret_value() for p in settings.providers.values()))
544
+ checks.append(("credentials", configured, "configured" if configured else "one or more provider keys are missing"))
545
+ storage_ok = _check_writable(settings.data_dir)
546
+ db_ok = False
547
+ db_detail = str(settings.db_path)
548
+ if storage_ok:
549
+ try:
550
+ service = Service(settings, start_worker=False)
551
+ with service.db.connect() as connection:
552
+ connection.execute("SELECT 1").fetchone()
553
+ db_ok = True
554
+ except Exception as exc:
555
+ db_detail = f"{settings.db_path}: {type(exc).__name__}: {exc}"
556
+ checks.append(("storage", storage_ok and db_ok, db_detail if storage_ok else f"not writable: {settings.data_dir}"))
557
+ checks.append(("task_directory", _check_writable(settings.task_dir), str(settings.task_dir)))
558
+ for provider_name, provider in settings.providers.items():
559
+ configured_provider = bool(provider.base_url and provider.api_key.get_secret_value())
560
+ checks.append((f"provider:{provider_name}", configured_provider, "URL and key configured" if configured_provider else "URL or key missing"))
561
+ checks.append(("mcp_sdk", importlib.metadata.version("mcp").startswith("1."), f"mcp {importlib.metadata.version('mcp')}"))
562
+ mcp_ok,mcp_detail=_mcp_startup_probe(settings)
563
+ checks.append(('mcp_startup',mcp_ok,mcp_detail))
564
+ checks.append(("skill", _skill_installed(), "writune-polish skill found" if _skill_installed() else "skill file not found in project/user skill directories"))
565
+ if probe:
566
+ ok, detail = _provider_probe(settings)
567
+ checks.append(("provider_probe", ok, detail))
568
+ except Exception as exc:
569
+ checks.append(("config", False, f"{type(exc).__name__}: {exc}"))
570
+ for name, ok, detail in checks:
571
+ typer.echo(f"{'OK' if ok else 'FAIL'} {name}: {detail}")
572
+ if any(not ok for _, ok, _ in checks):
573
+ raise typer.Exit(code=1)
574
+
575
+
576
+ def _skill_installed() -> bool:
577
+ candidates = [
578
+ Path.cwd() / ".agents" / "skills" / "writune-polish" / "SKILL.md",
579
+ Path.home() / ".agents" / "skills" / "writune-polish" / "SKILL.md",
580
+ Path.home() / ".codex" / "skills" / "writune-polish" / "SKILL.md",
581
+ ]
582
+ return any(path.is_file() for path in candidates)
583
+
584
+
585
+ @app.command()
586
+ def test_provider(
587
+ model: str | None = typer.Option(None, "--model", help="provider/model; defaults to configured English primary."),
588
+ home: Path | None = typer.Option(None, "--home", "--config-dir"),
589
+ ) -> None:
590
+ """Make an actual short generation request to confirm provider connectivity."""
591
+
592
+ settings = _settings(home)
593
+ if model:
594
+ settings.en_primary = model
595
+ ok, detail = _provider_probe(settings)
596
+ typer.echo(("Provider test passed: " if ok else "Provider test failed: ") + detail)
597
+ if not ok:
598
+ raise typer.Exit(code=1)
599
+
600
+
601
+ @app.command()
602
+ def serve(home: Path | None = typer.Option(None, "--home", "--config-dir")) -> None:
603
+ """Run the Writune MCP stdio server."""
604
+
605
+ from writune.mcp_server import run
606
+
607
+ run(home)
608
+
609
+
610
+ @app.command()
611
+ def submit(
612
+ text: str | None = typer.Option(None, "--text"),
613
+ source_path: Path | None = typer.Option(None, "--source-path"),
614
+ source_encoding: str | None = typer.Option(None,'--source-encoding'),
615
+ language: str | None = typer.Option(None, "--language"),
616
+ scene: str | None = typer.Option(None, "--scene"),
617
+ context_id: str | None = typer.Option(None, "--context-id"),
618
+ primary_model: str | None = typer.Option(None, "--primary-model"),
619
+ secondary_model: str | None = typer.Option(None, "--secondary-model"),
620
+ style: str | None = typer.Option(None, "--style"),
621
+ priority: int | None = typer.Option(None, "--priority"),
622
+ profile: str | None = typer.Option(None,'--profile'),
623
+ idempotency_key: str | None = typer.Option(None, "--idempotency-key"),
624
+ home: Path | None = typer.Option(None, "--home", "--config-dir"),
625
+ ) -> None:
626
+ """Submit one paragraph from text or an authorized source file."""
627
+
628
+ result = _service(home).submit(
629
+ text=text,
630
+ source_path=str(source_path) if source_path else None,
631
+ source_encoding=source_encoding,
632
+ language=language,
633
+ scene=scene,
634
+ context_id=context_id,
635
+ primary_model=primary_model,
636
+ secondary_model=secondary_model,
637
+ style=style,
638
+ priority=priority,
639
+ profile=profile,
640
+ idempotency_key=idempotency_key,
641
+ )
642
+ _echo_json(result)
643
+
644
+
645
+ @app.command()
646
+ def status(
647
+ task_id: str | None = typer.Option(None, "--task-id"),
648
+ batch_id: str | None = typer.Option(None, "--batch-id"),
649
+ home: Path | None = typer.Option(None, "--home", "--config-dir"),
650
+ ) -> None:
651
+ """Show task or batch progress."""
652
+
653
+ _echo_json(_service(home).status(task_id=task_id, batch_id=batch_id))
654
+
655
+
656
+ @app.command('submit-batch')
657
+ def submit_batch(
658
+ markdown_path: Path | None = typer.Option(None,'--markdown-path'),
659
+ items_file: Path | None = typer.Option(None,'--items-file',help='UTF-8 JSON array of paragraph objects'),
660
+ source_paths: list[Path] | None = typer.Option(None,'--source-path'),
661
+ language: str | None = typer.Option(None,'--language'),
662
+ scene: str | None = typer.Option(None,'--scene'),
663
+ context_id: str | None = typer.Option(None,'--context-id'),
664
+ style: str | None = typer.Option(None,'--style'),
665
+ max_concurrency: int | None = typer.Option(None,'--max-concurrency',min=1),
666
+ idempotency_key: str | None = typer.Option(None,'--idempotency-key'),
667
+ home: Path | None = typer.Option(None,'--home','--config-dir'),
668
+ ) -> None:
669
+ service=_service(home)
670
+ items=json.loads(service.workspace.check(items_file).read_text(encoding='utf-8-sig')) if items_file else None
671
+ _echo_json(service.submit_batch(items=items,markdown_path=markdown_path,source_paths=source_paths or None,language=language,scene=scene,context_id=context_id,style=style,max_concurrency=max_concurrency,idempotency_key=idempotency_key))
672
+
673
+
674
+ @app.command('merge-batch')
675
+ def merge_batch(batch_id: str, output_path: Path, separator: str | None = typer.Option(None,'--separator'),overwrite: bool = typer.Option(False,'--overwrite'),home: Path | None = typer.Option(None,'--home','--config-dir')) -> None:
676
+ _echo_json(_service(home,start_worker=False).merge_batch(batch_id,output_path,separator,overwrite))
677
+
678
+
679
+ @app.command()
680
+ def result(
681
+ task_id: str = typer.Argument(...),
682
+ inline_text: bool = typer.Option(False, "--inline-text", help="Include full result text in output."),
683
+ home: Path | None = typer.Option(None, "--home", "--config-dir"),
684
+ ) -> None:
685
+ """Show result paths, outcome, and optional inline text."""
686
+
687
+ _echo_json(_service(home).result(task_id, inline_text=inline_text))
688
+
689
+
690
+ @app.command()
691
+ def apply(
692
+ task_id: str = typer.Option(..., "--task-id"),
693
+ target_path: Path = typer.Option(..., "--target-path"),
694
+ placeholder_id: str = typer.Option(..., "--placeholder-id"),
695
+ output_path: Path | None = typer.Option(None, "--output-path"),
696
+ overwrite: bool = typer.Option(False, "--overwrite"),
697
+ home: Path | None = typer.Option(None, "--home", "--config-dir"),
698
+ ) -> None:
699
+ """Apply a result to a controlled document path."""
700
+
701
+ _echo_json(
702
+ _service(home).apply(
703
+ task_id=task_id,
704
+ target_path=str(target_path),
705
+ placeholder_id=placeholder_id,
706
+ output_path=str(output_path) if output_path else None,
707
+ overwrite=overwrite,
708
+ )
709
+ )
710
+
711
+
712
+ @app.command()
713
+ def cancel(task_id: str = typer.Argument(...), home: Path | None = typer.Option(None, "--home", "--config-dir")) -> None:
714
+ """Cancel a queued or running task."""
715
+
716
+ _echo_json(_service(home).cancel(task_id))
717
+
718
+
719
+ @app.command()
720
+ def stats(home: Path | None = typer.Option(None, "--home", "--config-dir")) -> None:
721
+ """Display actual historical performance observations."""
722
+
723
+ _echo_json(_service(home, start_worker=False).stats())
724
+
725
+
726
+ @app.command()
727
+ def worker(home: Path | None = typer.Option(None, "--home", "--config-dir")) -> None:
728
+ """Run a worker process in the foreground."""
729
+
730
+ from writune.tasks.worker import Worker
731
+
732
+ asyncio.run(Worker(_settings(home)).run())
733
+
734
+
735
+ @app.command('update-status')
736
+ def update_status_command() -> None:
737
+ """Show the last background update outcome without making a network request."""
738
+ from writune.updates import update_status
739
+ _echo_json(update_status())
740
+
741
+
742
+ @app.command()
743
+ def cleanup(home: Path | None = typer.Option(None, "--home", "--config-dir"), all_history: bool = typer.Option(False, "--all", help="Remove all terminal task history and unused contexts; keep active tasks.")) -> None:
744
+ """Remove expired task files and records, or all terminal history."""
745
+
746
+ _echo_json(_service(home, start_worker=False).cleanup(all_history=all_history))
747
+
748
+
749
+ def _echo_json(value: Any) -> None:
750
+ typer.echo(json.dumps(value, ensure_ascii=False, indent=2, default=str))