-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
3985 lines (3576 loc) · 169 KB
/
server.py
File metadata and controls
3985 lines (3576 loc) · 169 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import hashlib
import html
import json
import mimetypes
import os
import re
import shutil
import smtplib
import socket
import ssl
import subprocess
import sys
import threading
import time
import traceback
import urllib.error
import urllib.parse
import urllib.request
import uuid
from dataclasses import dataclass
from datetime import datetime, timedelta
from email.message import EmailMessage
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any, Callable, Iterable
ROOT = Path(__file__).resolve().parent
WEB_DIR = ROOT / "web"
DEFAULT_BOOKS_DIR = ROOT / "books"
CONFIG_PATH = ROOT / "config.local.json"
STATE_PATH = ROOT / ".server_state.json"
API_KEY_TEXT_PATH = ROOT / "ANTHROPIC_API_KEY.txt"
TMP_DIR = ROOT / "tmp"
WHISPER_DIR = ROOT / "runtime" / "whisper"
VERSION_PATH = ROOT / "VERSION"
DEFAULT_UPDATE_REPO = "Xyloth/Generation-Engine"
CANON_FILES = ("world", "characters", "timeline", "arcs", "voice_profile")
RESEARCH_TABS = ("sources", "people", "timeline", "claims", "records", "voice")
PROJECT_TYPES = {"novel", "research"}
SIDE_SUFFIXES = (".plan", ".transcript")
DEFAULT_DRAFT_MODEL = "claude-opus-4-7"
DEFAULT_UTILITY_MODEL = "claude-sonnet-4-6"
DEFAULT_CLAUDE_CODE_MODEL = "claude-sonnet-4-6"
VALID_MODES = {"auto", "api", "claude-code", "local-fallback"}
PREFLIGHT_TIMEOUT_SECONDS = 12
GENERATION_TIMEOUT_SECONDS = 900
CLAUDE_CODE_BRIDGE_SYSTEM = (
"You are Generation Engine's Claude backend. Treat the AUTHORITATIVE SYSTEM CONTEXT in stdin as system instructions."
)
DEFAULT_CANON = {
"world": "# World\n\n## Setting\n\n## Rules\n\n## Factions\n\n## History\n",
"characters": "# Characters\n\n## Protagonist\n- Role:\n- Voice:\n- Goals:\n- Fears:\n- Relationships:\n- Current state:\n",
"timeline": "# Timeline\n\n",
"arcs": "# Arcs / Threads\n\n## Open\n\n## Advanced\n\n## Closed\n",
"voice_profile": "# Voice Profile\n\nWrite with concrete physical detail, opinionated rhythm, lived-in dialogue, and clear causal motion. Avoid generic polish, summary endings, and assistant-like balance. The voice should feel authored by a working novelist, not generated by a helper.\n",
}
BASE_NOVELIST_SYSTEM = """You are a working novelist collaborating with one human author on a long book.
Write like a human writer with opinions, rhythm, impatience, tenderness, and taste. Do not write like an AI assistant. Do not use polished, balanced, vaguely uplifting prose. Do not explain the work before or after you do it.
The user owns canon. Canon files are authoritative. If canon is thin or contradictory, use the user's latest stated intent and keep the prose concrete.
This product is a chat-first collaboration. Decide what to do from the user's words, not from app modes.
If the user riffs, brainstorm and ask 1-3 sharp clarifying questions only when material stakes are unclear.
If the user asks to draft the next chapter, write the full chapter in the chat.
If the user asks to revise a prior draft, return the revised full draft in the chat.
If the user asks for recap, continuity, what happened, or what is next, answer conversationally from canon and saved chapters.
If the user asks you to save a chapter, acknowledge the intent, but saving is done only by the user's explicit Save button in the app.
When you output a full chapter draft or full revised chapter draft, end the message with one final machine-readable HTML comment on its own line:
<!-- GE_DRAFT {"draft_for":"chapter","suggested_id":"NN","title":"Chapter N"} -->
Use the most likely next chapter number. Do not mention the marker.
Drafting rules:
- Embody the editable voice profile without imitating any named author directly.
- Keep visible plot motion on the page.
- Prefer specific images, specific verbs, and character-specific dialogue.
- Avoid these AI tells: "the air was thick with tension", "she felt a sense of", "a reminder that", "in that moment", "could not help but", closing paragraphs that summarize the meaning of the scene, and tidy emotional thesis statements.
"""
IMPORT_SYSTEM = """You are Generation Engine's import analyst.
You are not drafting prose. You are reading already-written chapters and extracting usable canon for a long-running writing project.
Rules:
- Infer only from supplied text.
- Preserve uncertainty as "possible", "implied", or "unclear"; do not invent.
- Prefer concrete details over labels.
- Character entries must contain useful notes: role, voice/speech, goals, fears, relationships, and current state when the text supports them.
- Timeline must cover every imported chapter, not just the opening chapters.
- Return valid JSON only. No markdown fences, no commentary.
"""
BASE_RESEARCH_SYSTEM = """You are a careful research assistant working with one human author on a long-form nonfiction project.
Real people, real events, and real harm may be involved. Accuracy matters more than fluency.
Hard rules:
- Never assert a factual claim in prose without a backing source or claim marker.
- If a claim is not sourced, write it inline as [UNSOURCED: ...] or say there is not enough source material yet.
- Use attributed language: according to the report, court records show, the family told the newspaper, the transcript says.
- Allegations involving living people must stay allegations: alleged, reportedly, according to charging documents, according to police.
- Speculation must be marked [SPECULATION - no source].
- When sources disagree, surface the contradiction instead of choosing one as truth.
- You may flag risk, sourcing gaps, and contradictions. The user decides what to do.
The project's claims matrix is the source of truth for what prose may assert. Drafts should use inline citation markers like [[claim:claim-007]] tied to claim ids. If no claim exists for a factual sentence, mark it [UNSOURCED: ...] and suggest what source or record request would close the gap.
When you output a full chapter draft or full revised chapter draft, end the message with one final machine-readable HTML comment on its own line:
<!-- GE_DRAFT {"draft_for":"chapter","suggested_id":"NN","title":"Chapter N"} -->
Use the most likely next chapter number. Do not mention the marker.
"""
DEFAULT_RESEARCH_VOICE = "# Voice Profile\n\nUse clear, sourced nonfiction prose. Favor attribution, concrete chronology, and precise verbs over atmosphere. The voice may be literary, but factual claims must remain visible, qualified, and traceable to evidence.\n"
DEFAULT_RESEARCH_TIMELINE = "# Timeline\n\n"
DEFAULT_RESEARCH_CLAIMS: list[dict[str, Any]] = []
def now_iso() -> str:
return time.strftime("%Y-%m-%dT%H:%M:%S%z")
def slugify(value: str) -> str:
value = value.strip().lower()
value = re.sub(r"[^a-z0-9]+", "-", value)
value = re.sub(r"-+", "-", value).strip("-")
return value or "book"
def pad_id(value: int | str) -> str:
text = str(value).strip()
if text.isdigit():
return text.zfill(2)
return text
def json_safe_load(path: Path, default: Any) -> Any:
if not path.exists():
return default
try:
return json.loads(path.read_text(encoding="utf-8-sig"))
except Exception:
return default
def read_local_api_key_file() -> str:
if not API_KEY_TEXT_PATH.exists():
return ""
text = read_text(API_KEY_TEXT_PATH).strip()
if not text:
return ""
for line in text.splitlines():
stripped = line.strip()
if not stripped or stripped.startswith("#"):
continue
if "=" in stripped:
_name, value = stripped.split("=", 1)
stripped = value.strip().strip('"').strip("'")
return stripped
return ""
def read_text(path: Path, default: str = "") -> str:
try:
return path.read_text(encoding="utf-8")
except FileNotFoundError:
return default
except UnicodeDecodeError:
return path.read_text(encoding="utf-8", errors="replace")
def write_text(path: Path, text: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_name(path.name + ".tmp")
tmp.write_text(text, encoding="utf-8", newline="\n")
tmp.replace(path)
def write_json(path: Path, data: Any) -> None:
write_text(path, json.dumps(data, indent=2, ensure_ascii=False) + "\n")
def console_log(message: str) -> None:
stream = getattr(sys, "stdout", None)
if not stream:
return
try:
stream.write(message + "\n")
stream.flush()
except Exception:
pass
def hidden_subprocess_kwargs() -> dict[str, Any]:
if os.name != "nt":
return {}
return {"creationflags": getattr(subprocess, "CREATE_NO_WINDOW", 0)}
def sha_text(text: str) -> str:
return hashlib.sha256(text.encode("utf-8")).hexdigest()
def clean_title_from_markdown(text: str, fallback: str) -> str:
for line in text.splitlines():
stripped = line.strip()
if stripped.startswith("#"):
title = stripped.lstrip("#").strip()
if title:
return title[:90]
return fallback
def split_markdown_chapters(raw: str) -> list[dict[str, str]]:
raw = raw.replace("\r\n", "\n").replace("\r", "\n").strip()
if not raw:
return []
marker = re.compile(
r"(?im)^(?:#{1,3}\s*)?(?:chapter|chap\.?|mini[-\s]?chapter)\s+([0-9]+|[ivxlcdm]+)\b[^\n]*$"
)
matches = list(marker.finditer(raw))
chapters: list[dict[str, str]] = []
if matches:
for index, match in enumerate(matches):
start = match.start()
end = matches[index + 1].start() if index + 1 < len(matches) else len(raw)
chunk = raw[start:end].strip()
title = match.group(0).strip().lstrip("#").strip()
chapters.append({"title": title, "content": chunk})
return chapters
file_marker = re.compile(r"(?m)^#\s+Imported file:\s+(.+)$")
matches = list(file_marker.finditer(raw))
if matches:
for index, match in enumerate(matches):
start = match.start()
end = matches[index + 1].start() if index + 1 < len(matches) else len(raw)
title = match.group(1).strip()
chunk = raw[start:end].strip()
chapters.append({"title": title, "content": chunk})
return chapters
chunks = [part.strip() for part in re.split(r"\n\s*---+\s*\n", raw) if part.strip()]
if len(chunks) > 1:
for index, chunk in enumerate(chunks, start=1):
chapters.append({"title": clean_title_from_markdown(chunk, f"Chapter {index}"), "content": chunk})
return chapters
return [{"title": clean_title_from_markdown(raw, "Chapter 1"), "content": raw}]
def extract_names(text: str, limit: int = 24) -> list[str]:
stop = {
"Chapter",
"The",
"A",
"An",
"And",
"But",
"She",
"He",
"They",
"It",
"When",
"Where",
"There",
"This",
"That",
"I",
}
counts: dict[str, int] = {}
for name in re.findall(r"\b[A-Z][a-z]+(?:\s+[A-Z][a-z]+)?\b", text):
first = name.split()[0]
if first in stop or len(first) < 3:
continue
counts[name] = counts.get(name, 0) + 1
ordered = sorted(counts.items(), key=lambda item: (-item[1], item[0]))
return [name for name, _count in ordered[:limit]]
def first_sentences(text: str, count: int = 2) -> str:
body = re.sub(r"^#+[^\n]*", "", text, flags=re.M).strip()
sentences = re.split(r"(?<=[.!?])\s+", body)
picked = [s.strip() for s in sentences if len(s.strip()) > 20][:count]
return " ".join(picked)[:600]
@dataclass
class RuntimeConfig:
books_dir: Path
api_key: str
draft_model: str
utility_model: str
claude_code_model: str
port: int
requested_mode: str
claude_path: str | None
bug_report: dict[str, Any]
update: dict[str, Any]
@dataclass
class PreflightState:
requested_mode: str
active_mode: str
api_ok: bool
api_message: str
claude_code_ok: bool
claude_code_message: str
claude_path: str | None
checked_at: str
status_message: str
def discover_claude_path() -> str | None:
on_path = shutil.which("claude")
if on_path:
return on_path
candidate_roots: list[Path] = []
appdata = os.environ.get("APPDATA")
if appdata:
candidate_roots.append(Path(appdata) / "Claude" / "claude-code")
local_appdata = os.environ.get("LOCALAPPDATA")
if local_appdata:
candidate_roots.append(Path(local_appdata) / "Claude" / "claude-code")
candidate_roots.append(Path(local_appdata) / "Programs" / "Claude Code")
packages = Path(local_appdata) / "Packages"
if packages.is_dir():
for package_root in packages.glob("Claude_*"):
candidate_roots.append(package_root / "LocalCache" / "Roaming" / "Claude" / "claude-code")
versioned: list[Path] = []
direct: list[Path] = []
for root in candidate_roots:
if not root.is_dir():
continue
flat = root / "claude.exe"
if flat.is_file():
direct.append(flat)
for child in root.iterdir():
if not child.is_dir():
continue
exe = child / "claude.exe"
if exe.is_file():
versioned.append(exe)
if versioned:
def version_key(path: Path) -> tuple:
parts = path.parent.name.split(".")
return tuple(int(part) if part.isdigit() else -1 for part in parts)
versioned.sort(key=version_key, reverse=True)
return str(versioned[0])
if direct:
return str(direct[0])
return None
def load_config() -> RuntimeConfig:
cfg = json_safe_load(CONFIG_PATH, {})
books_dir_raw = cfg.get("booksDir") or os.environ.get("GENERATION_ENGINE_BOOKS_DIR") or str(DEFAULT_BOOKS_DIR)
books_dir = Path(books_dir_raw).expanduser()
if not books_dir.is_absolute():
books_dir = (ROOT / books_dir).resolve()
api_key = cfg.get("anthropicApiKey") or read_local_api_key_file() or os.environ.get("ANTHROPIC_API_KEY") or ""
draft_model = cfg.get("draftModel") or os.environ.get("ANTHROPIC_DRAFT_MODEL") or DEFAULT_DRAFT_MODEL
utility_model = cfg.get("utilityModel") or os.environ.get("ANTHROPIC_UTILITY_MODEL") or DEFAULT_UTILITY_MODEL
claude_code_model = (
cfg.get("claudeCodeModel")
or os.environ.get("ANTHROPIC_DRAFT_MODEL")
or os.environ.get("CLAUDE_CODE_MODEL")
or DEFAULT_CLAUDE_CODE_MODEL
)
mode = (cfg.get("mode") or os.environ.get("GENERATION_ENGINE_MODE") or "auto").strip().lower()
if mode not in VALID_MODES:
mode = "auto"
claude_path = cfg.get("claudePath") or discover_claude_path()
port = int(cfg.get("port") or os.environ.get("GENERATION_ENGINE_PORT") or 8765)
bug_report = cfg.get("bugReport") if isinstance(cfg.get("bugReport"), dict) else {}
update = cfg.get("update") if isinstance(cfg.get("update"), dict) else {}
books_dir.mkdir(parents=True, exist_ok=True)
return RuntimeConfig(
books_dir=books_dir,
api_key=api_key,
draft_model=draft_model,
utility_model=utility_model,
claude_code_model=claude_code_model,
port=port,
requested_mode=mode,
claude_path=claude_path,
bug_report=bug_report,
update=update,
)
CONFIG = load_config()
PREFLIGHT: PreflightState | None = None
def save_local_config(updates: dict[str, Any]) -> dict[str, Any]:
cfg = json_safe_load(CONFIG_PATH, {})
cfg.update(updates)
write_json(CONFIG_PATH, cfg)
return cfg
def reload_runtime_config() -> None:
global CONFIG
CONFIG = load_config()
def api_key_preview() -> str:
if not CONFIG.api_key:
return "not configured"
if len(CONFIG.api_key) <= 10:
return "configured"
return f"{CONFIG.api_key[:7]}...{CONFIG.api_key[-4:]}"
def current_version() -> str:
return read_text(VERSION_PATH, "0.0.0").strip() or "0.0.0"
def update_repo() -> str:
return str(CONFIG.update.get("repo") or os.environ.get("GENERATION_ENGINE_UPDATE_REPO") or DEFAULT_UPDATE_REPO)
def version_key(value: str) -> tuple[int, ...]:
parts = re.findall(r"\d+", value)
return tuple(int(part) for part in parts[:4]) or (0,)
def compare_versions(left: str, right: str) -> int:
a = list(version_key(left))
b = list(version_key(right))
size = max(len(a), len(b))
a.extend([0] * (size - len(a)))
b.extend([0] * (size - len(b)))
return (a > b) - (a < b)
def github_latest_release() -> dict[str, Any]:
repo = update_repo()
url = f"https://api.github.com/repos/{repo}/releases/latest"
req = urllib.request.Request(url, headers={"accept": "application/vnd.github+json", "user-agent": "Generation-Engine"})
with urllib.request.urlopen(req, timeout=20) as response:
release = json.loads(response.read().decode("utf-8"))
assets = release.get("assets") or []
zip_assets = [asset for asset in assets if str(asset.get("name", "")).lower().endswith(".zip")]
preferred = [
asset
for asset in zip_assets
if "generation_engine" in str(asset.get("name", "")).lower()
or "generation-engine" in str(asset.get("name", "")).lower()
]
asset = (preferred or zip_assets or assets or [None])[0]
tag = str(release.get("tag_name") or "")
latest = tag[1:] if tag.lower().startswith("v") else tag
current = current_version()
return {
"repo": repo,
"currentVersion": current,
"latestVersion": latest,
"tagName": tag,
"name": release.get("name") or tag,
"htmlUrl": release.get("html_url"),
"body": release.get("body") or "",
"publishedAt": release.get("published_at"),
"updateAvailable": bool(latest and compare_versions(latest, current) > 0),
"asset": {
"name": asset.get("name"),
"size": asset.get("size"),
"browserDownloadUrl": asset.get("browser_download_url"),
} if asset else None,
}
def download_update_asset(release: dict[str, Any]) -> Path:
asset = release.get("asset") or {}
download_url = asset.get("browserDownloadUrl")
if not download_url:
raise RuntimeError("Latest GitHub release does not include a downloadable zip asset.")
update_dir = TMP_DIR / "update"
update_dir.mkdir(parents=True, exist_ok=True)
name = safe_file_stem(str(asset.get("name") or "Generation_Engine-update.zip"), "Generation_Engine-update")
if not name.lower().endswith(".zip"):
name += ".zip"
target = update_dir / name
req = urllib.request.Request(download_url, headers={"user-agent": "Generation-Engine"})
with urllib.request.urlopen(req, timeout=120) as response, target.open("wb") as out:
shutil.copyfileobj(response, out)
return target
def start_update_install(server_url: str, force: bool = False) -> dict[str, Any]:
release = github_latest_release()
if not force and not release.get("updateAvailable"):
return {"installing": False, "message": "Generation Engine is already up to date.", "release": release}
zip_path = download_update_asset(release)
script = ROOT / "scripts" / "apply-update.ps1"
if not script.exists():
raise RuntimeError("Updater script is missing.")
subprocess.Popen(
[
"powershell",
"-NoProfile",
"-ExecutionPolicy",
"Bypass",
"-File",
str(script),
"-Root",
str(ROOT),
"-ZipPath",
str(zip_path),
"-ServerUrl",
server_url,
],
cwd=str(ROOT),
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
**hidden_subprocess_kwargs(),
)
return {"installing": True, "message": "Update downloaded. Generation Engine will restart.", "release": release}
def ping_anthropic_api() -> tuple[bool, str]:
if not CONFIG.api_key:
return False, "ANTHROPIC_API_KEY/config.local.json key is not configured."
req = urllib.request.Request(
"https://api.anthropic.com/v1/models?limit=1",
headers={
"x-api-key": CONFIG.api_key,
"anthropic-version": "2023-06-01",
},
method="GET",
)
try:
with urllib.request.urlopen(req, timeout=PREFLIGHT_TIMEOUT_SECONDS) as response:
if 200 <= response.status < 300:
return True, f"Anthropic API key verified ({api_key_preview()})."
return False, f"Anthropic API returned HTTP {response.status}."
except urllib.error.HTTPError as exc:
if exc.code in {401, 403}:
return False, f"Anthropic API key rejected with HTTP {exc.code}."
return False, f"Anthropic API preflight failed with HTTP {exc.code}."
except Exception as exc:
return False, f"Anthropic API preflight failed: {exc}"
def ping_claude_code() -> tuple[bool, str, str | None]:
claude_path = CONFIG.claude_path or discover_claude_path()
if not claude_path:
return False, "Claude Code CLI was not found on PATH.", None
try:
completed = subprocess.run(
[claude_path, "--version"],
capture_output=True,
text=True,
timeout=PREFLIGHT_TIMEOUT_SECONDS,
encoding="utf-8",
errors="replace",
**hidden_subprocess_kwargs(),
)
except Exception as exc:
return False, f"Claude Code preflight failed: {exc}", claude_path
if completed.returncode != 0:
message = (completed.stderr or completed.stdout or "claude --version returned a non-zero exit code").strip()
return False, message, claude_path
version = (completed.stdout or completed.stderr or "claude --version succeeded").strip()
try:
auth_check = subprocess.run(
[claude_path, "auth", "status"],
capture_output=True,
text=True,
timeout=PREFLIGHT_TIMEOUT_SECONDS,
encoding="utf-8",
errors="replace",
**hidden_subprocess_kwargs(),
)
payload = json.loads((auth_check.stdout or "").strip() or "{}")
if not payload.get("loggedIn"):
return (
False,
f"Claude Code CLI found ({version}) but not logged in. Run `claude auth login` once in a terminal, then restart.",
claude_path,
)
except (json.JSONDecodeError, Exception):
pass
return True, version, claude_path
def refresh_preflight(log: bool = False) -> PreflightState:
global PREFLIGHT
requested = CONFIG.requested_mode
api_ok = False
api_message = "API mode not checked."
claude_ok = False
claude_message = "Claude Code mode not checked."
claude_path = CONFIG.claude_path or discover_claude_path()
should_check_api = bool(CONFIG.api_key) and requested in {"auto", "api"}
should_check_claude = requested in {"auto", "claude-code"}
if should_check_api:
api_ok, api_message = ping_anthropic_api()
elif requested == "api":
api_ok, api_message = ping_anthropic_api()
if should_check_claude:
claude_ok, claude_message, claude_path = ping_claude_code()
elif requested == "claude-code":
claude_ok, claude_message, claude_path = ping_claude_code()
if requested == "api":
active = "api" if api_ok else "local-fallback"
status = api_message if api_ok else f"Anthropic API unavailable. {api_message}"
elif requested == "claude-code":
if claude_ok:
active = "claude-code"
status = f"Claude Code verified: {claude_message}"
else:
active = "local-fallback"
status = f"Claude Code unavailable. {claude_message}"
elif requested == "local-fallback":
active = "local-fallback"
status = "Local fallback mode selected."
else:
if claude_ok:
active = "claude-code"
status = f"Claude Code verified: {claude_message}"
elif CONFIG.api_key and api_ok:
active = "api"
status = api_message
else:
active = "local-fallback"
pieces = []
if claude_message:
pieces.append(f"Claude Code: {claude_message}")
if CONFIG.api_key:
pieces.append(f"API: {api_message}")
else:
pieces.append("API key is not configured.")
status = "AI setup required. " + " ".join(pieces)
PREFLIGHT = PreflightState(
requested_mode=requested,
active_mode=active,
api_ok=api_ok,
api_message=api_message,
claude_code_ok=claude_ok,
claude_code_message=claude_message,
claude_path=claude_path,
checked_at=now_iso(),
status_message=status,
)
if log:
console_log(f"Mode requested: {requested}")
console_log(f"Mode active: {active}")
console_log(f"API preflight: {api_message}")
console_log(f"Claude Code preflight: {claude_message}")
return PREFLIGHT
def get_preflight() -> PreflightState:
return PREFLIGHT or refresh_preflight()
def active_mode() -> str:
return get_preflight().active_mode
def book_dir(slug: str) -> Path:
safe = slugify(slug)
if safe != slug:
raise ValueError("Invalid book slug")
return CONFIG.books_dir / safe
def chapter_path(book: Path, chapter_id: str) -> Path:
return book / "chapters" / f"{pad_id(chapter_id)}.md"
def chapter_plan_path(book: Path, chapter_id: str) -> Path:
return book / "chapters" / f"{pad_id(chapter_id)}.plan.md"
def chapter_transcript_path(book: Path, chapter_id: str) -> Path:
return book / "chapters" / f"{pad_id(chapter_id)}.transcript.md"
def conversation_path(book: Path) -> Path:
return book / "conversation.json"
def research_dir(book: Path) -> Path:
return book / "research"
def ensure_research_dirs(book: Path) -> None:
root = research_dir(book)
for name in ("sources", "people", "records", "originals", "proposals"):
(root / name).mkdir(parents=True, exist_ok=True)
timeline = root / "timeline.md"
if not timeline.exists():
write_text(timeline, DEFAULT_RESEARCH_TIMELINE)
voice = root / "voice_profile.md"
if not voice.exists():
write_text(voice, DEFAULT_RESEARCH_VOICE)
claims = root / "claims.json"
if not claims.exists():
write_json(claims, DEFAULT_RESEARCH_CLAIMS)
def project_type_for_book(book: Path) -> str:
meta = load_meta(book)
value = str(meta.get("projectType") or "novel")
return value if value in PROJECT_TYPES else "novel"
def project_type_for_slug(slug: str) -> str:
return project_type_for_book(book_dir(slug))
def is_research_project(slug: str) -> bool:
return project_type_for_slug(slug) == "research"
def load_conversation(slug: str) -> dict[str, Any]:
book = book_dir(slug)
raw = json_safe_load(conversation_path(book), {"messages": []})
if isinstance(raw, list):
raw = {"messages": raw}
raw.setdefault("messages", [])
raw.setdefault("summary", "")
return raw
def save_conversation(slug: str, conversation: dict[str, Any]) -> dict[str, Any]:
book = book_dir(slug)
conversation.setdefault("messages", [])
conversation.setdefault("summary", "")
write_json(conversation_path(book), conversation)
return conversation
def append_conversation_message(
slug: str,
role: str,
content: str,
metadata: dict[str, Any] | None = None,
message_id: str | None = None,
) -> dict[str, Any]:
conversation = load_conversation(slug)
message = {
"id": message_id or uuid.uuid4().hex,
"role": role,
"content": content,
"createdAt": now_iso(),
"metadata": metadata or {},
}
conversation["messages"].append(message)
save_conversation(slug, conversation)
return message
def replace_conversation_message(slug: str, message_id: str, content: str, metadata: dict[str, Any] | None = None) -> None:
conversation = load_conversation(slug)
for message in conversation.get("messages", []):
if message.get("id") == message_id:
message["content"] = content
message["updatedAt"] = now_iso()
if metadata is not None:
message["metadata"] = metadata
save_conversation(slug, conversation)
return
def clear_conversation(slug: str) -> dict[str, Any]:
return save_conversation(slug, {"messages": [], "summary": ""})
def next_chapter_id(slug: str) -> str:
meta = load_meta(book_dir(slug))
used = [int(c["id"]) for c in meta.get("chapters", []) if str(c.get("id", "")).isdigit()]
return pad_id((max(used) if used else 0) + 1)
def chapter_is_blank(content: str) -> bool:
body = re.sub(r"^#+[^\n]*", "", content or "", flags=re.M).strip()
return not body
def extract_draft_marker(text: str) -> tuple[str, dict[str, Any] | None]:
marker_re = re.compile(r"<!--\s*GE_DRAFT\s+({.*?})\s*-->\s*$", re.S)
match = marker_re.search(text.strip())
if not match:
return text, None
try:
metadata = json.loads(match.group(1))
except json.JSONDecodeError:
metadata = {"draft_for": "chapter"}
cleaned = marker_re.sub("", text.strip()).rstrip()
return cleaned, metadata
def default_meta(title: str, slug: str, project_type: str = "novel") -> dict[str, Any]:
if project_type not in PROJECT_TYPES:
project_type = "novel"
return {
"title": title,
"slug": slug,
"projectType": project_type,
"createdAt": now_iso(),
"updatedAt": now_iso(),
"locked": False,
"activeChapter": "01",
"sections": [{"id": "part-1", "label": "Part 1", "chapterIds": []}],
"chapters": [],
}
def load_meta(book: Path) -> dict[str, Any]:
slug = book.name
meta = json_safe_load(book / "meta.json", default_meta(slug.replace("-", " ").title(), slug))
meta.setdefault("title", slug.replace("-", " ").title())
meta.setdefault("slug", slug)
if meta.get("projectType") not in PROJECT_TYPES:
meta["projectType"] = "novel"
meta.setdefault("locked", False)
meta.setdefault("activeChapter", "01")
meta.setdefault("sections", [{"id": "part-1", "label": "Part 1", "chapterIds": []}])
meta.setdefault("chapters", [])
scan_chapter_files(book, meta)
return meta
def save_meta(book: Path, meta: dict[str, Any]) -> None:
meta["updatedAt"] = now_iso()
write_json(book / "meta.json", meta)
def ensure_book(title: str, slug: str | None = None, project_type: str = "novel") -> dict[str, Any]:
if project_type not in PROJECT_TYPES:
project_type = "novel"
base_slug = slugify(slug or title)
safe_slug = base_slug
target = CONFIG.books_dir / safe_slug
suffix = 2
while slug is None and target.exists():
safe_slug = f"{base_slug}-{suffix}"
target = CONFIG.books_dir / safe_slug
suffix += 1
target.mkdir(parents=True, exist_ok=True)
(target / "canon").mkdir(exist_ok=True)
(target / "chapters").mkdir(exist_ok=True)
(target / "recaps").mkdir(exist_ok=True)
if not conversation_path(target).exists():
write_json(conversation_path(target), {"messages": [], "summary": ""})
if not (target / "meta.json").exists():
write_json(target / "meta.json", default_meta(title, safe_slug, project_type))
for name, default in DEFAULT_CANON.items():
path = target / "canon" / f"{name}.md"
if not path.exists():
write_text(path, default)
meta = load_meta(target)
if project_type == "research" and meta.get("projectType") != "research":
meta["projectType"] = "research"
save_meta(target, meta)
if meta.get("projectType") == "research":
ensure_research_dirs(target)
if not meta.get("chapters"):
write_text(chapter_path(target, "01"), "# Chapter 1\n\n")
write_text(chapter_plan_path(target, "01"), "")
write_text(chapter_transcript_path(target, "01"), "")
meta["chapters"] = [{"id": "01", "title": "Chapter 1", "status": "draft", "section": "part-1"}]
meta["activeChapter"] = "01"
save_meta(target, meta)
return load_book(safe_slug)
def scan_chapter_files(book: Path, meta: dict[str, Any]) -> None:
chapters_dir = book / "chapters"
chapters_dir.mkdir(parents=True, exist_ok=True)
existing = {str(item.get("id")): item for item in meta.get("chapters", [])}
for path in sorted(chapters_dir.glob("*.md")):
stem = path.stem
if stem.endswith(SIDE_SUFFIXES):
continue
if "." in stem:
continue
if not re.fullmatch(r"\d+", stem):
continue
cid = pad_id(stem)
if cid not in existing:
content = read_text(path)
existing[cid] = {
"id": cid,
"title": clean_title_from_markdown(content, f"Chapter {int(cid)}"),
"status": "draft",
"section": meta.get("sections", [{"id": "part-1"}])[0].get("id", "part-1"),
}
meta["chapters"] = sorted(existing.values(), key=lambda item: int(item.get("id", "0")))
section_ids = {section.get("id") for section in meta.get("sections", [])}
if not section_ids:
meta["sections"] = [{"id": "part-1", "label": "Part 1", "chapterIds": []}]
section_ids = {"part-1"}
default_section = next(iter(section_ids))
for chapter in meta["chapters"]:
chapter.setdefault("status", "draft")
chapter.setdefault("title", f"Chapter {int(chapter['id'])}")
if chapter.get("section") not in section_ids:
chapter["section"] = default_section
for section in meta.get("sections", []):
section["chapterIds"] = [chapter["id"] for chapter in meta["chapters"] if chapter.get("section") == section.get("id")]
if meta["chapters"] and meta.get("activeChapter") not in {c["id"] for c in meta["chapters"]}:
meta["activeChapter"] = meta["chapters"][-1]["id"]
def list_books() -> list[dict[str, Any]]:
CONFIG.books_dir.mkdir(parents=True, exist_ok=True)
books: list[dict[str, Any]] = []
for path in sorted(CONFIG.books_dir.iterdir()):
if not path.is_dir() or not (path / "meta.json").exists():
continue
meta = load_meta(path)
books.append(
{
"slug": path.name,
"title": meta.get("title", path.name),
"projectType": meta.get("projectType", "novel"),
"chapterCount": len(meta.get("chapters", [])),
"updatedAt": meta.get("updatedAt"),
"locked": bool(meta.get("locked")),
}
)
return books
def delete_book(slug: str, confirmation: str) -> dict[str, Any]:
book = book_dir(slug)
if not book.exists():
raise FileNotFoundError(f"Book not found: {slug}")
meta = load_meta(book)
if meta.get("locked"):
raise PermissionError("Project is locked. Unlock it before deleting.")
title = str(meta.get("title") or slug)
if confirmation.strip() != title:
raise ValueError("Deletion confirmation did not match the project title.")
books_root = CONFIG.books_dir.resolve()
target = book.resolve()
if target == books_root or books_root not in target.parents:
raise ValueError("Refusing to delete a path outside the books directory.")
if book.is_symlink():
raise ValueError("Refusing to delete a symlinked project directory.")
shutil.rmtree(target)
return {"ok": True, "deleted": slug, "books": list_books()}
def tail_text(path: Path, max_chars: int = 12000) -> str:
try:
text = read_text(path)
except Exception:
return ""
return text[-max_chars:]
def draft_bug_report(description: str, diagnostics: dict[str, Any] | None = None) -> dict[str, str]:
description = description.strip()
diagnostics = diagnostics or {}
status = preflight_payload()
payload = {
"description": description,
"client_diagnostics": diagnostics,
"server": {
"active_mode": active_mode(),
"requested_mode": CONFIG.requested_mode,
"books_dir": str(CONFIG.books_dir.resolve()),
"python": sys.version.split()[0],
"platform": sys.platform,
"preflight": status,
},
"recent_desktop_log": tail_text(ROOT / "desktop-shell.log", 9000),
}
fallback = (
"Generation Engine bug report\n\n"
"What happened:\n"
f"{description}\n\n"
"Useful diagnostics:\n"
f"{json.dumps(payload, indent=2, ensure_ascii=False)}\n"
)