@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
|
@@ -1,11 +1,19 @@
|
|
|
1
|
-
import { extname, join } from 'node:path';
|
|
1
|
+
import { basename, dirname, extname, join } from 'node:path';
|
|
2
|
+
import { type RenderProvenance, RenderProvenanceSchema } from '@gobing-ai/kk-core';
|
|
3
|
+
import { type ExternalJobsDao, openStore } from '@gobing-ai/kk-store';
|
|
2
4
|
import type { FileSystem } from '@gobing-ai/ts-runtime';
|
|
3
5
|
import {
|
|
4
6
|
appendLedger,
|
|
5
7
|
assertBudget,
|
|
8
|
+
BUDGET_LOCK_NAME,
|
|
9
|
+
type BudgetLock,
|
|
10
|
+
budgetLeaseTtlMs,
|
|
11
|
+
budgetWindowMs,
|
|
6
12
|
type ColabGpu,
|
|
13
|
+
createKkBudgetLock,
|
|
7
14
|
DEFAULT_MAX_MONTHLY_CCU,
|
|
8
15
|
estimateCcu,
|
|
16
|
+
LOCK_DB_NAME,
|
|
9
17
|
readRolling30d,
|
|
10
18
|
} from './ccu-ledger';
|
|
11
19
|
import type { RunProcess } from './process';
|
|
@@ -17,7 +25,7 @@ import type { RunProcess } from './process';
|
|
|
17
25
|
*/
|
|
18
26
|
|
|
19
27
|
/** Job kinds this runner can dispatch (0452 adds the avatar workers). */
|
|
20
|
-
export type ColabJobType = 'wan21-i2v' | 'musetalk' | 'echomimic-v2';
|
|
28
|
+
export type ColabJobType = 'wan21-i2v' | 'comfyui-minimax-h3' | 'musetalk' | 'echomimic-v2';
|
|
21
29
|
|
|
22
30
|
/** One GPU job. */
|
|
23
31
|
export interface ColabJob {
|
|
@@ -27,6 +35,8 @@ export interface ColabJob {
|
|
|
27
35
|
script: string;
|
|
28
36
|
/** Local media, ordered as stills for Wan or portrait then audio for a presenter. */
|
|
29
37
|
inputPaths: string[];
|
|
38
|
+
/** Files the worker imports or reads beside itself, staged into `COLAB_SUPPORT_DIR` by basename. */
|
|
39
|
+
supportPaths?: string[];
|
|
30
40
|
/** Local output file names. */
|
|
31
41
|
outputNames: string[];
|
|
32
42
|
/** Remote directory the worker writes into. */
|
|
@@ -37,8 +47,13 @@ export interface ColabJob {
|
|
|
37
47
|
timeoutMs: number;
|
|
38
48
|
/** Extra `--env KEY=VALUE` pairs (the cache dir is added by the runner). */
|
|
39
49
|
env?: Record<string, string>;
|
|
50
|
+
/** H3 only: native frames at 24 fps for the generated clip. */
|
|
51
|
+
frames?: number;
|
|
40
52
|
}
|
|
41
53
|
|
|
54
|
+
/** Worker-reported provenance beyond the cache mode (H3 today); every field is optional. */
|
|
55
|
+
export type WorkerProvenance = Omit<RenderProvenance, 'cache'>;
|
|
56
|
+
|
|
42
57
|
/** Outcome of one job; `ok:false` never throws — the caller falls back (R5). */
|
|
43
58
|
export interface ColabJobResult {
|
|
44
59
|
ok: boolean;
|
|
@@ -46,6 +61,7 @@ export interface ColabJobResult {
|
|
|
46
61
|
durationSec: number;
|
|
47
62
|
cache: 'drive' | 'local';
|
|
48
63
|
estimatedCcu: number;
|
|
64
|
+
provenance?: WorkerProvenance;
|
|
49
65
|
error?: string;
|
|
50
66
|
}
|
|
51
67
|
|
|
@@ -63,30 +79,91 @@ export interface ColabDeps {
|
|
|
63
79
|
/** Extra wall-clock allowance on top of `timeoutMs` before the group is killed. */
|
|
64
80
|
killGraceMs?: number;
|
|
65
81
|
now?: () => number;
|
|
82
|
+
/** Works root shared by every video workflow. Defaults to the ledger's own directory. */
|
|
83
|
+
worksRoot?: string;
|
|
84
|
+
/** Admission claim seam; defaults to `kk lock` against `<worksRoot>/kk.db`. */
|
|
85
|
+
budgetLock?: BudgetLock;
|
|
86
|
+
/** Lease TTL override (tests pin a short one). */
|
|
87
|
+
lockTtlMs?: number;
|
|
88
|
+
/**
|
|
89
|
+
* Durable per-session reservation rows (ADR-066 R5). Opens `<worksRoot>/kk.db` by default;
|
|
90
|
+
* tests inject the DAO so no store file is created.
|
|
91
|
+
*/
|
|
92
|
+
externalJobs?: ExternalJobsDao;
|
|
93
|
+
/** Explicit store path override for the reservation rows. */
|
|
94
|
+
storePath?: string;
|
|
95
|
+
/** The managed external job this session belongs to (null for a direct caller). */
|
|
96
|
+
jobId?: string | null;
|
|
66
97
|
}
|
|
67
98
|
|
|
99
|
+
/** How long one reserve/settle critical section holds the budget claim (R5: SHORT claims only). */
|
|
100
|
+
export const BUDGET_CLAIM_HOLD_MS = 60_000;
|
|
101
|
+
/** Bounded retries for claim contention — a short claim is worth waiting for, never bypassing. */
|
|
102
|
+
export const BUDGET_CLAIM_ATTEMPTS = 5;
|
|
103
|
+
/** Delay between claim attempts. */
|
|
104
|
+
export const BUDGET_CLAIM_RETRY_MS = 200;
|
|
105
|
+
|
|
68
106
|
/** Default Drive cache path inside a Colab VM (R2). */
|
|
69
107
|
export const DEFAULT_COLAB_CACHE_DIR = '/content/drive/MyDrive/kk-video-cache';
|
|
70
108
|
/** Local allowance on top of the job deadline before the process group is killed (R1). */
|
|
71
109
|
export const LOCAL_KILL_GRACE_MS = 60_000;
|
|
72
110
|
/** Marker the worker prints on its last line with its JSON result. */
|
|
73
111
|
export const WORKER_RESULT_MARKER = 'KK_COLAB_RESULT ';
|
|
112
|
+
/** `colab exec --file` ships only the worker source; its siblings are staged here (the worker's default). */
|
|
113
|
+
export const COLAB_SUPPORT_DIR = '/content/kk-support';
|
|
74
114
|
/** Cap for `colab new`: a live A100 allocation took 2m45s, so the 120s per-stage cap is too short. */
|
|
75
115
|
export const COLAB_ALLOCATE_TIMEOUT_MS = 600_000;
|
|
76
116
|
const STAGE_TIMEOUT_MS = 120_000;
|
|
77
117
|
|
|
118
|
+
/**
|
|
119
|
+
* The remote artifact name one job type writes for output `index` (D91 R7, 0459).
|
|
120
|
+
*
|
|
121
|
+
* WHY explicit instead of a `wan21 ? clip : presenter` branch: the H3 job also writes clips, and the
|
|
122
|
+
* old branch would have downloaded `presenter.mp4` for it. The mapping is the runner's contract with
|
|
123
|
+
* each worker script, so it is data with a validation pass rather than a ternary.
|
|
124
|
+
*/
|
|
125
|
+
export function remoteArtifactName(jobType: ColabJob['jobType'], index: number): string {
|
|
126
|
+
if (!Number.isInteger(index) || index < 0) {
|
|
127
|
+
throw new Error(`colab: output index must be a non-negative integer (got ${index})`);
|
|
128
|
+
}
|
|
129
|
+
return jobType === 'wan21-i2v' || jobType === 'comfyui-minimax-h3' ? `clip-${index}.mp4` : 'presenter.mp4';
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Transfer only unique, expected basenames: a worker cannot make the runner fetch an arbitrary path. */
|
|
133
|
+
export function assertTransferableArtifact(name: string): string {
|
|
134
|
+
const base = name.split('/').pop() ?? '';
|
|
135
|
+
if (base === '' || base !== name || base.startsWith('.') || !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(base)) {
|
|
136
|
+
throw new Error(`colab: refusing to transfer unexpected artifact name ${JSON.stringify(name)}`);
|
|
137
|
+
}
|
|
138
|
+
return base;
|
|
139
|
+
}
|
|
140
|
+
|
|
78
141
|
/** A distinct session for each attempt, including retries for the same date and provider. */
|
|
79
142
|
export function sessionName(job: ColabJob): string {
|
|
80
143
|
return `kk-video-${job.runDate}-${job.jobType}-${crypto.randomUUID()}`;
|
|
81
144
|
}
|
|
82
145
|
|
|
146
|
+
/** Native H3 clip length in frames at 24 fps (the pinned graph's baseline; ~3 s). */
|
|
147
|
+
export const H3_DEFAULT_FRAMES = 73;
|
|
148
|
+
|
|
83
149
|
/** Execute the local worker in the session where the media has been staged. */
|
|
84
150
|
export function buildColabArgv(job: ColabJob, session: string, cacheDir: string = DEFAULT_COLAB_CACHE_DIR): string[] {
|
|
85
151
|
const inputs = job.inputPaths.map((path, index) => `/content/kk-input-${index}${extname(path)}`);
|
|
152
|
+
// Each worker's argv is its own contract: Wan and H3 take stills and write clip-N.mp4; a
|
|
153
|
+
// presenter worker takes portrait + audio and writes presenter.mp4.
|
|
86
154
|
const scriptArgs =
|
|
87
155
|
job.jobType === 'wan21-i2v'
|
|
88
156
|
? ['--images', ...inputs, '--out-dir', job.remoteDir]
|
|
89
|
-
:
|
|
157
|
+
: job.jobType === 'comfyui-minimax-h3'
|
|
158
|
+
? [
|
|
159
|
+
'--first-frame',
|
|
160
|
+
inputs[0],
|
|
161
|
+
'--out-dir',
|
|
162
|
+
job.remoteDir,
|
|
163
|
+
'--frames',
|
|
164
|
+
String(job.frames ?? H3_DEFAULT_FRAMES),
|
|
165
|
+
]
|
|
166
|
+
: ['--portrait', inputs[0], '--audio', inputs[1], '--out', join(job.remoteDir, 'presenter.mp4')];
|
|
90
167
|
const env = {
|
|
91
168
|
KK_COLAB_CACHE_DIR: cacheDir,
|
|
92
169
|
...job.env,
|
|
@@ -118,7 +195,9 @@ export function buildStopArgv(session: string): string[] {
|
|
|
118
195
|
}
|
|
119
196
|
|
|
120
197
|
/** Parse the worker's `KK_COLAB_RESULT {json}` line; a silent worker reports no result. */
|
|
121
|
-
export function parseWorkerResult(
|
|
198
|
+
export function parseWorkerResult(
|
|
199
|
+
stdout: string,
|
|
200
|
+
): { cache: 'drive' | 'local'; outputs?: string[]; provenance?: WorkerProvenance } | null {
|
|
122
201
|
for (const line of stdout.split('\n').reverse()) {
|
|
123
202
|
const trimmed = line.trim();
|
|
124
203
|
if (!trimmed.startsWith(WORKER_RESULT_MARKER)) continue;
|
|
@@ -128,7 +207,21 @@ export function parseWorkerResult(stdout: string): { cache: 'drive' | 'local'; o
|
|
|
128
207
|
const outputs = Array.isArray(parsed.outputs)
|
|
129
208
|
? parsed.outputs.filter((entry): entry is string => typeof entry === 'string')
|
|
130
209
|
: undefined;
|
|
131
|
-
|
|
210
|
+
// Each field is validated on its own, so one malformed key never discards the rest.
|
|
211
|
+
const field = <K extends keyof WorkerProvenance>(key: K) => {
|
|
212
|
+
const checked = RenderProvenanceSchema.shape[key].safeParse(parsed[key]);
|
|
213
|
+
return checked.success && checked.data !== undefined ? { [key]: checked.data } : {};
|
|
214
|
+
};
|
|
215
|
+
const provenance: WorkerProvenance = {
|
|
216
|
+
...field('comfyuiCommit'),
|
|
217
|
+
...field('comfyuiRuntimeCommit'),
|
|
218
|
+
...field('modelCache'),
|
|
219
|
+
};
|
|
220
|
+
return {
|
|
221
|
+
cache,
|
|
222
|
+
...(outputs === undefined ? {} : { outputs }),
|
|
223
|
+
...(Object.keys(provenance).length === 0 ? {} : { provenance }),
|
|
224
|
+
};
|
|
132
225
|
} catch {
|
|
133
226
|
return null;
|
|
134
227
|
}
|
|
@@ -141,24 +234,237 @@ function bounded(text: string): string {
|
|
|
141
234
|
}
|
|
142
235
|
|
|
143
236
|
/**
|
|
144
|
-
* Run one GPU job:
|
|
145
|
-
* Every failure mode returns `ok:false` with a cause the caller turns
|
|
237
|
+
* Run one GPU job: **reserve** (short claim) → create → upload → execute → download → stop →
|
|
238
|
+
* **settle** (short claim). Every failure mode returns `ok:false` with a cause the caller turns
|
|
239
|
+
* into a fallback warning.
|
|
240
|
+
*
|
|
241
|
+
* WHY the claim is short and split in two (task 0464 R5): the ledger is read-then-appended, so a
|
|
242
|
+
* cross-process claim must still serialize the read/append pair — but holding it for the whole
|
|
243
|
+
* render serialized every direct caller behind a 30-minute job. A reservation written BEFORE
|
|
244
|
+
* allocation is visible to the next reader, so correctness no longer depends on holding the claim
|
|
245
|
+
* for the render, and the reservation is the number that guards admission.
|
|
146
246
|
*/
|
|
147
247
|
export async function runColabJob(job: ColabJob, deps: ColabDeps): Promise<ColabJobResult> {
|
|
248
|
+
const killGraceMs = deps.killGraceMs ?? LOCAL_KILL_GRACE_MS;
|
|
249
|
+
const worksRoot = deps.worksRoot ?? dirname(deps.ledgerPath);
|
|
250
|
+
const lock =
|
|
251
|
+
deps.budgetLock ?? createKkBudgetLock({ runProcess: deps.runProcess, dbPath: join(worksRoot, LOCK_DB_NAME) });
|
|
252
|
+
const session = sessionName(job);
|
|
253
|
+
const ttlMs = deps.lockTtlMs ?? budgetLeaseTtlMs(job.timeoutMs, killGraceMs);
|
|
148
254
|
const now = deps.now ?? Date.now;
|
|
149
|
-
const cacheDir = deps.cacheDir ?? DEFAULT_COLAB_CACHE_DIR;
|
|
150
255
|
const maxMonthlyCcu = deps.maxMonthlyCcu ?? DEFAULT_MAX_MONTHLY_CCU;
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
const
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
256
|
+
// The reservation is the same worst-case window the old whole-job claim projected, so
|
|
257
|
+
// admission and accounting still agree about what one attempt may cost.
|
|
258
|
+
const plannedCcu = estimateCcu(job.gpu, budgetWindowMs(job.timeoutMs, killGraceMs) / 1000);
|
|
259
|
+
|
|
260
|
+
const reserved = await reserveBudget({ job, deps, lock, session, plannedCcu, now, maxMonthlyCcu, ttlMs });
|
|
261
|
+
if ('error' in reserved) {
|
|
262
|
+
// Includes a reservation whose claim could not be released: the claim would strand the
|
|
263
|
+
// NEXT run until its TTL, and nothing has launched yet, so this is a refusal.
|
|
264
|
+
// A refusal is a pre-allocation decision: nothing launches, nothing is billed.
|
|
265
|
+
return {
|
|
266
|
+
ok: false,
|
|
267
|
+
outputs: [],
|
|
268
|
+
durationSec: 0,
|
|
269
|
+
cache: 'local',
|
|
270
|
+
estimatedCcu: 0,
|
|
271
|
+
error: reserved.error,
|
|
272
|
+
};
|
|
157
273
|
}
|
|
158
274
|
|
|
159
|
-
const
|
|
275
|
+
const outcome = await runReservedJob(job, deps, { session, killGraceMs });
|
|
276
|
+
// Stop before refund: a reservation whose teardown was not confirmed stays conservative.
|
|
277
|
+
await settleBudget({ job, deps, lock, session, plannedCcu, outcome, now, ttlMs });
|
|
278
|
+
return outcome.result;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/** The parts of one attempt settlement needs that only the runner knows. */
|
|
282
|
+
interface AttemptOutcome {
|
|
283
|
+
result: ColabJobResult;
|
|
284
|
+
/** The attempt's terminal class, carried into the settlement line. */
|
|
285
|
+
status: 'ok' | 'failed' | 'timeout';
|
|
286
|
+
/** A confirmed `colab stop`; anything else keeps the full reservation. */
|
|
287
|
+
stopped: boolean;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* Reserve the full projected window under one short claim, then record the session row.
|
|
292
|
+
*
|
|
293
|
+
* The session row is persisted BEFORE `colab new`, so an uncertain allocation is still stoppable
|
|
294
|
+
* from `kk job status`/`cancel` after a crash.
|
|
295
|
+
*/
|
|
296
|
+
async function reserveBudget(args: {
|
|
297
|
+
job: ColabJob;
|
|
298
|
+
deps: ColabDeps;
|
|
299
|
+
lock: BudgetLock;
|
|
300
|
+
session: string;
|
|
301
|
+
plannedCcu: number;
|
|
302
|
+
now: () => number;
|
|
303
|
+
maxMonthlyCcu: number;
|
|
304
|
+
ttlMs: number;
|
|
305
|
+
}): Promise<{ ok: true } | { error: string }> {
|
|
306
|
+
const claim = await acquireBounded(args.lock, args.session, args.ttlMs);
|
|
307
|
+
if (!claim.acquired) {
|
|
308
|
+
return {
|
|
309
|
+
error: `another video run holds the colab budget claim${claim.holder === undefined || claim.holder === null ? '' : ` (${claim.holder})`}; retry after it settles`,
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
let outcome: { ok: true } | { error: string } = { ok: true };
|
|
313
|
+
let releaseError: string | undefined;
|
|
314
|
+
try {
|
|
315
|
+
const rolling = await readRolling30d(args.deps.ledgerPath, args.now(), args.deps.fs);
|
|
316
|
+
const budget = assertBudget({
|
|
317
|
+
rollingCcu: rolling.totalCcu,
|
|
318
|
+
projectedCcu: args.plannedCcu,
|
|
319
|
+
maxMonthlyCcu: args.maxMonthlyCcu,
|
|
320
|
+
});
|
|
321
|
+
if ('error' in budget) {
|
|
322
|
+
outcome = { error: budget.error };
|
|
323
|
+
} else {
|
|
324
|
+
const startedAt = args.now();
|
|
325
|
+
await appendLedger(
|
|
326
|
+
args.deps.ledgerPath,
|
|
327
|
+
{
|
|
328
|
+
timestamp: new Date(startedAt).toISOString(),
|
|
329
|
+
gpu: args.job.gpu,
|
|
330
|
+
durationSec: 0,
|
|
331
|
+
estimatedCcu: args.plannedCcu,
|
|
332
|
+
jobType: args.job.jobType,
|
|
333
|
+
status: 'ok',
|
|
334
|
+
kind: 'reserve',
|
|
335
|
+
ref: args.session,
|
|
336
|
+
},
|
|
337
|
+
args.deps.fs,
|
|
338
|
+
);
|
|
339
|
+
await withExternalJobs(args.deps, (dao) =>
|
|
340
|
+
dao.recordSession({
|
|
341
|
+
ref: args.session,
|
|
342
|
+
jobId: args.deps.jobId ?? null,
|
|
343
|
+
session: args.session,
|
|
344
|
+
gpu: args.job.gpu,
|
|
345
|
+
startedAt,
|
|
346
|
+
reservedCcu: args.plannedCcu,
|
|
347
|
+
ledgerPath: args.deps.ledgerPath,
|
|
348
|
+
now: startedAt,
|
|
349
|
+
}),
|
|
350
|
+
);
|
|
351
|
+
}
|
|
352
|
+
} finally {
|
|
353
|
+
releaseError = await releaseQuietly(args.lock, args.session);
|
|
354
|
+
}
|
|
355
|
+
if (releaseError !== undefined) {
|
|
356
|
+
// A stranded claim blocks the next run until its short TTL; name it instead of hiding it.
|
|
357
|
+
return { error: `colab budget claim could not be released: ${releaseError}` };
|
|
358
|
+
}
|
|
359
|
+
return outcome;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* Settle the reservation exactly once: stop marked, then one `settle` delta line.
|
|
364
|
+
*
|
|
365
|
+
* A reservation is NOT refunded when teardown could not be confirmed — the operator pays for an
|
|
366
|
+
* uncertain stop rather than getting budget credited for a session that may still be running.
|
|
367
|
+
*/
|
|
368
|
+
async function settleBudget(args: {
|
|
369
|
+
job: ColabJob;
|
|
370
|
+
deps: ColabDeps;
|
|
371
|
+
lock: BudgetLock;
|
|
372
|
+
session: string;
|
|
373
|
+
plannedCcu: number;
|
|
374
|
+
outcome: AttemptOutcome;
|
|
375
|
+
now: () => number;
|
|
376
|
+
ttlMs: number;
|
|
377
|
+
}): Promise<void> {
|
|
378
|
+
if (!args.outcome.stopped) return;
|
|
379
|
+
const claim = await acquireBounded(args.lock, args.session, args.ttlMs);
|
|
380
|
+
if (!claim.acquired) return;
|
|
381
|
+
try {
|
|
382
|
+
const settledFirst = await withExternalJobs(args.deps, (dao) => dao.markSettled(args.session, args.now()));
|
|
383
|
+
if (!settledFirst) return;
|
|
384
|
+
const actual = estimateCcu(args.job.gpu, args.outcome.result.durationSec);
|
|
385
|
+
await appendLedger(
|
|
386
|
+
args.deps.ledgerPath,
|
|
387
|
+
{
|
|
388
|
+
timestamp: new Date(args.now()).toISOString(),
|
|
389
|
+
gpu: args.job.gpu,
|
|
390
|
+
durationSec: args.outcome.result.durationSec,
|
|
391
|
+
// The delta against the reservation, not a second charge.
|
|
392
|
+
estimatedCcu: Number((actual - args.plannedCcu).toFixed(4)),
|
|
393
|
+
jobType: args.job.jobType,
|
|
394
|
+
status: args.outcome.status,
|
|
395
|
+
kind: 'settle',
|
|
396
|
+
ref: args.session,
|
|
397
|
+
},
|
|
398
|
+
args.deps.fs,
|
|
399
|
+
);
|
|
400
|
+
} finally {
|
|
401
|
+
await releaseQuietly(args.lock, args.session);
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/** Take the budget claim, retrying a bounded number of times for a short critical section. */
|
|
406
|
+
async function acquireBounded(
|
|
407
|
+
lock: BudgetLock,
|
|
408
|
+
session: string,
|
|
409
|
+
ttlMs: number,
|
|
410
|
+
): Promise<{ acquired: boolean; holder?: string | null }> {
|
|
411
|
+
let last: { acquired: boolean; holder?: string | null } = { acquired: false };
|
|
412
|
+
for (let attempt = 0; attempt < BUDGET_CLAIM_ATTEMPTS; attempt += 1) {
|
|
413
|
+
last = await lock.acquire({ name: BUDGET_LOCK_NAME, owner: session, ttlMs: BUDGET_CLAIM_HOLD_MS });
|
|
414
|
+
if (last.acquired) return last;
|
|
415
|
+
await Bun.sleep(BUDGET_CLAIM_RETRY_MS);
|
|
416
|
+
}
|
|
417
|
+
void ttlMs;
|
|
418
|
+
return last;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/**
|
|
422
|
+
* Release the claim.
|
|
423
|
+
*
|
|
424
|
+
* @returns the failure message, or `undefined` when the claim was freed. The reserve phase turns
|
|
425
|
+
* it into a pre-allocation refusal; the settle phase ignores it, because accounting has already
|
|
426
|
+
* landed and a stale claim expires on its own short TTL.
|
|
427
|
+
*/
|
|
428
|
+
async function releaseQuietly(lock: BudgetLock, session: string): Promise<string | undefined> {
|
|
429
|
+
try {
|
|
430
|
+
await lock.release({ name: BUDGET_LOCK_NAME, owner: session });
|
|
431
|
+
return undefined;
|
|
432
|
+
} catch (thrown) {
|
|
433
|
+
return thrown instanceof Error ? thrown.message : String(thrown);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/** Run `fn` against the reservation DAO, opening and closing `<worksRoot>/kk.db` when needed. */
|
|
438
|
+
async function withExternalJobs<T>(deps: ColabDeps, fn: (dao: ExternalJobsDao) => Promise<T>): Promise<T | undefined> {
|
|
439
|
+
if (deps.externalJobs !== undefined) return fn(deps.externalJobs);
|
|
440
|
+
try {
|
|
441
|
+
const store = await openStore({
|
|
442
|
+
path: deps.storePath ?? join(deps.worksRoot ?? dirname(deps.ledgerPath), LOCK_DB_NAME),
|
|
443
|
+
});
|
|
444
|
+
try {
|
|
445
|
+
return await fn(store.externalJobs);
|
|
446
|
+
} finally {
|
|
447
|
+
await store.close();
|
|
448
|
+
}
|
|
449
|
+
} catch {
|
|
450
|
+
// The ledger reservation already guarded admission; a store that cannot open must not
|
|
451
|
+
// turn a booked render into a crash. Reconciliation then over-counts (conservative).
|
|
452
|
+
return undefined;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/** The reserved section: lifecycle → teardown. Accounting is the caller's reserve/settle pair. */
|
|
457
|
+
async function runReservedJob(
|
|
458
|
+
job: ColabJob,
|
|
459
|
+
deps: ColabDeps,
|
|
460
|
+
claim: { session: string; killGraceMs: number },
|
|
461
|
+
): Promise<AttemptOutcome> {
|
|
462
|
+
const now = deps.now ?? Date.now;
|
|
463
|
+
const cacheDir = deps.cacheDir ?? DEFAULT_COLAB_CACHE_DIR;
|
|
464
|
+
|
|
465
|
+
const session = claim.session;
|
|
160
466
|
const startedAt = now();
|
|
161
|
-
const deadline = startedAt + job.timeoutMs +
|
|
467
|
+
const deadline = startedAt + job.timeoutMs + claim.killGraceMs;
|
|
162
468
|
const remaining = (): number => {
|
|
163
469
|
const timeoutMs = deadline - now();
|
|
164
470
|
if (timeoutMs <= 0) throw new Error('colab job timed out');
|
|
@@ -166,8 +472,11 @@ export async function runColabJob(job: ColabJob, deps: ColabDeps): Promise<Colab
|
|
|
166
472
|
};
|
|
167
473
|
let outputs: string[] = [];
|
|
168
474
|
let cache: 'drive' | 'local' = 'local';
|
|
475
|
+
let provenance: WorkerProvenance | undefined;
|
|
169
476
|
let error: string | undefined;
|
|
170
477
|
let status: 'ok' | 'failed' | 'timeout' = 'failed';
|
|
478
|
+
// Declared outside the teardown block because settlement reads it after the finally runs.
|
|
479
|
+
let stopError: string | undefined;
|
|
171
480
|
|
|
172
481
|
try {
|
|
173
482
|
const cli = process.env.KK_COLAB_BIN ?? 'colab';
|
|
@@ -188,6 +497,9 @@ export async function runColabJob(job: ColabJob, deps: ColabDeps): Promise<Colab
|
|
|
188
497
|
for (const [index, path] of job.inputPaths.entries()) {
|
|
189
498
|
await stage([cli, 'upload', path, `/content/kk-input-${index}${extname(path)}`, '--session', session]);
|
|
190
499
|
}
|
|
500
|
+
for (const path of job.supportPaths ?? []) {
|
|
501
|
+
await stage([cli, 'upload', path, `${COLAB_SUPPORT_DIR}/${basename(path)}`, '--session', session]);
|
|
502
|
+
}
|
|
191
503
|
const result = await deps.runProcess(buildColabArgv(job, session, cacheDir), {
|
|
192
504
|
timeoutMs: remaining(),
|
|
193
505
|
});
|
|
@@ -199,10 +511,17 @@ export async function runColabJob(job: ColabJob, deps: ColabDeps): Promise<Colab
|
|
|
199
511
|
error = 'colab worker produced no KK_COLAB_RESULT line';
|
|
200
512
|
} else {
|
|
201
513
|
cache = worker.cache;
|
|
514
|
+
provenance = worker.provenance;
|
|
202
515
|
const downloaded: string[] = [];
|
|
516
|
+
const seenRemote = new Set<string>();
|
|
203
517
|
for (const [index, name] of job.outputNames.entries()) {
|
|
204
518
|
const localPath = join(deps.outputDir, name);
|
|
205
|
-
const remoteName = job.jobType
|
|
519
|
+
const remoteName = assertTransferableArtifact(remoteArtifactName(job.jobType, index));
|
|
520
|
+
if (seenRemote.has(remoteName)) {
|
|
521
|
+
error = `colab worker declared the same remote artifact twice: ${remoteName}`;
|
|
522
|
+
break;
|
|
523
|
+
}
|
|
524
|
+
seenRemote.add(remoteName);
|
|
206
525
|
const download = await deps.runProcess(
|
|
207
526
|
buildDownloadArgv(session, join(job.remoteDir, remoteName), localPath),
|
|
208
527
|
{ timeoutMs: Math.min(STAGE_TIMEOUT_MS, remaining()) },
|
|
@@ -226,7 +545,6 @@ export async function runColabJob(job: ColabJob, deps: ColabDeps): Promise<Colab
|
|
|
226
545
|
error = `colab run threw: ${thrown instanceof Error ? thrown.message : String(thrown)}`;
|
|
227
546
|
status = /timeout/i.test(error) ? 'timeout' : 'failed';
|
|
228
547
|
} finally {
|
|
229
|
-
let stopError: string | undefined;
|
|
230
548
|
try {
|
|
231
549
|
const stopped = await deps.runProcess(buildStopArgv(session), { timeoutMs: 60_000 });
|
|
232
550
|
if (stopped.code !== 0) stopError = bounded(stopped.stderr) || `exit ${stopped.code}`;
|
|
@@ -241,25 +559,18 @@ export async function runColabJob(job: ColabJob, deps: ColabDeps): Promise<Colab
|
|
|
241
559
|
|
|
242
560
|
const durationSec = Number(((now() - startedAt) / 1000).toFixed(2));
|
|
243
561
|
const estimatedCcu = estimateCcu(job.gpu, durationSec);
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
562
|
+
return {
|
|
563
|
+
status,
|
|
564
|
+
// Teardown is the settlement precondition: an unconfirmed stop keeps the reservation.
|
|
565
|
+
stopped: stopError === undefined,
|
|
566
|
+
result: {
|
|
567
|
+
ok: status === 'ok',
|
|
568
|
+
outputs,
|
|
249
569
|
durationSec,
|
|
570
|
+
cache,
|
|
250
571
|
estimatedCcu,
|
|
251
|
-
|
|
252
|
-
|
|
572
|
+
...(provenance === undefined ? {} : { provenance }),
|
|
573
|
+
...(error === undefined ? {} : { error }),
|
|
253
574
|
},
|
|
254
|
-
deps.fs,
|
|
255
|
-
);
|
|
256
|
-
|
|
257
|
-
return {
|
|
258
|
-
ok: status === 'ok',
|
|
259
|
-
outputs,
|
|
260
|
-
durationSec,
|
|
261
|
-
cache,
|
|
262
|
-
estimatedCcu,
|
|
263
|
-
...(error === undefined ? {} : { error }),
|
|
264
575
|
};
|
|
265
576
|
}
|