@2kog/kacha 0.1.2 → 0.2.0

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/README.md CHANGED
@@ -30,7 +30,10 @@ kacha
30
30
 
31
31
  ```text
32
32
  my-project/
33
+ ├── .env
34
+ ├── .gitattributes
33
35
  ├── .gitignore
36
+ ├── .lfsconfig
34
37
  ├── AGENTS.md
35
38
  ├── README.md
36
39
  └── assets/
@@ -41,13 +44,15 @@ my-project/
41
44
  └── audio/
42
45
  ```
43
46
 
44
- 每个资产库附有目录说明。单项资产用 `index.json` 登记元数据,用 `README.md` 记录制作说明。需要分组时,可在每层分组目录放置 `group.json`。初始化可重复执行,已有文件会保留。
47
+ 每个资产库附有目录说明。单项资产用 `index.json` 登记元数据,用 `README.md` 记录制作说明。需要分组时,可在每层分组目录放置 `group.json`。`kacha init` 会补齐空白 OSS 配置 `.env`、Git LFS 规则 `.gitattributes`、外部 LFS 标记 `.lfsconfig` 和 `.gitignore`。初始化可重复执行,已有文件及凭据会保留。
48
+
49
+ 咔嚓的通用制作技能随 npm 包发布。项目根目录的 `AGENTS.md` 会引导 Codex 从已安装的 `@2kog/kacha/skills/` 读取技能。升级包即可更新技能。
45
50
 
46
51
  工作台从项目的 `package.json` 读取名称和简介,从 `config/logo.*` 读取可选的项目 Logo。
47
52
 
48
53
  ## 素材存储
49
54
 
50
- 创作项目以 OSS 和微云为主要存储。Git 用于记录现行采用的资产和说明。新项目的 `.gitignore` 默认忽略任意层级的 `archive/`、常见视频文件和本地依赖,项目可按需要追加规则。OSS 和微云的配置方式将在后续补充。
55
+ 创作项目以 OSS 和微云为主要存储。Git 记录项目版本,Git LFS 可将图片、音频和视频原件存到 OSS。新项目的 `.gitignore` 默认忽略 `.DS_Store`、`tmp/`、`node_modules/`、`.env`、`.env.*` 和本地同步状态。常见图片、音频和视频格式由初始化生成的 `.gitattributes` 指定走 Git LFS,历史资产所在的 `archive/` 随项目保存。已有项目若单独忽略了要纳入 LFS 的媒体,需调整相应的 `.gitignore` 规则。
51
56
 
52
57
  ## 创作模板
53
58
 
@@ -56,3 +61,59 @@ my-project/
56
61
  ## 本地开发
57
62
 
58
63
  在本仓库运行 `npm install` 安装依赖,用 `npm run dev -- /path/to/project` 启动工作台,用 `npm run build` 执行生产构建。
64
+
65
+ ## Git LFS 存储设置
66
+
67
+ 工作台「全局设置 → 存储设置」配置 Git LFS 上传和下载媒体所用的 OSS。保存后,咔嚓的 Git LFS 代理会读取同一份项目根目录 `.env`。也可以直接编辑 `.env`。新项目生成的五个字段均留空,默认由 `.gitignore` 排除这个文件。
68
+
69
+ ```dotenv
70
+ OSS_ENDPOINT=
71
+ OSS_BUCKET=
72
+ OSS_PREFIX=
73
+ OSS_ACCESS_KEY_ID=
74
+ OSS_ACCESS_KEY_SECRET=
75
+ ```
76
+
77
+ Git LFS 对象存放在配置的 Bucket 下的 `OSS_PREFIX/__kacha_lfs__/objects/`。前缀留空时使用 Bucket 根目录下的 `__kacha_lfs__/objects/`。工作台的「测试连接」会验证已保存的 OSS 配置。
78
+
79
+ 旧版工作台的云朵同步入口已隐藏。历史 OSS 协作版本仍可用 `kacha clone` 下载。
80
+
81
+ ### 下载历史 OSS 协作版本
82
+
83
+ 先创建空目录,在其中创建 `.env`,填写同事分享的 `OSS_ENDPOINT`、`OSS_BUCKET`、`OSS_PREFIX` 和自己的 `OSS_ACCESS_KEY_ID`、`OSS_ACCESS_KEY_SECRET`。Bucket 根目录可省略 `OSS_PREFIX`。项目需已通过咔嚓发布协作版本。
84
+
85
+ 在该目录运行:
86
+
87
+ ```bash
88
+ kacha clone .
89
+ ```
90
+
91
+ 点号表示当前目录,也可以省略,或传入一个已配置 `.env` 的目标目录。克隆完成后,运行 `kacha` 打开工作台。
92
+
93
+ ## Git LFS 直连 OSS
94
+
95
+ 安装 Git LFS 后,可以用 Git 管理剧本和文件指针,用阿里云 OSS 保存媒体文件。咔嚓作为 Git LFS 的本地传输代理,读取仓库根目录的 `.env`,直接上传和下载 OSS 对象。凭据留在每台电脑的 `.env`。对象写入 `OSS_PREFIX/__kacha_lfs__/objects/`,与咔嚓的项目同步版本分开。
96
+
97
+ `kacha init` 根据编码后的目录名生成 `.lfsconfig`,以 `https://kacha-lfs.invalid/<目录名>` 标识外部 LFS。实际传输目标由项目的 OSS 配置决定。常见媒体格式已在 `.gitattributes` 中登记,有其他格式时可用 `git lfs track` 补充。
98
+
99
+ 创建 Git 仓库后,可在工作台保存 OSS 配置,也可直接填写项目根目录的 `.env`。首次 `git add` 媒体前,先运行 `kacha lfs setup`。该命令配置当前 Git 仓库和本地 Git LFS 钩子,并在 Git 的本地排除文件中加入 `.env` 和传输状态目录。移动咔嚓安装目录后,重新执行一次配置命令。
100
+
101
+ ```bash
102
+ git init
103
+ kacha lfs setup
104
+ git add .gitattributes .lfsconfig .gitignore
105
+ ```
106
+
107
+ 将这三份配置提交到仓库,让同事获得同一套跟踪规则和外部存储标记。
108
+
109
+ 同事第一次获取项目时,先跳过媒体下载,等本机凭据和传输代理配置好后再拉取媒体。
110
+
111
+ ```bash
112
+ GIT_LFS_SKIP_SMUDGE=1 git clone <GitHub 仓库地址>
113
+ cd <项目目录>
114
+ # 在工作台的「存储设置」保存 OSS 配置,或填写项目根目录的 .env
115
+ kacha lfs setup
116
+ git lfs pull
117
+ ```
118
+
119
+ 配置完成后,照常使用 `git pull` 和 `git push`。传输代理校验文件大小和 SHA-256,大文件上传分片检查点保存在本机 `.kacha/lfs-transfer/`。
@@ -0,0 +1,88 @@
1
+ import { applyProject, planProject, selectChanges } from '../server/oss-collab-plan.js'
2
+ import { openProjectStorage } from '../server/project-storage.js'
3
+
4
+ const messages = {
5
+ OSS_NOT_CONFIGURED: 'Set OSS_ENDPOINT, OSS_BUCKET, OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET in the target directory’s .env.',
6
+ OSS_INVALID_CONFIG: 'Check the OSS settings in the target directory’s .env.',
7
+ OSS_COLLAB_NO_PUBLISHED_VERSION: 'No collaboration version has been published to the configured OSS path.',
8
+ OSS_COLLAB_REMOTE_CHANGED: 'A newer version was published during the download. Run kacha clone again.',
9
+ OSS_COLLAB_PREVIEW_STALE: 'The local files or cloud version changed. Run kacha clone again.',
10
+ OSS_COLLAB_PROJECT_MISMATCH: 'The target directory belongs to a different OSS project.',
11
+ OSS_COLLAB_REMOTE_INVALID: 'The cloud project manifest is invalid.',
12
+ OSS_COLLAB_REMOTE_IO: 'Unable to read the cloud project. Check the OSS settings, permissions and network.',
13
+ OSS_COLLAB_PATH_COLLISION: 'Local and cloud paths collide. Use an empty directory or rename the affected files.',
14
+ OSS_SYNC_BUSY: 'Another Kacha process is using the target directory.',
15
+ OSS_SYNC_SCAN_FAILED: 'Unable to scan the target directory. Make sure Git is installed and the files are readable.',
16
+ OSS_SYNC_BASELINE_INVALID: 'The target directory has an invalid config/oss-sync.json.',
17
+ OSS_SYNC_STATE_FAILED: 'Unable to save the download state. Check free space and directory permissions.',
18
+ OSS_SYNC_FILE_CHANGED: 'A local file changed during the download. Check the target directory and retry.',
19
+ OSS_CLONE_EXISTING_PROJECT: 'This directory already has a project. Clone legacy OSS versions into a new directory. For Git LFS projects, use git pull.',
20
+ }
21
+
22
+ export async function cloneProject(root) {
23
+ const controller = new AbortController()
24
+ const stop = () => controller.abort()
25
+ process.once('SIGINT', stop)
26
+ let progressVisible = false
27
+ let lastProgress = 0
28
+
29
+ function clearProgress() {
30
+ if (!progressVisible) return
31
+ process.stdout.clearLine(0)
32
+ process.stdout.cursorTo(0)
33
+ progressVisible = false
34
+ }
35
+
36
+ try {
37
+ const { client, destination } = await openProjectStorage({ root, timeout: 120000 })
38
+ console.log('Reading the latest project version from OSS…')
39
+ const plan = await planProject({ root, client, destination, signal: controller.signal, requireRemote: true })
40
+ if (plan.baseRevision) throw Object.assign(new Error(), { code: 'OSS_CLONE_EXISTING_PROJECT' })
41
+
42
+ const unexpected = [...plan.local.keys()].filter(file => !Object.hasOwn(plan.head.manifest.files, file))
43
+ const conflicts = [...new Set([...plan.conflicts.map(({ file }) => file), ...unexpected])]
44
+ if (conflicts.length) {
45
+ console.error('The target directory contains files that differ from the cloud project. Use an empty directory or move these files first:')
46
+ for (const file of conflicts.slice(0, 20)) console.error(' ' + file)
47
+ if (conflicts.length > 20) console.error(' … and ' + (conflicts.length - 20) + ' more')
48
+ return 1
49
+ }
50
+
51
+ const action = 'download'
52
+ const changes = selectChanges(plan, { action, resolutions: {}, confirmDeletes: false })
53
+ console.log('Downloading version ' + plan.revision + ' (' + plan.download.length + ' files to download)…')
54
+ const result = await applyProject({
55
+ root, client, destination, plan, action, changes, signal: controller.signal,
56
+ onProgress(progress) {
57
+ if (!process.stdout.isTTY || !progress.total || Date.now() - lastProgress < 120) return
58
+ clearProgress()
59
+ process.stdout.write('Processed ' + (progress.downloaded + progress.skipped + progress.failed) + '/' + progress.total + ' files')
60
+ progressVisible = true
61
+ lastProgress = Date.now()
62
+ },
63
+ })
64
+ clearProgress()
65
+ if (result.failed) {
66
+ console.error(result.failed + ' files could not be downloaded. Run kacha clone again to retry.')
67
+ for (const { file, code, status } of result.failures.slice(0, 20)) {
68
+ console.error(' ' + file + ' (' + code + (status ? ', HTTP ' + status : '') + ')')
69
+ }
70
+ if (result.failed > 20) console.error(' … and ' + (result.failed - 20) + ' more')
71
+ return 1
72
+ }
73
+ console.log('Downloaded ' + result.downloaded + ' files, skipped ' + result.skipped + '. Project ready in ' + root)
74
+ return 0
75
+ } catch (error) {
76
+ clearProgress()
77
+ if (controller.signal.aborted || error?.code === 'OSS_SYNC_STOPPED') {
78
+ console.error('Download interrupted. Run kacha clone again to continue.')
79
+ return 130
80
+ }
81
+ const code = error?.code
82
+ const message = Object.hasOwn(messages, code) ? messages[code] : 'Unable to clone the project from OSS.'
83
+ console.error('kacha clone: ' + message)
84
+ return 1
85
+ } finally {
86
+ process.off('SIGINT', stop)
87
+ }
88
+ }
@@ -1,36 +1,24 @@
1
1
  import { constants } from 'node:fs'
2
2
  import { copyFile, lstat, mkdir, readdir, writeFile } from 'node:fs/promises'
3
- import { join } from 'node:path'
3
+ import { basename, join } from 'node:path'
4
4
  import { fileURLToPath } from 'node:url'
5
5
 
6
6
  const templateRoot = fileURLToPath(new URL('../templates/project/', import.meta.url))
7
7
 
8
- const gitignore = `node_modules/
9
- .DS_Store
10
-
11
- # 资产历史版本
12
- archive/
8
+ const gitignore = `.DS_Store
9
+ tmp/
10
+ node_modules/
11
+ .env
12
+ .env.*
13
+ .kacha/oss-sync/
14
+ .kacha/lfs-transfer/
15
+ `
13
16
 
14
- # 视频素材
15
- *.[mM][pP]4
16
- *.[mM][oO][vV]
17
- *.[mM]4[vV]
18
- *.[wW][eE][bB][mM]
19
- *.[mM][kK][vV]
20
- *.[aA][vV][iI]
21
- *.[mM][pP][gG]
22
- *.[mM][pP][eE][gG]
23
- *.[wW][mM][vV]
24
- *.[fF][lL][vV]
25
- *.[mM][xX][fF]
26
- *.3[gG][pP]
27
- *.3[gG]2
28
- *.[oO][gG][vV]
29
- *.[mM][tT][sS]
30
- *.[mM]2[tT][sS]
31
- *.[vV][oO][bB]
32
- *.[rR][mM]
33
- *.[rR][mM][vV][bB]
17
+ const envTemplate = `OSS_ENDPOINT=
18
+ OSS_BUCKET=
19
+ OSS_PREFIX=
20
+ OSS_ACCESS_KEY_ID=
21
+ OSS_ACCESS_KEY_SECRET=
34
22
  `
35
23
 
36
24
  async function keepExisting(operation) {
@@ -60,4 +48,8 @@ async function copyTemplates(source, destination) {
60
48
  export async function initProject(projectRoot) {
61
49
  await copyTemplates(templateRoot, projectRoot)
62
50
  await keepExisting(() => writeFile(join(projectRoot, '.gitignore'), gitignore, { flag: 'wx' }))
51
+ await keepExisting(() => writeFile(join(projectRoot, '.env'), envTemplate, { flag: 'wx', mode: 0o600 }))
52
+ const projectName = encodeURIComponent(basename(projectRoot) || 'project')
53
+ const lfsConfig = `[lfs]\n\turl = https://kacha-lfs.invalid/${projectName}\n`
54
+ await keepExisting(() => writeFile(join(projectRoot, '.lfsconfig'), lfsConfig, { flag: 'wx' }))
63
55
  }
package/bin/kacha.js CHANGED
@@ -16,7 +16,29 @@ try {
16
16
  },
17
17
  })
18
18
  if (values.help) {
19
- console.log('Usage: kacha [project-directory] [--port 24074]\n kacha init')
19
+ console.log('Usage: kacha [project-directory] [--port 24074]\n kacha init\n kacha clone [project-directory]\n kacha lfs setup')
20
+ } else if (positionals[0] === 'lfs') {
21
+ const command = positionals[1]
22
+ if (positionals.length !== 2 || !['setup', 'transfer'].includes(command)) {
23
+ throw new Error('Usage: kacha lfs setup')
24
+ }
25
+ const { findGitProject, setupLfs } = await import('./lfs-setup.js')
26
+ const root = findGitProject()
27
+ if (command === 'setup') {
28
+ setupLfs(root)
29
+ console.log('Kacha OSS transfer agent configured for this Git repository.')
30
+ } else {
31
+ const { runLfsTransfer } = await import('./lfs-transfer.js')
32
+ await runLfsTransfer(root)
33
+ }
34
+ } else if (positionals[0] === 'clone') {
35
+ if (positionals.length > 2) throw new Error('Usage: kacha clone [project-directory]')
36
+ const projectRoot = resolve(positionals[1] ?? '.')
37
+ if (!(await stat(projectRoot).catch(() => null))?.isDirectory()) {
38
+ throw new Error('Create the target directory and add its .env before running kacha clone.')
39
+ }
40
+ const { cloneProject } = await import('./clone-project.js')
41
+ process.exitCode = await cloneProject(projectRoot)
20
42
  } else if (positionals[0] === 'init' && positionals.length === 1) {
21
43
  await initProject(process.cwd())
22
44
  console.log('Kacha project initialized in ' + process.cwd())
@@ -0,0 +1,75 @@
1
+ import { execFileSync } from 'node:child_process'
2
+ import { appendFileSync, mkdirSync, readFileSync } from 'node:fs'
3
+ import { dirname } from 'node:path'
4
+ import { fileURLToPath } from 'node:url'
5
+
6
+ const agent = 'kacha-oss'
7
+ const cli = fileURLToPath(new URL('./kacha.js', import.meta.url))
8
+
9
+ export function findGitProject() {
10
+ try {
11
+ return execFileSync('git', ['rev-parse', '--show-toplevel'], {
12
+ encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'],
13
+ }).replace(/\r?\n$/, '')
14
+ } catch {
15
+ throw new Error('Run this command in a Git working tree.')
16
+ }
17
+ }
18
+
19
+ export function setupLfs(root) {
20
+ const git = (args, stdio = ['ignore', 'pipe', 'ignore']) => execFileSync('git', args, {
21
+ cwd: root, encoding: 'utf8', stdio,
22
+ })
23
+
24
+ try {
25
+ git(['lfs', 'version'])
26
+ } catch {
27
+ throw new Error('Install Git LFS before configuring the Kacha OSS transfer agent.')
28
+ }
29
+
30
+ let existing
31
+ try {
32
+ existing = git(['config', '--local', '--get', 'lfs.standalonetransferagent']).trim()
33
+ } catch (error) {
34
+ if (error.status !== 1) throw error
35
+ }
36
+ if (existing && existing !== agent) {
37
+ throw new Error('This repository already uses another standalone Git LFS transfer agent.')
38
+ }
39
+
40
+ if (git(['ls-files', '--', '.env', '.kacha/lfs-transfer/']).trim()) {
41
+ throw new Error('Remove .env and .kacha/lfs-transfer/ from the Git index before configuring the OSS agent.')
42
+ }
43
+ const exclude = git(['rev-parse', '--path-format=absolute', '--git-path', 'info/exclude']).trimEnd()
44
+ mkdirSync(dirname(exclude), { recursive: true })
45
+ let current = ''
46
+ try {
47
+ current = readFileSync(exclude, 'utf8')
48
+ } catch (error) {
49
+ if (error.code !== 'ENOENT') throw error
50
+ }
51
+ const existingRules = new Set(current.split(/\r?\n/))
52
+ const rules = ['/.env', '/.kacha/lfs-transfer/'].filter(rule => !existingRules.has(rule))
53
+ if (rules.length) appendFileSync(exclude, (current && !current.endsWith('\n') ? '\n' : '') + rules.join('\n') + '\n')
54
+
55
+ for (const file of ['.env', '.kacha/lfs-transfer/checkpoint.json']) {
56
+ try {
57
+ git(['check-ignore', '--quiet', '--', file])
58
+ } catch (error) {
59
+ if (error.status !== 1) throw error
60
+ throw new Error('Add a Git ignore rule for ' + file + ' before configuring the OSS agent.')
61
+ }
62
+ }
63
+
64
+ // Let Git LFS create its usual hook and report an existing-hook conflict without replacing it.
65
+ git(['lfs', 'install', '--local'], 'inherit')
66
+ const args = '"' + cli.replaceAll('\\', '\\\\').replaceAll('"', '\\"') + '" lfs transfer'
67
+ const settings = {
68
+ ['lfs.customtransfer.' + agent + '.path']: process.execPath,
69
+ ['lfs.customtransfer.' + agent + '.args']: args,
70
+ ['lfs.customtransfer.' + agent + '.concurrent']: 'false',
71
+ 'lfs.locksverify': 'false',
72
+ 'lfs.standalonetransferagent': agent,
73
+ }
74
+ for (const [key, value] of Object.entries(settings)) git(['config', '--local', key, value])
75
+ }
@@ -0,0 +1,235 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { constants, createWriteStream } from 'node:fs'
3
+ import { mkdtemp, open, realpath, rm } from 'node:fs/promises'
4
+ import { join, resolve } from 'node:path'
5
+ import { createInterface } from 'node:readline'
6
+ import { Transform, Writable } from 'node:stream'
7
+ import { pipeline } from 'node:stream/promises'
8
+ import {
9
+ checkStopped, createSnapshot, ensureDirectory, readRecord, sameFile, uploadFile,
10
+ } from '../server/oss-sync-engine.js'
11
+ import { openProjectStorage } from '../server/project-storage.js'
12
+
13
+ const oidPattern = /^[a-f0-9]{64}$/
14
+ const operationSet = new Set(['upload', 'download'])
15
+ const gatewayError = 'The OSS transfer failed. Check the project .env, OSS permissions and network.'
16
+ const messages = {
17
+ OSS_NOT_CONFIGURED: 'Add OSS_ENDPOINT, OSS_BUCKET, OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET to the project .env.',
18
+ OSS_INVALID_CONFIG: 'Check the OSS settings in the project .env.',
19
+ OSS_SYNC_STATE_FAILED: 'Unable to save transfer state. Check free space and directory permissions.',
20
+ OSS_SYNC_STOPPED: 'The OSS transfer was interrupted.',
21
+ LFS_LOCAL_OBJECT_INVALID: 'The local LFS object does not match its SHA-256 or size.',
22
+ LFS_REQUEST_INVALID: 'Invalid Git LFS transfer request.',
23
+ LFS_REMOTE_OBJECT_INVALID: 'The OSS object does not match its LFS SHA-256 or size.',
24
+ LFS_REMOTE_OBJECT_MISSING: 'The LFS object is missing from the configured OSS path.',
25
+ }
26
+
27
+ function transferError(code) {
28
+ return Object.assign(new Error(messages[code]), { code })
29
+ }
30
+
31
+ function publicMessage(error) {
32
+ if (Object.hasOwn(messages, error?.code)) return messages[error.code]
33
+ return Number.isInteger(error?.status) && error.status >= 400 && error.status <= 599
34
+ ? gatewayError + ' HTTP ' + error.status + '.'
35
+ : gatewayError
36
+ }
37
+
38
+ function isMissing(error) {
39
+ return error?.code === 'NoSuchKey' || (error?.status === 404 && error.code !== 'NoSuchBucket')
40
+ }
41
+
42
+ function objectKey(prefix, oid) {
43
+ return [prefix, '__kacha_lfs__', 'objects', oid.slice(0, 2), oid].filter(Boolean).join('/')
44
+ }
45
+
46
+ function progressReporter(send, oid, size) {
47
+ let previous = 0
48
+ let updatedAt = 0
49
+ return (bytes, final = false) => {
50
+ if (!final && (bytes <= previous || Date.now() - updatedAt < 120)) return
51
+ const current = final ? size : Math.max(previous, Math.min(size, bytes))
52
+ send({ event: 'progress', oid, bytesSoFar: current, bytesSinceLast: current - previous })
53
+ previous = current
54
+ updatedAt = Date.now()
55
+ }
56
+ }
57
+
58
+ async function verifyRemoteObject(client, key, oid, size, output, progress, signal) {
59
+ checkStopped(signal)
60
+ const hash = createHash('sha256')
61
+ let received = 0
62
+ const meter = new Transform({
63
+ transform(chunk, _encoding, done) {
64
+ received += chunk.length
65
+ if (received > size) return done(transferError('LFS_REMOTE_OBJECT_INVALID'))
66
+ hash.update(chunk)
67
+ progress?.(received)
68
+ done(null, chunk)
69
+ },
70
+ })
71
+ const { stream } = await client.getStream(key, { headers: { 'Accept-Encoding': 'identity' } }).catch(error => {
72
+ if (isMissing(error)) throw transferError('LFS_REMOTE_OBJECT_MISSING')
73
+ throw error
74
+ })
75
+ const sink = output
76
+ ? createWriteStream(output, { flags: 'wx', mode: 0o600 })
77
+ : new Writable({ write(_chunk, _encoding, done) { done() } })
78
+ await pipeline(stream, meter, sink, { signal })
79
+ if (received !== size || hash.digest('hex') !== oid) throw transferError('LFS_REMOTE_OBJECT_INVALID')
80
+ }
81
+
82
+ async function alreadyUploaded(client, key, oid, size, signal) {
83
+ const result = await client.head(key).catch(error => {
84
+ if (isMissing(error)) return null
85
+ throw error
86
+ })
87
+ if (!result) return false
88
+ const headers = result.res?.headers || {}
89
+ const recordedSize = headers['content-length']
90
+ if (recordedSize !== undefined && Number(recordedSize) !== size) throw transferError('LFS_REMOTE_OBJECT_INVALID')
91
+ if (Number(recordedSize) === size && headers['x-oss-meta-sha256'] === oid) return true
92
+
93
+ // Older objects may have no checksum metadata. Verify their content before reusing the key.
94
+ await verifyRemoteObject(client, key, oid, size, undefined, undefined, signal)
95
+ return true
96
+ }
97
+
98
+ async function snapshotLocalObject(root, request, snapshot, signal) {
99
+ const source = await open(resolve(root, request.path), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)
100
+ .catch(() => { throw transferError('LFS_LOCAL_OBJECT_INVALID') })
101
+ try {
102
+ const before = await source.stat({ bigint: true })
103
+ if (!before.isFile() || before.size !== BigInt(request.size)) throw transferError('LFS_LOCAL_OBJECT_INVALID')
104
+ const digest = await createSnapshot(source, request.size, snapshot, signal)
105
+ const after = await source.stat({ bigint: true })
106
+ if (digest !== request.oid || !sameFile(before, after)) throw transferError('LFS_LOCAL_OBJECT_INVALID')
107
+ } finally {
108
+ await source.close()
109
+ }
110
+ }
111
+
112
+ async function uploadObject({ client, key, root, scratch, checkpoints, request, progress, signal }) {
113
+ const { oid, size } = request
114
+ const snapshot = join(scratch, 'upload')
115
+ await snapshotLocalObject(root, request, snapshot, signal)
116
+ const recordFile = join(checkpoints, oid + '.json')
117
+ if (!(await alreadyUploaded(client, key, oid, size, signal))) {
118
+ checkStopped(signal)
119
+ const record = await readRecord(recordFile)
120
+ const options = { mime: 'application/octet-stream', meta: { sha256: oid } }
121
+ const uploadClient = {
122
+ put(name, file) {
123
+ return client.put(name, file, options)
124
+ },
125
+ multipartUpload(name, file, multipartOptions) {
126
+ return client.multipartUpload(name, file, {
127
+ ...multipartOptions,
128
+ ...options,
129
+ // ali-oss sends a final 100% callback without a checkpoint.
130
+ progress(fraction, current) {
131
+ if (current) return multipartOptions.progress(fraction, current)
132
+ },
133
+ })
134
+ },
135
+ }
136
+ await uploadFile({
137
+ client: uploadClient, file: oid, key, snapshot, size, fingerprint: oid,
138
+ checkpoint: record?.fingerprint === oid ? record.checkpoint : null,
139
+ recordFile, signal, progress: percent => progress(Math.floor(size * percent / 100)),
140
+ })
141
+ }
142
+ await rm(recordFile, { force: true })
143
+ progress(size, true)
144
+ }
145
+
146
+ async function makeTransferDirectories(root, destination) {
147
+ const cache = join(root, '.kacha')
148
+ const state = join(cache, 'lfs-transfer')
149
+ const id = createHash('sha256').update(JSON.stringify(destination)).digest('hex')
150
+ const directory = join(state, id)
151
+ const checkpoints = join(directory, 'multipart')
152
+ for (const path of [cache, state, directory, checkpoints]) await ensureDirectory(path)
153
+ return { directory, checkpoints }
154
+ }
155
+
156
+ // Git LFS reserves stdout for line-delimited JSON and sends requests serially to each worker.
157
+ export async function runLfsTransfer(projectRoot) {
158
+ const reader = createInterface({ input: process.stdin, crlfDelay: Infinity, terminal: false })
159
+ const send = message => process.stdout.write(JSON.stringify(message) + '\n')
160
+ const controller = new AbortController()
161
+ const { signal } = controller
162
+ const interrupt = () => {
163
+ controller.abort()
164
+ reader.close()
165
+ }
166
+ process.once('SIGINT', interrupt)
167
+ process.once('SIGTERM', interrupt)
168
+ let session
169
+
170
+ try {
171
+ for await (const line of reader) {
172
+ let request
173
+ try {
174
+ request = JSON.parse(line)
175
+ } catch {
176
+ throw transferError('LFS_REQUEST_INVALID')
177
+ }
178
+ if (!session) {
179
+ if (request?.event !== 'init' || !operationSet.has(request.operation)) throw transferError('LFS_REQUEST_INVALID')
180
+ try {
181
+ const root = await realpath(projectRoot)
182
+ const { client, destination } = await openProjectStorage({ root, timeout: 120000 })
183
+ const { directory, checkpoints } = await makeTransferDirectories(root, destination)
184
+ const scratch = await mkdtemp(join(directory, 'worker-'))
185
+ session = { client, destination, root, scratch, checkpoints, operation: request.operation }
186
+ } catch (error) {
187
+ send({ error: { code: 1, message: publicMessage(error) } })
188
+ return
189
+ }
190
+ send({})
191
+ continue
192
+ }
193
+
194
+ if (request?.event === 'terminate') return
195
+ const { oid, size, path } = request || {}
196
+ const validOid = typeof oid === 'string' && oidPattern.test(oid)
197
+ if (!validOid) throw transferError('LFS_REQUEST_INVALID')
198
+ if (request.event !== session.operation || !Number.isSafeInteger(size) || size < 0 ||
199
+ (session.operation === 'upload' && (typeof path !== 'string' || !path))) {
200
+ send({ event: 'complete', oid, error: { code: 1, message: messages.LFS_REQUEST_INVALID } })
201
+ continue
202
+ }
203
+
204
+ const { client, destination, root, scratch, checkpoints } = session
205
+ const progress = progressReporter(send, oid, size)
206
+ const key = objectKey(destination.prefix, oid)
207
+ let work
208
+ let transferred = false
209
+ try {
210
+ work = await mkdtemp(join(scratch, 'transfer-'))
211
+ if (session.operation === 'upload') {
212
+ await uploadObject({ client, key, root, scratch: work, checkpoints, request, progress, signal })
213
+ send({ event: 'complete', oid })
214
+ } else {
215
+ const download = join(work, oid)
216
+ await verifyRemoteObject(client, key, oid, size, download, progress, signal)
217
+ progress(size, true)
218
+ send({ event: 'complete', oid, path: download })
219
+ transferred = true
220
+ }
221
+ } catch (error) {
222
+ const message = signal.aborted ? messages.OSS_SYNC_STOPPED : publicMessage(error)
223
+ send({ event: 'complete', oid, error: { code: 1, message } })
224
+ } finally {
225
+ // Git LFS moves a completed download into its cache before asking for another transfer.
226
+ if (work && !transferred) await rm(work, { recursive: true, force: true }).catch(() => {})
227
+ }
228
+ }
229
+ } finally {
230
+ reader.close()
231
+ process.off('SIGINT', interrupt)
232
+ process.off('SIGTERM', interrupt)
233
+ if (session) await rm(session.scratch, { recursive: true, force: true }).catch(() => {})
234
+ }
235
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@2kog/kacha",
3
- "version": "0.1.2",
3
+ "version": "0.2.0",
4
4
  "description": "Local production workbench for creative projects",
5
5
  "author": "rx6",
6
6
  "repository": {
@@ -19,6 +19,7 @@
19
19
  "bin/",
20
20
  "server/",
21
21
  "templates/",
22
+ "skills/",
22
23
  "src/",
23
24
  "index.html",
24
25
  "vite.config.js"
@@ -36,6 +37,7 @@
36
37
  },
37
38
  "dependencies": {
38
39
  "@vitejs/plugin-vue": "^5.2.0",
40
+ "ali-oss": "^6.23.0",
39
41
  "dompurify": "^3.2.0",
40
42
  "element-plus": "^2.14.8",
41
43
  "lucide-vue-next": "^0.468.0",
package/server/index.js CHANGED
@@ -1,7 +1,10 @@
1
1
  import { assetWatch } from './asset-watch.js'
2
2
  import { characterAssets } from './character-assets.js'
3
3
  import { imageAssets } from './image-assets.js'
4
+ import { projectGlobal } from './project-global.js'
4
5
  import { projectBrand } from './project-brand.js'
6
+ import { projectOssSync } from './project-oss-sync.js'
7
+ import { projectStorage } from './project-storage.js'
5
8
  import { projectSettings } from './project-settings.js'
6
9
 
7
10
  export function workbenchPlugins() {
@@ -10,6 +13,9 @@ export function workbenchPlugins() {
10
13
  ...['scenes', 'props', 'other', 'audio'].map(imageAssets),
11
14
  projectSettings(),
12
15
  projectBrand(),
16
+ projectGlobal(),
17
+ projectStorage(),
18
+ projectOssSync(),
13
19
  assetWatch(),
14
20
  ]
15
21
  }