@gobing-ai/knowledge-kit 0.1.29 → 0.1.30
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.
- package/.claude-plugin/marketplace.json +1 -1
- package/dist/board/api.js +8724 -3861
- package/dist/board/collect/index.js +69 -1
- package/dist/board/daily-voice/index.js +474 -265
- package/dist/board/itc/index.js +69 -1
- package/dist/board/wiki/index.css +1305 -0
- package/dist/board/wiki/index.js +1621 -0
- package/dist/index.js +34689 -28532
- package/package.json +1 -1
- package/plugins/generations/content-gen/dist/index.js +14 -1
- package/plugins/generations/core-facts-gen/dist/index.js +14 -1
- package/plugins/generations/daily-article-gen/dist/index.js +14 -1
- package/plugins/generations/dailynews-gen/dist/index.js +14 -1
- package/plugins/generations/episode-plan-gen/dist/index.js +32 -2
- package/plugins/generations/episode-plan-gen/src/index.ts +19 -1
- package/plugins/generations/gemini-tts/dist/index.js +14 -1
- package/plugins/generations/image-gen/dist/index.js +14 -1
- package/plugins/generations/music-gen/dist/index.js +15 -2
- package/plugins/generations/news-report-gen/dist/index.js +14 -1
- package/plugins/generations/vibe-voice-tts/dist/index.js +14 -1
- package/plugins/generations/video-gen/README.md +245 -8
- package/plugins/generations/video-gen/dist/index.js +22447 -4763
- package/plugins/generations/video-gen/package.json +1 -0
- package/plugins/generations/video-gen/presets/formats/avatar.yaml +5 -0
- package/plugins/generations/video-gen/presets/formats/editorial.yaml +6 -0
- package/plugins/generations/video-gen/presets/formats/hybrid-pip.yaml +5 -0
- package/plugins/generations/video-gen/presets/styles/daily-ai.yaml +5 -0
- package/plugins/generations/video-gen/presets/styles/neutral.yaml +3 -0
- package/plugins/generations/video-gen/python/colab_comfyui_h3.py +322 -0
- package/plugins/generations/video-gen/python/comfyui-h3-i2v-api.json +47 -0
- package/plugins/generations/video-gen/python/comfyui-h3-models.json +32 -0
- package/plugins/generations/video-gen/python/comfyui_model_cache.py +388 -0
- package/plugins/generations/video-gen/python/drive_client.py +187 -0
- package/plugins/generations/video-gen/src/brief-cli.ts +65 -0
- package/plugins/generations/video-gen/src/brief.ts +464 -0
- package/plugins/generations/video-gen/src/ccu-ledger.ts +206 -3
- package/plugins/generations/video-gen/src/colab-runner.ts +346 -35
- package/plugins/generations/video-gen/src/index.ts +141 -109
- package/plugins/generations/video-gen/src/inputs.ts +162 -4
- package/plugins/generations/video-gen/src/layout.ts +33 -0
- package/plugins/generations/video-gen/src/props.ts +27 -3
- package/plugins/generations/video-gen/src/remotion/AvatarReel.tsx +17 -1
- package/plugins/generations/video-gen/src/remotion/EditorialReel.tsx +17 -1
- package/plugins/generations/video-gen/src/remotion/Root.tsx +2 -0
- package/plugins/generations/video-gen/src/remotion/engine.ts +3 -7
- package/plugins/generations/video-gen/src/render.ts +25 -0
- package/plugins/generations/video-gen/src/request.ts +150 -20
- package/plugins/generations/video-gen/src/visual-provider.ts +116 -3
- package/plugins/generations/voice-gen/dist/index.js +14 -1
- package/plugins/generations/voxcpm-tts/dist/index.js +14 -1
- package/plugins/ingestions/aihot-ingest/dist/index.js +14 -1
- package/plugins/ingestions/horizon-ingest/dist/index.js +14 -1
- package/plugins/ingestions/last30days-ingest/dist/index.js +14 -1
- package/plugins/ingestions/web-search/dist/index.js +14 -1
- package/plugins/kk/config.example.yaml +1 -1
- package/plugins/kk/mcp-tools.yaml +47 -0
- package/plugins/kk/plugin.json +1 -1
- package/plugins/kk/publish-presets/itc-surfdash-locales.json +42 -0
- package/plugins/kk/scripts/daily-stages.ts +87 -6
- package/plugins/kk/scripts/kk-workflow-stages.ts +64 -9
- package/plugins/kk/scripts/video-stages.ts +332 -0
- package/plugins/kk/scripts/wiki-normalize-audio.ts +354 -0
- package/plugins/kk/scripts/wiki-normalize-document.ts +495 -0
- package/plugins/kk/scripts/wiki-normalize-stages.ts +96 -0
- package/plugins/kk/scripts/wiki-stage-runtime.ts +39 -0
- package/plugins/kk/skills/news-editorial/SKILL.md +2 -1
- package/plugins/kk/workflows/kk-collect.yaml +10 -0
- package/plugins/kk/workflows/kk-news-generate.yaml +70 -8
- package/plugins/kk/workflows/kk-smart-seo.yaml +8 -0
- package/plugins/kk/workflows/kk-storm-research.yaml +10 -0
- package/plugins/kk/workflows/kk-video-generate.yaml +169 -0
- package/plugins/kk/workflows/kk-wiki-digest.yaml +49 -0
- package/plugins/publishings/bilibili-pub/dist/index.js +281 -268
- package/plugins/publishings/bilibili-pub/dist/profile-check.js +202 -0
- package/plugins/publishings/cnblogs-pub/dist/index.js +281 -268
- package/plugins/publishings/cnblogs-pub/dist/profile-check.js +202 -0
- package/plugins/publishings/csdn-pub/dist/index.js +281 -268
- package/plugins/publishings/csdn-pub/dist/profile-check.js +216 -1
- package/plugins/publishings/emdash-pub/dist/index.js +33 -3
- package/plugins/publishings/infoq-pub/dist/index.js +281 -268
- package/plugins/publishings/infoq-pub/dist/profile-check.js +216 -1
- package/plugins/publishings/jike-pub/dist/index.js +281 -268
- package/plugins/publishings/jike-pub/dist/profile-check.js +216 -1
- package/plugins/publishings/juejin-pub/dist/index.js +281 -268
- package/plugins/publishings/juejin-pub/dist/profile-check.js +216 -1
- package/plugins/publishings/linkedin-pub/dist/index.js +281 -268
- package/plugins/publishings/linkedin-pub/dist/profile-check.js +216 -1
- package/plugins/publishings/medium-pub/dist/index.js +281 -268
- package/plugins/publishings/medium-pub/dist/profile-check.js +216 -1
- package/plugins/publishings/podcast-pub/dist/index.js +39 -9
- package/plugins/publishings/qiita-pub/dist/index.js +33 -3
- package/plugins/publishings/shipinhao-pub/dist/index.js +281 -268
- package/plugins/publishings/shipinhao-pub/dist/profile-check.js +175 -0
- package/plugins/publishings/sspai-pub/dist/index.js +281 -268
- package/plugins/publishings/sspai-pub/dist/profile-check.js +202 -0
- package/plugins/publishings/substack-pub/dist/index.js +281 -268
- package/plugins/publishings/substack-pub/dist/profile-check.js +216 -1
- package/plugins/publishings/surfdash-pub/dist/index.js +99 -39
- package/plugins/publishings/surfdash-pub/plugin.json +54 -0
- package/plugins/publishings/surfdash-pub/src/index.ts +36 -5
- package/plugins/publishings/threads-pub/dist/index.js +281 -268
- package/plugins/publishings/threads-pub/dist/profile-check.js +216 -1
- package/plugins/publishings/wechatmp-pub/dist/index.js +665 -451
- package/plugins/publishings/wechatmp-pub/dist/profile-check.js +215 -3
- package/plugins/publishings/weibo-pub/dist/index.js +281 -268
- package/plugins/publishings/weibo-pub/dist/profile-check.js +189 -1
- package/plugins/publishings/x-pub/dist/index.js +281 -268
- package/plugins/publishings/x-pub/dist/profile-check.js +216 -1
- package/plugins/publishings/xhs-pub/dist/index.js +281 -268
- package/plugins/publishings/xhs-pub/dist/profile-check.js +119 -1
- package/plugins/publishings/xiaoyuzhou-pub/dist/index.js +281 -268
- package/plugins/publishings/xiaoyuzhou-pub/dist/profile-check.js +202 -0
- package/plugins/publishings/youtube-pub/dist/index.js +14 -1
- package/plugins/publishings/zenn-pub/dist/index.js +37 -7
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Verified Drive cache for the MiniMax H3 FL2VA weights (D91 R6, task 0458).
|
|
3
|
+
|
|
4
|
+
Two operations, deliberately separate from inference:
|
|
5
|
+
|
|
6
|
+
populate --manifest <json> --dest <dir> --state <file> # local weights -> Drive cache
|
|
7
|
+
restore --manifest <json> --dest <dir> # Drive cache -> local weights
|
|
8
|
+
|
|
9
|
+
Why a provisioner instead of the mounted Drive the other workers use: a mount gives no upload
|
|
10
|
+
resume, no byte verification and no cache provenance. This module owns the pinned set, checks size
|
|
11
|
+
and SHA-256 before anything is promoted, resumes an interrupted upload from Drive's confirmed
|
|
12
|
+
offset, and never downloads a model from its upstream source (the Drive copy is the transport).
|
|
13
|
+
|
|
14
|
+
Design constraints (0458):
|
|
15
|
+
- The manifest is strict: unknown fields, unsafe relative paths and a malformed digest are refused.
|
|
16
|
+
- `populate` preflights free space for the missing bytes against the Drive quota.
|
|
17
|
+
- `restore` adopts an already-correct local file, otherwise streams into a sibling temp file and
|
|
18
|
+
promotes atomically with `os.replace` — a corrupt or truncated download never lands.
|
|
19
|
+
- Receipts carry paths, sizes and digests only: no tokens, no upload-session URLs, no weight bytes.
|
|
20
|
+
|
|
21
|
+
Stdlib only (urllib/hashlib/os): the plugin's uv environment ships faster-whisper, and a Drive client
|
|
22
|
+
belongs to the job that runs it, not to this repo's dependency graph.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import argparse
|
|
28
|
+
import hashlib
|
|
29
|
+
import json
|
|
30
|
+
import os
|
|
31
|
+
import sys
|
|
32
|
+
from dataclasses import dataclass
|
|
33
|
+
from pathlib import Path
|
|
34
|
+
from typing import Iterable, Protocol
|
|
35
|
+
|
|
36
|
+
SCHEMA_VERSION = 1
|
|
37
|
+
"""Keys a manifest row may carry. Anything else is a typo, not an extension point."""
|
|
38
|
+
ROW_KEYS = {"relativePath", "remote", "bytes", "sha256"}
|
|
39
|
+
MANIFEST_KEYS = {"schemaVersion", "group", "repo", "revision", "models"}
|
|
40
|
+
CHUNK_BYTES = 8 * 1024 * 1024
|
|
41
|
+
"""Drive's resumable upload requires a multiple of 256 KiB except for the final chunk."""
|
|
42
|
+
UPLOAD_CHUNK_BYTES = 256 * 1024
|
|
43
|
+
STATE_MODE = 0o600
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class CacheError(RuntimeError):
|
|
47
|
+
"""A refusal the operator can act on: it always names the model path."""
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass(frozen=True)
|
|
51
|
+
class ModelRow:
|
|
52
|
+
relative_path: str
|
|
53
|
+
remote: str
|
|
54
|
+
bytes: int
|
|
55
|
+
sha256: str
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass(frozen=True)
|
|
59
|
+
class Manifest:
|
|
60
|
+
group: str
|
|
61
|
+
repo: str
|
|
62
|
+
revision: str
|
|
63
|
+
models: tuple[ModelRow, ...]
|
|
64
|
+
|
|
65
|
+
@property
|
|
66
|
+
def total_bytes(self) -> int:
|
|
67
|
+
return sum(row.bytes for row in self.models)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class DriveTransport(Protocol):
|
|
71
|
+
"""The Drive surface this provisioner needs, so a test can supply a fake in one object."""
|
|
72
|
+
|
|
73
|
+
def free_bytes(self) -> int:
|
|
74
|
+
"""Remaining Drive quota in bytes."""
|
|
75
|
+
|
|
76
|
+
def find(self, name: str) -> dict | None:
|
|
77
|
+
"""The cache object named `name` (`None` when absent), with `size` and `appProperties`."""
|
|
78
|
+
|
|
79
|
+
def open_upload(self, *, name: str, size: int, sha256: str) -> str:
|
|
80
|
+
"""Start a resumable upload and return its session id (private, never in a receipt)."""
|
|
81
|
+
|
|
82
|
+
def upload_offset(self, session: str) -> int:
|
|
83
|
+
"""Drive's confirmed byte offset for `session`; an expired session raises `UploadExpired`."""
|
|
84
|
+
|
|
85
|
+
def upload_chunk(self, session: str, chunk: bytes, offset: int) -> int:
|
|
86
|
+
"""Send one chunk from `offset` and return the confirmed offset afterwards."""
|
|
87
|
+
|
|
88
|
+
def download(self, name: str, sink) -> None:
|
|
89
|
+
"""Stream the cache object's bytes into `sink` (a binary file object)."""
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class UploadExpired(CacheError):
|
|
93
|
+
"""The resumable session is gone (expired or already finalized)."""
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _digest_file(path: Path) -> tuple[int, str]:
|
|
97
|
+
sha = hashlib.sha256()
|
|
98
|
+
size = 0
|
|
99
|
+
with path.open("rb") as handle:
|
|
100
|
+
for chunk in iter(lambda: handle.read(CHUNK_BYTES), b""):
|
|
101
|
+
sha.update(chunk)
|
|
102
|
+
size += len(chunk)
|
|
103
|
+
return size, sha.hexdigest()
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def load_manifest(path: Path) -> Manifest:
|
|
107
|
+
"""Read and validate the pinned set; every refusal names the field and the file."""
|
|
108
|
+
try:
|
|
109
|
+
raw = json.loads(path.read_text(encoding="utf-8"))
|
|
110
|
+
except FileNotFoundError as error:
|
|
111
|
+
raise CacheError(f"manifest {path} is missing") from error
|
|
112
|
+
except json.JSONDecodeError as error:
|
|
113
|
+
raise CacheError(f"manifest {path} is not valid JSON: {error}") from error
|
|
114
|
+
if not isinstance(raw, dict):
|
|
115
|
+
raise CacheError(f"manifest {path} must be a JSON object")
|
|
116
|
+
unknown = set(raw) - MANIFEST_KEYS
|
|
117
|
+
if unknown:
|
|
118
|
+
raise CacheError(f"manifest {path} carries unknown field(s): {', '.join(sorted(unknown))}")
|
|
119
|
+
if raw.get("schemaVersion") != SCHEMA_VERSION:
|
|
120
|
+
raise CacheError(f"manifest {path} schemaVersion must be {SCHEMA_VERSION}")
|
|
121
|
+
for key in ("group", "repo", "revision"):
|
|
122
|
+
value = raw.get(key)
|
|
123
|
+
if not isinstance(value, str) or value.strip() == "":
|
|
124
|
+
raise CacheError(f"manifest {path} needs a non-empty {key}")
|
|
125
|
+
rows_raw = raw.get("models")
|
|
126
|
+
if not isinstance(rows_raw, list) or not rows_raw:
|
|
127
|
+
raise CacheError(f"manifest {path} needs a non-empty models list")
|
|
128
|
+
rows: list[ModelRow] = []
|
|
129
|
+
seen: set[str] = set()
|
|
130
|
+
for index, entry in enumerate(rows_raw):
|
|
131
|
+
if not isinstance(entry, dict):
|
|
132
|
+
raise CacheError(f"manifest {path} models[{index}] must be an object")
|
|
133
|
+
extra = set(entry) - ROW_KEYS
|
|
134
|
+
if extra:
|
|
135
|
+
raise CacheError(
|
|
136
|
+
f"manifest {path} models[{index}] carries unknown field(s): {', '.join(sorted(extra))}"
|
|
137
|
+
)
|
|
138
|
+
relative = entry.get("relativePath")
|
|
139
|
+
remote = entry.get("remote")
|
|
140
|
+
size = entry.get("bytes")
|
|
141
|
+
digest = entry.get("sha256")
|
|
142
|
+
if not isinstance(relative, str) or relative.strip() == "":
|
|
143
|
+
raise CacheError(f"manifest {path} models[{index}] needs a non-empty relativePath")
|
|
144
|
+
_assert_safe_relative(relative, path)
|
|
145
|
+
if relative in seen:
|
|
146
|
+
raise CacheError(f"manifest {path} repeats the model path {relative}")
|
|
147
|
+
seen.add(relative)
|
|
148
|
+
if not isinstance(remote, str) or remote.strip() == "":
|
|
149
|
+
raise CacheError(f"manifest {path} models[{index}] needs a non-empty remote path")
|
|
150
|
+
_assert_safe_relative(remote, path)
|
|
151
|
+
if not isinstance(size, int) or isinstance(size, bool) or size <= 0:
|
|
152
|
+
raise CacheError(f"manifest {path} models[{index}] bytes must be a positive integer")
|
|
153
|
+
if not isinstance(digest, str) or len(digest) != 64 or any(c not in "0123456789abcdef" for c in digest):
|
|
154
|
+
raise CacheError(f"manifest {path} models[{index}] sha256 must be 64 lowercase hex characters")
|
|
155
|
+
rows.append(ModelRow(relative_path=relative, remote=remote, bytes=size, sha256=digest))
|
|
156
|
+
return Manifest(group=raw["group"], repo=raw["repo"], revision=raw["revision"], models=tuple(rows))
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _assert_safe_relative(value: str, manifest: Path) -> None:
|
|
160
|
+
"""A manifest path is a portable relative path: no absolute, no `..`, no separators of the other OS."""
|
|
161
|
+
if value.startswith(("/", "\\")) or "\\" in value or ":" in value:
|
|
162
|
+
raise CacheError(f"manifest {manifest}: {value!r} must be a relative POSIX path")
|
|
163
|
+
parts = [part for part in value.split("/") if part not in ("", ".")]
|
|
164
|
+
if not parts or any(part == ".." for part in parts):
|
|
165
|
+
raise CacheError(f"manifest {manifest}: {value!r} must not traverse outside the cache")
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def resolve_local(dest: Path, relative: str) -> Path:
|
|
169
|
+
"""The destination path inside `dest`, re-checked so a manifest can never escape it."""
|
|
170
|
+
target = (dest / relative).resolve()
|
|
171
|
+
root = dest.resolve()
|
|
172
|
+
if root != target and root not in target.parents:
|
|
173
|
+
raise CacheError(f"model path {relative!r} escapes the cache directory {dest}")
|
|
174
|
+
return target
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def read_state(path: Path) -> dict:
|
|
178
|
+
"""The private resumable-session bookkeeping for this VM; absent means nothing in flight."""
|
|
179
|
+
try:
|
|
180
|
+
raw = json.loads(path.read_text(encoding="utf-8"))
|
|
181
|
+
except (FileNotFoundError, json.JSONDecodeError):
|
|
182
|
+
return {"uploads": {}}
|
|
183
|
+
return raw if isinstance(raw, dict) else {"uploads": {}}
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def write_state(path: Path, state: dict) -> None:
|
|
187
|
+
"""Persist session ids for resume, owner-only: they are upload capability, not evidence."""
|
|
188
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
189
|
+
path.write_text(json.dumps(state, indent=2, sort_keys=True), encoding="utf-8")
|
|
190
|
+
os.chmod(path, STATE_MODE)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _cache_name(row: ModelRow) -> str:
|
|
194
|
+
"""The Drive object name: the pinned relative path, so a cache listing is self-describing."""
|
|
195
|
+
return row.relative_path
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _matches(path: Path, row: ModelRow) -> bool:
|
|
199
|
+
if not path.is_file() or path.stat().st_size != row.bytes:
|
|
200
|
+
return False
|
|
201
|
+
_, digest = _digest_file(path)
|
|
202
|
+
return digest == row.sha256
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def populate(manifest: Manifest, dest: Path, transport: DriveTransport, state_path: Path) -> dict:
|
|
206
|
+
"""Upload every missing weight; verify size + digest locally and the object's metadata remotely."""
|
|
207
|
+
dest.mkdir(parents=True, exist_ok=True)
|
|
208
|
+
state = read_state(state_path)
|
|
209
|
+
# "Missing" means the CACHE lacks a verified object — not that this VM lacks a local file. A VM
|
|
210
|
+
# that already holds the weights is exactly the one that populates the cache.
|
|
211
|
+
missing = [row for row in manifest.models if not _remote_matches(transport.find(_cache_name(row)), row)]
|
|
212
|
+
missing_bytes = sum(row.bytes for row in missing)
|
|
213
|
+
if missing_bytes > 0 and transport.free_bytes() < missing_bytes:
|
|
214
|
+
raise CacheError(
|
|
215
|
+
f"the Drive cache cannot hold {manifest.group}: {missing_bytes} bytes needed, "
|
|
216
|
+
f"{transport.free_bytes()} free — free space or populate a subset"
|
|
217
|
+
)
|
|
218
|
+
uploaded: list[dict] = []
|
|
219
|
+
reused: list[dict] = []
|
|
220
|
+
for row in missing:
|
|
221
|
+
local = resolve_local(dest, row.relative_path)
|
|
222
|
+
if not local.is_file():
|
|
223
|
+
raise CacheError(
|
|
224
|
+
f"model {row.relative_path} is missing locally — download it first "
|
|
225
|
+
f"(cache population never fetches from the upstream source)"
|
|
226
|
+
)
|
|
227
|
+
size, digest = _digest_file(local)
|
|
228
|
+
if size != row.bytes or digest != row.sha256:
|
|
229
|
+
raise CacheError(
|
|
230
|
+
f"model {row.relative_path} does not match the pinned manifest "
|
|
231
|
+
f"({size} bytes / {digest[:12]}… vs {row.bytes} / {row.sha256[:12]}…) — "
|
|
232
|
+
f"re-download it from {manifest.repo}@{manifest.revision[:12]}"
|
|
233
|
+
)
|
|
234
|
+
name = _cache_name(row)
|
|
235
|
+
_upload_row(row, local, transport, state, state_path)
|
|
236
|
+
confirmed = transport.find(name)
|
|
237
|
+
if not _remote_matches(confirmed, row):
|
|
238
|
+
raise CacheError(
|
|
239
|
+
f"the Drive object for {row.relative_path} does not report the pinned size and digest "
|
|
240
|
+
f"after upload — re-run populate to resume it"
|
|
241
|
+
)
|
|
242
|
+
uploaded.append({"path": row.relative_path, "bytes": row.bytes, "sha256": row.sha256})
|
|
243
|
+
return {
|
|
244
|
+
"schemaVersion": SCHEMA_VERSION,
|
|
245
|
+
"operation": "populate",
|
|
246
|
+
"group": manifest.group,
|
|
247
|
+
"repo": manifest.repo,
|
|
248
|
+
"revision": manifest.revision,
|
|
249
|
+
"uploaded": uploaded,
|
|
250
|
+
"alreadyCached": reused,
|
|
251
|
+
"bytesUploaded": sum(entry["bytes"] for entry in uploaded),
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _remote_matches(obj: dict | None, row: ModelRow) -> bool:
|
|
256
|
+
"""A cache object is usable only when Drive reports the pinned size and digest."""
|
|
257
|
+
return obj is not None and obj.get("size") == row.bytes and _app_digest(obj) == row.sha256
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _app_digest(obj: dict) -> str | None:
|
|
261
|
+
props = obj.get("appProperties")
|
|
262
|
+
return props.get("sha256") if isinstance(props, dict) else None
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _upload_row(row: ModelRow, local: Path, transport: DriveTransport, state: dict, state_path: Path) -> None:
|
|
266
|
+
"""Upload one weight, resuming from the confirmed offset when this VM already started it."""
|
|
267
|
+
name = _cache_name(row)
|
|
268
|
+
session = state["uploads"].get(name)
|
|
269
|
+
offset = 0
|
|
270
|
+
if session is not None:
|
|
271
|
+
try:
|
|
272
|
+
offset = transport.upload_offset(session)
|
|
273
|
+
except UploadExpired:
|
|
274
|
+
# An expired session may have finalized before it died: adopt a completed object, else restart.
|
|
275
|
+
completed = transport.find(name)
|
|
276
|
+
if completed is not None and completed.get("size") == row.bytes and _app_digest(completed) == row.sha256:
|
|
277
|
+
state["uploads"].pop(name, None)
|
|
278
|
+
write_state(state_path, state)
|
|
279
|
+
return
|
|
280
|
+
session = None
|
|
281
|
+
offset = 0
|
|
282
|
+
if session is None:
|
|
283
|
+
session = transport.open_upload(name=name, size=row.bytes, sha256=row.sha256)
|
|
284
|
+
state["uploads"][name] = session
|
|
285
|
+
write_state(state_path, state)
|
|
286
|
+
with local.open("rb") as handle:
|
|
287
|
+
handle.seek(offset)
|
|
288
|
+
for chunk in iter(lambda: handle.read(UPLOAD_CHUNK_BYTES), b""):
|
|
289
|
+
offset = transport.upload_chunk(session, chunk, offset)
|
|
290
|
+
state["uploads"][name] = session
|
|
291
|
+
write_state(state_path, state)
|
|
292
|
+
state["uploads"].pop(name, None)
|
|
293
|
+
write_state(state_path, state)
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def restore(manifest: Manifest, dest: Path, transport: DriveTransport) -> dict:
|
|
297
|
+
"""Install every weight from the Drive cache, verifying bytes before an atomic promotion."""
|
|
298
|
+
dest.mkdir(parents=True, exist_ok=True)
|
|
299
|
+
adopted: list[dict] = []
|
|
300
|
+
restored: list[dict] = []
|
|
301
|
+
for row in manifest.models:
|
|
302
|
+
local = resolve_local(dest, row.relative_path)
|
|
303
|
+
if _matches(local, row):
|
|
304
|
+
adopted.append({"path": row.relative_path, "source": "local"})
|
|
305
|
+
continue
|
|
306
|
+
name = _cache_name(row)
|
|
307
|
+
remote = transport.find(name)
|
|
308
|
+
if not _remote_matches(remote, row):
|
|
309
|
+
raise CacheError(
|
|
310
|
+
f"the Drive cache has no verified object for {row.relative_path} — run populate first "
|
|
311
|
+
f"(expected {row.bytes} bytes / {row.sha256[:12]}…)"
|
|
312
|
+
)
|
|
313
|
+
local.parent.mkdir(parents=True, exist_ok=True)
|
|
314
|
+
temporary = local.with_name(f".{local.name}.part")
|
|
315
|
+
try:
|
|
316
|
+
with temporary.open("wb") as sink:
|
|
317
|
+
transport.download(name, sink)
|
|
318
|
+
size, digest = _digest_file(temporary)
|
|
319
|
+
if size != row.bytes or digest != row.sha256:
|
|
320
|
+
raise CacheError(
|
|
321
|
+
f"restored {row.relative_path} does not match the pinned manifest "
|
|
322
|
+
f"({size} bytes / {digest[:12]}… vs {row.bytes} / {row.sha256[:12]}…) — "
|
|
323
|
+
f"the cache object is corrupt; re-run populate"
|
|
324
|
+
)
|
|
325
|
+
os.replace(temporary, local)
|
|
326
|
+
finally:
|
|
327
|
+
if temporary.exists():
|
|
328
|
+
temporary.unlink()
|
|
329
|
+
restored.append({"path": row.relative_path, "source": "drive", "bytes": row.bytes, "sha256": row.sha256})
|
|
330
|
+
return {
|
|
331
|
+
"schemaVersion": SCHEMA_VERSION,
|
|
332
|
+
"operation": "restore",
|
|
333
|
+
"group": manifest.group,
|
|
334
|
+
"repo": manifest.repo,
|
|
335
|
+
"revision": manifest.revision,
|
|
336
|
+
"restored": restored,
|
|
337
|
+
"adopted": adopted,
|
|
338
|
+
"verified": True,
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def _write_receipt(path: Path | None, payload: dict) -> None:
|
|
343
|
+
if path is None:
|
|
344
|
+
return
|
|
345
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
346
|
+
path.write_text(json.dumps(payload, indent=4, sort_keys=True) + "\n", encoding="utf-8")
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def main(argv: Iterable[str] | None = None) -> int:
|
|
350
|
+
parser = argparse.ArgumentParser(prog="comfyui_model_cache", description=__doc__)
|
|
351
|
+
parser.add_argument("operation", choices=["populate", "restore", "manifest"])
|
|
352
|
+
parser.add_argument("--manifest", required=True)
|
|
353
|
+
parser.add_argument("--dest", default="")
|
|
354
|
+
parser.add_argument("--state", default="")
|
|
355
|
+
parser.add_argument("--receipt", default="")
|
|
356
|
+
args = parser.parse_args(list(argv) if argv is not None else None)
|
|
357
|
+
try:
|
|
358
|
+
manifest = load_manifest(Path(args.manifest))
|
|
359
|
+
if args.operation == "manifest":
|
|
360
|
+
print(json.dumps({
|
|
361
|
+
"group": manifest.group,
|
|
362
|
+
"repo": manifest.repo,
|
|
363
|
+
"revision": manifest.revision,
|
|
364
|
+
"models": len(manifest.models),
|
|
365
|
+
"bytes": manifest.total_bytes,
|
|
366
|
+
}))
|
|
367
|
+
return 0
|
|
368
|
+
if not args.dest:
|
|
369
|
+
raise CacheError(f"{args.operation} needs --dest <cache dir>")
|
|
370
|
+
from drive_client import drive_transport # the runtime's approved credential path
|
|
371
|
+
|
|
372
|
+
transport = drive_transport()
|
|
373
|
+
dest = Path(args.dest)
|
|
374
|
+
receipt = (
|
|
375
|
+
populate(manifest, dest, transport, Path(args.state or dest / ".cache-uploads.json"))
|
|
376
|
+
if args.operation == "populate"
|
|
377
|
+
else restore(manifest, dest, transport)
|
|
378
|
+
)
|
|
379
|
+
_write_receipt(Path(args.receipt) if args.receipt else None, receipt)
|
|
380
|
+
print(json.dumps(receipt))
|
|
381
|
+
return 0
|
|
382
|
+
except CacheError as error:
|
|
383
|
+
print(f"comfyui-model-cache: {error}", file=sys.stderr)
|
|
384
|
+
return 1
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
if __name__ == "__main__":
|
|
388
|
+
sys.exit(main())
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Minimal Google Drive v3 transport for the ComfyUI model cache (D91 R6, task 0458).
|
|
3
|
+
|
|
4
|
+
Scope: `drive.file` only — the app can see the objects it created and nothing else. Credentials come
|
|
5
|
+
from the runtime's approved secret file (`KK_DRIVE_TOKEN_FILE`, default
|
|
6
|
+
`~/.config/kk/drive-token.json`), which holds an OAuth access token (and optionally a refresh token);
|
|
7
|
+
no value from it is ever printed, logged or written into a receipt.
|
|
8
|
+
|
|
9
|
+
The whole Drive surface the provisioner needs is five calls here; `comfyui_model_cache.py` depends on
|
|
10
|
+
its `DriveTransport` protocol, not on this module, so a fixture can substitute a fake in one object.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
import os
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from urllib import error, request
|
|
19
|
+
|
|
20
|
+
API = "https://www.googleapis.com/drive/v3"
|
|
21
|
+
UPLOAD_API = "https://www.googleapis.com/upload/drive/v3"
|
|
22
|
+
DEFAULT_SCOPE = "https://www.googleapis.com/auth/drive.file"
|
|
23
|
+
TOKEN_ENV = "KK_DRIVE_TOKEN_FILE"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class DriveTransportError(RuntimeError):
|
|
27
|
+
"""A Drive call failed; the message names the operation, never the credential."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def token_path() -> Path:
|
|
31
|
+
configured = os.environ.get(TOKEN_ENV)
|
|
32
|
+
return Path(configured) if configured else Path.home() / ".config" / "kk" / "drive-token.json"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def load_access_token(path: Path | None = None) -> str:
|
|
36
|
+
"""Read the access token from the approved secret file; a missing file is an actionable refusal."""
|
|
37
|
+
target = path or token_path()
|
|
38
|
+
try:
|
|
39
|
+
raw = json.loads(target.read_text(encoding="utf-8"))
|
|
40
|
+
except FileNotFoundError as error:
|
|
41
|
+
raise DriveTransportError(
|
|
42
|
+
f"no Drive credential at {target} — provision one with the drive.file scope and set {TOKEN_ENV}"
|
|
43
|
+
) from error
|
|
44
|
+
except json.JSONDecodeError as error:
|
|
45
|
+
raise DriveTransportError(f"Drive credential at {target} is not valid JSON") from error
|
|
46
|
+
token = raw.get("access_token") if isinstance(raw, dict) else None
|
|
47
|
+
if not isinstance(token, str) or token == "":
|
|
48
|
+
raise DriveTransportError(f"Drive credential at {target} carries no access_token")
|
|
49
|
+
return token
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class HttpDriveTransport:
|
|
53
|
+
"""`DriveTransport` over the Drive v3 REST API, stdlib only."""
|
|
54
|
+
|
|
55
|
+
def __init__(self, token: str, folder_id: str = "") -> None:
|
|
56
|
+
self._token = token
|
|
57
|
+
self._folder_id = folder_id
|
|
58
|
+
|
|
59
|
+
def _headers(self) -> dict[str, str]:
|
|
60
|
+
return {"Authorization": f"Bearer {self._token}"}
|
|
61
|
+
|
|
62
|
+
def _call(self, method: str, url: str, body: bytes | None = None, headers: dict[str, str] | None = None) -> bytes:
|
|
63
|
+
merged = self._headers()
|
|
64
|
+
if headers:
|
|
65
|
+
merged.update(headers)
|
|
66
|
+
req = request.Request(url, data=body, method=method, headers=merged)
|
|
67
|
+
try:
|
|
68
|
+
with request.urlopen(req, timeout=120) as response: # noqa: S310 — fixed googleapis origin
|
|
69
|
+
return response.read()
|
|
70
|
+
except error.HTTPError as failure:
|
|
71
|
+
detail = failure.read().decode("utf-8", "replace")[:300]
|
|
72
|
+
raise DriveTransportError(f"Drive {method} {url.split('?')[0]} failed ({failure.code}): {detail}") from failure
|
|
73
|
+
except error.URLError as failure:
|
|
74
|
+
raise DriveTransportError(f"Drive {method} unreachable: {failure.reason}") from failure
|
|
75
|
+
|
|
76
|
+
def free_bytes(self) -> int:
|
|
77
|
+
about = json.loads(self._call("GET", f"{API}/about?fields=storageQuota"))
|
|
78
|
+
quota = about.get("storageQuota", {})
|
|
79
|
+
limit = int(quota.get("limit", "0"))
|
|
80
|
+
usage = int(quota.get("usage", "0"))
|
|
81
|
+
return max(limit - usage, 0)
|
|
82
|
+
|
|
83
|
+
def find(self, name: str) -> dict | None:
|
|
84
|
+
query = f"name='{name.replace(chr(39), chr(92) + chr(39))}' and trashed=false"
|
|
85
|
+
if self._folder_id:
|
|
86
|
+
query += f" and '{self._folder_id}' in parents"
|
|
87
|
+
url = f"{API}/files?q={request.quote(query)}&fields=files(id,name,size,appProperties)&pageSize=1"
|
|
88
|
+
payload = json.loads(self._call("GET", url))
|
|
89
|
+
files = payload.get("files") or []
|
|
90
|
+
return files[0] if files else None
|
|
91
|
+
|
|
92
|
+
def open_upload(self, *, name: str, size: int, sha256: str) -> str:
|
|
93
|
+
metadata = {"name": name, "appProperties": {"sha256": sha256}}
|
|
94
|
+
if self._folder_id:
|
|
95
|
+
metadata["parents"] = [self._folder_id]
|
|
96
|
+
body = json.dumps(metadata).encode("utf-8")
|
|
97
|
+
req = request.Request(
|
|
98
|
+
f"{UPLOAD_API}/files?uploadType=resumable&fields=id",
|
|
99
|
+
data=body,
|
|
100
|
+
method="POST",
|
|
101
|
+
headers={
|
|
102
|
+
**self._headers(),
|
|
103
|
+
"Content-Type": "application/json; charset=UTF-8",
|
|
104
|
+
"X-Upload-Content-Length": str(size),
|
|
105
|
+
# The session id is the Location header; it is capability, so it never leaves this object.
|
|
106
|
+
},
|
|
107
|
+
)
|
|
108
|
+
try:
|
|
109
|
+
with request.urlopen(req, timeout=120) as response: # noqa: S310 — fixed googleapis origin
|
|
110
|
+
session = response.headers.get("Location", "")
|
|
111
|
+
except error.HTTPError as failure:
|
|
112
|
+
detail = failure.read().decode("utf-8", "replace")[:300]
|
|
113
|
+
raise DriveTransportError(f"Drive resumable upload could not start ({failure.code}): {detail}") from failure
|
|
114
|
+
if session == "":
|
|
115
|
+
raise DriveTransportError("Drive resumable upload returned no session")
|
|
116
|
+
return session
|
|
117
|
+
|
|
118
|
+
def upload_offset(self, session: str) -> int:
|
|
119
|
+
req = request.Request(
|
|
120
|
+
session,
|
|
121
|
+
method="PUT",
|
|
122
|
+
headers={**self._headers(), "Content-Range": "bytes */*", "Content-Length": "0"},
|
|
123
|
+
)
|
|
124
|
+
try:
|
|
125
|
+
with request.urlopen(req, timeout=120): # noqa: S310 — session URL from Google
|
|
126
|
+
return 0
|
|
127
|
+
except error.HTTPError as failure:
|
|
128
|
+
if failure.code == 308:
|
|
129
|
+
rng = failure.headers.get("Range", "")
|
|
130
|
+
return int(rng.split("-")[-1]) + 1 if rng else 0
|
|
131
|
+
if failure.code in (404, 410):
|
|
132
|
+
from comfyui_model_cache import UploadExpired
|
|
133
|
+
|
|
134
|
+
raise UploadExpired("the resumable upload session expired") from failure
|
|
135
|
+
raise DriveTransportError(f"Drive upload status failed ({failure.code})") from failure
|
|
136
|
+
except error.URLError as failure:
|
|
137
|
+
raise DriveTransportError(f"Drive unreachable: {failure.reason}") from failure
|
|
138
|
+
|
|
139
|
+
def upload_chunk(self, session: str, chunk: bytes, offset: int) -> int:
|
|
140
|
+
end = offset + len(chunk) - 1
|
|
141
|
+
req = request.Request(
|
|
142
|
+
session,
|
|
143
|
+
data=chunk,
|
|
144
|
+
method="PUT",
|
|
145
|
+
headers={
|
|
146
|
+
**self._headers(),
|
|
147
|
+
"Content-Range": f"bytes {offset}-{end}/*",
|
|
148
|
+
"Content-Length": str(len(chunk)),
|
|
149
|
+
},
|
|
150
|
+
)
|
|
151
|
+
try:
|
|
152
|
+
with request.urlopen(req, timeout=600): # noqa: S310 — session URL from Google
|
|
153
|
+
return offset + len(chunk)
|
|
154
|
+
except error.HTTPError as failure:
|
|
155
|
+
if failure.code == 308:
|
|
156
|
+
rng = failure.headers.get("Range", "")
|
|
157
|
+
return int(rng.split("-")[-1]) + 1 if rng else offset
|
|
158
|
+
if failure.code in (404, 410):
|
|
159
|
+
from comfyui_model_cache import UploadExpired
|
|
160
|
+
|
|
161
|
+
raise UploadExpired("the resumable upload session expired") from failure
|
|
162
|
+
raise DriveTransportError(f"Drive upload chunk failed ({failure.code})") from failure
|
|
163
|
+
except error.URLError as failure:
|
|
164
|
+
raise DriveTransportError(f"Drive unreachable: {failure.reason}") from failure
|
|
165
|
+
|
|
166
|
+
def download(self, name: str, sink) -> None:
|
|
167
|
+
file_id = name
|
|
168
|
+
query = f"name='{name.replace(chr(39), chr(92) + chr(39))}' and trashed=false"
|
|
169
|
+
found = json.loads(self._call("GET", f"{API}/files?q={request.quote(query)}&fields=files(id)&pageSize=1"))
|
|
170
|
+
files = found.get("files") or []
|
|
171
|
+
if not files:
|
|
172
|
+
raise DriveTransportError(f"Drive cache object {name} is missing")
|
|
173
|
+
file_id = files[0]["id"]
|
|
174
|
+
req = request.Request(f"{API}/files/{file_id}?alt=media", method="GET", headers=self._headers())
|
|
175
|
+
try:
|
|
176
|
+
with request.urlopen(req, timeout=600) as response: # noqa: S310 — fixed googleapis origin
|
|
177
|
+
for block in iter(lambda: response.read(8 * 1024 * 1024), b""):
|
|
178
|
+
sink.write(block)
|
|
179
|
+
except error.HTTPError as failure:
|
|
180
|
+
raise DriveTransportError(f"Drive download of {name} failed ({failure.code})") from failure
|
|
181
|
+
except error.URLError as failure:
|
|
182
|
+
raise DriveTransportError(f"Drive unreachable: {failure.reason}") from failure
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def drive_transport() -> HttpDriveTransport:
|
|
186
|
+
"""The runtime's transport: credential from the approved secret file, cache folder from env."""
|
|
187
|
+
return HttpDriveTransport(load_access_token(), os.environ.get("KK_DRIVE_CACHE_FOLDER_ID", ""))
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { dirname } from 'node:path';
|
|
2
|
+
import { parseArgs } from 'node:util';
|
|
3
|
+
import { echo, echoError } from '@gobing-ai/ts-utils';
|
|
4
|
+
import { resolveVideoBrief } from './brief';
|
|
5
|
+
import { nodeFileSystem } from './fs';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* `bun <video-gen>/src/brief-cli.ts --brief <brief.yaml> --run-dir <dir> [--runtime-file <yaml>]`
|
|
9
|
+
*
|
|
10
|
+
* The stage-facing half of 0455's resolver: it turns an authored brief into (a) the `Doc[]` request
|
|
11
|
+
* the executor consumes and (b) a stdout summary the workflow records. Kept separate from
|
|
12
|
+
* `src/index.ts` because the plugin entry is a generator that takes a *request*, not a brief — the
|
|
13
|
+
* resolution belongs to the standalone workflow (0457), not to the generator contract.
|
|
14
|
+
*
|
|
15
|
+
* Paths are argv, never interpolated into a shell string, and a failure exits nonzero with one
|
|
16
|
+
* actionable line so a workflow state stops instead of rendering something nobody asked for.
|
|
17
|
+
*/
|
|
18
|
+
export async function main(argv: string[] = process.argv.slice(2)): Promise<number> {
|
|
19
|
+
const { values } = parseArgs({
|
|
20
|
+
args: argv,
|
|
21
|
+
options: {
|
|
22
|
+
brief: { type: 'string' },
|
|
23
|
+
'run-dir': { type: 'string' },
|
|
24
|
+
'runtime-file': { type: 'string' },
|
|
25
|
+
out: { type: 'string' },
|
|
26
|
+
},
|
|
27
|
+
});
|
|
28
|
+
try {
|
|
29
|
+
if (values.brief === undefined || values.brief === '') {
|
|
30
|
+
throw new Error('video-gen brief: missing --brief <brief.yaml>');
|
|
31
|
+
}
|
|
32
|
+
if (values.out === undefined || values.out === '') {
|
|
33
|
+
throw new Error('video-gen brief: missing --out <request.json>');
|
|
34
|
+
}
|
|
35
|
+
const resolved = await resolveVideoBrief(values.brief, {
|
|
36
|
+
fs: nodeFileSystem,
|
|
37
|
+
...(values['run-dir'] === undefined || values['run-dir'] === '' ? {} : { outputDir: values['run-dir'] }),
|
|
38
|
+
...(values['runtime-file'] === undefined || values['runtime-file'] === ''
|
|
39
|
+
? {}
|
|
40
|
+
: { runtimeFile: values['runtime-file'] }),
|
|
41
|
+
});
|
|
42
|
+
await nodeFileSystem.ensureDir(dirname(values.out));
|
|
43
|
+
await nodeFileSystem.writeFile(values.out, `${JSON.stringify(resolved.input, null, 4)}\n`);
|
|
44
|
+
// The output seam, not raw stdout (no-raw-stdout-stderr).
|
|
45
|
+
echo(
|
|
46
|
+
JSON.stringify({
|
|
47
|
+
format: resolved.format,
|
|
48
|
+
style: resolved.style,
|
|
49
|
+
visualMode: resolved.request.visualMode,
|
|
50
|
+
provider: resolved.request.provider ?? 'local-ken-burns',
|
|
51
|
+
durationTargetSec: resolved.request.durationTargetSec,
|
|
52
|
+
outputDir: resolved.request.outputDir,
|
|
53
|
+
sources: resolved.sources,
|
|
54
|
+
}),
|
|
55
|
+
);
|
|
56
|
+
return 0;
|
|
57
|
+
} catch (error: unknown) {
|
|
58
|
+
echoError(`video-gen brief failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
59
|
+
return 1;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
if (import.meta.main) {
|
|
64
|
+
process.exit(await main());
|
|
65
|
+
}
|