Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(browser): 收敛配方诊断与上传状态边界
Dashc262932e1258
diff --git a/packages/lizi-mcps/src/browser/opencli-recipes.test.ts b/packages/lizi-mcps/src/browser/opencli-recipes.test.tsindex 4a9aad4c90..9646a9daa8 100644--- a/packages/lizi-mcps/src/browser/opencli-recipes.test.ts+++ b/packages/lizi-mcps/src/browser/opencli-recipes.test.ts@@ -29,10 +29,12 @@ import { readUtf8File } from '../../../opencli-vendor/clis/_atlassian/shared.js'import { resolvePayload } from '../../../opencli-vendor/clis/zhihu/write-shared.js';// @ts-expect-error Pinned upstream JavaScript helpers have no declarations.import { prepareChatGPTFilePaths } from '../../../opencli-vendor/clis/chatgpt/utils.js';-import { readFileSync, openSync } from 'node:fs';+import { readFileSync, openSync, fstatSync } from 'node:fs';import { AsyncResource } from 'node:async_hooks';// @ts-expect-error Upstream JavaScript helpers have no declarations.import { validateLocalReferences } from '../../../opencli-vendor/clis/midjourney/utils.js';+// @ts-expect-error Pinned upstream JavaScript uploader has no declarations.+import { tosUpload } from '../../../opencli-vendor/clis/douyin/_shared/tos-upload.js';afterEach(() => {vi.useRealTimers();@@ -41,6 +43,68 @@ afterEach(() => {});describe("bundled OpenCLI recipes", () => {+ // #6826 file-state recurrence, unit tier. Real uploader and broker-approved+ // descriptors; old tests never reached multipart init with task-only files.+ // The old resume write fails after init, before any part can be transferred.+ it.each([null, 'init', 'transfer', 'finish'])('uploads without disk state and closes the input after failure at %s', async fail => {+ const dir = await mkdtemp(path.join(tmpdir(), 'cindy-recipe-tos-test-'));+ const file = path.join(dir, 'clip.mp4');+ await writeFile(file, 'fixture-video');+ const opened: number[] = [];+ const phases: string[] = [];+ const fetch = vi.fn(async (url: string, init: RequestInit) => {+ const phase = new URL(url).searchParams.get('phase')!;+ phases.push(phase);+ if (phase === 'init') return new Response('<UploadId>invalid-fixture-upload</UploadId>', { status: fail === phase ? 500 : 200 });+ if (phase === 'transfer') {+ expect(Buffer.from(init.body as Uint8Array).toString()).toBe('fixture-video');+ return new Response(JSON.stringify({ code: fail === phase ? 4000 : 2000, data: { crc32: 'fixture-crc' } }));+ }+ return new Response(JSON.stringify({ code: fail === phase ? 4000 : 2000, data: { key: 'fixture-completed' } }));+ });+ vi.stubGlobal('fetch', fetch);+ const output = vi.fn(() => { throw new Error('no extra disk state'); });+ const run = () => tosUpload({ filePath: 'clip.mp4', uploadInfo: {+ tos_upload_url: 'https://upload.example.test/video', auth: 'invalid-fixture-auth',+ } });+ try {+ await expect(withRecipeHost(undefined, run, {+ directory: dir, read: () => { throw new Error('input rejected'); },+ open: () => { throw new Error('input rejected'); }, output,+ })).rejects.toThrow();+ expect(fetch).not.toHaveBeenCalled();+ const inputOnlyOutput = vi.fn((candidate: string) => {+ if (candidate === file) return candidate;+ throw new Error('no extra disk state');+ });+ const running = withRecipeHost(undefined, run, {+ directory: dir, read: readFileSync,+ open: file => { const fd = openSync(file, 'r'); opened.push(fd); return fd; }, output: inputOnlyOutput,+ });+ if (fail) await expect(running).rejects.toThrow(fail === 'init' ? 'TOS init multipart upload failed'+ : fail === 'transfer' ? 'TOS upload part 1 failed' : 'TOS complete multipart upload failed');+ else expect(await running).toBe('fixture-completed');+ expect(phases).toEqual(fail === 'init' ? ['init'] : fail === 'transfer' ? ['init', 'transfer'] : ['init', 'transfer', 'finish']);+ expect(output).not.toHaveBeenCalled();+ expect(inputOnlyOutput).not.toHaveBeenCalled();+ expect(opened).toHaveLength(1);+ expect(() => fstatSync(opened[0])).toThrow();+ expect(await readdir(dir)).toEqual(['clip.mp4']);+ } finally { await rm(dir, { recursive: true, force: true }); }+ });++ // #6826 quota regression, unit tier. Actual adapter result must survive a+ // broker denying all optional files; older coverage never ran quota/account.+ it.each(['quota', 'account'])('returns current Midjourney %s without historical snapshot files', async command => {+ const io = vi.fn(() => { throw new Error('host denied optional state'); });+ const result = await executeAdapter(`midjourney/${command}`, {}, {+ goto: async () => {}, fetchJson: async () => ({ user_id: 'fixture-user', plan: { type: 'basic' }, total_credits: 120000, period_credits_used: 60000 }),+ } as unknown as IPage, undefined, undefined, { directory: tmpdir(), read: io, open: io, output: io });+ expect(result).toMatchObject([{ plan: 'basic', remaining_minutes: 2, used_minutes: 1,+ avg_daily_minutes: null, projected_exhaustion_date: null }]);+ expect(io).not.toHaveBeenCalled();+ });+// #6826 credentials-and-local-storage: production broker, unit tier. Prior// file tests did not cover a missing encrypted entry with a legacy file present.// Only invalid fixture credentials are written under an isolated temp root.@@ -727,7 +791,7 @@ describe("bundled OpenCLI recipes", () => {const all = await query();expect(all.ok).toBe(true);expect(all.recipeCount).toBe(loadRecipes().size);- for (const id of ['opencli:zlibrary/search', 'opencli:slock/task-create', 'opencli:claude/login', 'opencli:claude/ask', 'opencli:spotify/auth', 'opencli:spotify/status', 'opencli:ones/login', 'opencli:ones/token-info', 'opencli:xiaoyuzhou/history', 'opencli:paperreview/submit', 'opencli:paperreview/review', 'opencli:paperreview/feedback', 'opencli:quark/share-tree', 'opencli:quark/save', 'books-list', 'hockey-search']) {+ for (const id of ['opencli:zlibrary/search', 'opencli:slock/task-create', 'opencli:claude/login', 'opencli:claude/ask', 'opencli:spotify/auth', 'opencli:spotify/status', 'opencli:ones/login', 'opencli:ones/token-info', 'opencli:xiaoyuzhou/history', 'opencli:paperreview/submit', 'opencli:paperreview/review', 'opencli:paperreview/feedback', 'opencli:quark/share-tree', 'opencli:quark/save', 'opencli:kimi/storage-get', 'opencli:kimi/storage-keys', 'opencli:kimi/cookies', 'opencli:kimi/idb-list', 'books-list', 'hockey-search']) {expect(JSON.stringify(all)).not.toContain(id);const response = await client.callTool({ name: 'call_tool', arguments: { name: 'browser', args: { action: 'recipe', recipeId: id } } });expect(JSON.parse((response.content as Array<{ text: string }>)[0].text).ok).toBe(false);diff --git a/packages/opencli-vendor/README.md b/packages/opencli-vendor/README.mdindex 59303377ea..765d73aabf 100644--- a/packages/opencli-vendor/README.md+++ b/packages/opencli-vendor/README.md@@ -11,14 +11,14 @@- 170 个站点/应用,1,223 条命令(916 read、307 write)。- 1,112 个命令模块,所有生产共享代码、JSON 和其他资源一并引入;不引入上游测试。- 上游快照完整保留,但默认目录独立选择:排除 Z-Library、Slock、Claude.ai、Spotify、ONES、- 小宇宙适配器、PaperReview 和 Quark 共 92 条,剩余 1,131 条命令、25 个上游别名。原因记录在 [selection.json](cindy/selection.json),+ 小宇宙适配器、PaperReview、Quark 和 Kimi 共 121 条,剩余 1,102 条命令、25 个上游别名。原因记录在 [selection.json](cindy/selection.json),同步会沿用此选择,排除条目不进入模块导入表和可执行目录。- Cindy 原有 56 个 ID:47 个转到新版适配器,7 个保留原流程,两个爬虫练习站移至`packages/lizi-mcps/src/browser/recipe-examples`,不再出现在默认列表。逐项记录见 [legacy-coverage.json](cindy/legacy-coverage.json)。- Cindy 独立增加 App Store 搜索、Google Play 搜索、TapTap 中国站游戏详情、Steam 玩家评价、Open Library 书目查询和 Crossref 文献/DOI 查询,共 6 个配方,位于- `packages/lizi-mcps/src/browser/cindy-recipes`。共 1,216 个可发现 ID、169 份指南;这个数包含别名和兼容入口。+ `packages/lizi-mcps/src/browser/cindy-recipes`。共 1,187 个可发现 ID、168 份指南;这个数包含别名和兼容入口。- 兼容入口保持输入名,输出改为新版结构化结果;用户本地覆盖层仍优先于内置层。通过 `browser(action="siteguide")` 查询精简完整目录;传 `site`(域名或上游站点名)@@ -43,6 +43,8 @@会把可复用能力令牌放入模型结果或参数。完整来源保留,不增加配置或句柄存储机制。- ONES 暂不进入默认目录:密码参数和令牌打印不符合宿主代输入及凭据边界。登录继续使用已有的通用代输入流程,不新增站点专用配置。+- Kimi 暂不进入默认目录:存储读取与 Cookie 诊断会把任意存储值或授权材料预览返回模型。+ 完整来源保留,不新增秘密键猜测或凭据脱敏机制。- 文章 stdout 输出改为 MCP 返回值;Readability 脚本随构建打包,避免安装包运行时查找源码文件。- 主进程使用静态入口加载所选命令及其执行依赖,不在运行期动态导入模块;导入不执行命令。@@ -54,6 +56,10 @@成功和失败均沿用调用 finally 清理,源文件保留;外部 Chrome 与内嵌浏览器使用相同的暂存入口。- 图片、音频和下载成果的默认路径与目录参数元数据均使用任务内相对路径;诊断截图及跟踪文件按调用隔离,结束后清理,兼容 Windows。+- 抖音分片上传先批准并打开源文件,再创建远端上传;上传 ID 和进度只存于本次调用,+ 不读写跨调用断点文件。初始化、分片、完成失败及成功都关闭源描述符,不自动重试。+- Midjourney 保留当前额度和批次估算,不读写历史监控快照;历史趋势字段返回空值,+ 不因可选的历史存储不可用而丢掉已取得的当前额度或误报付费操作失败。- 共享 Node 文件下载复用浏览器运行层的 SSRF fetch:首跳与每次重定向均检查协议、DNS/IP,连接固定在已校验的公网地址;跨 origin 移除鉴权头,正文结束或失败后释放连接。这条下载路径使用受保护的直连,不读取适配器的代理环境变量;需要代理的站点可沿用浏览器操作。diff --git a/packages/opencli-vendor/UPSTREAM.json b/packages/opencli-vendor/UPSTREAM.jsonindex c3522610a1..783f4ff6a5 100644--- a/packages/opencli-vendor/UPSTREAM.json+++ b/packages/opencli-vendor/UPSTREAM.json@@ -219,6 +219,9 @@},"src/browser/cdp.ts": {"upstreamSha256": "0558dc14d65741c39f9c3fe8461e1dd3b3ae0cbdd0b7ddafbd1f02e1153d04b3"+ },+ "clis/midjourney/quota.js": {+ "upstreamSha256": "c9be85847c01d7a0d9673dc45b2ddbadc77a2de885825530b08886fe6e310a0f"}},"files": {@@ -518,7 +521,7 @@"clis/douyin/_shared/sts2.js": "0759c0b4ac5542ad06a7bc03af5370579721f9af249ff29ad6230bdb6a2d7c46","clis/douyin/_shared/text-extra.js": "4caa2e8660eba04115476ee212deaa7ac578271e3df18c4513295b9c15fca3dd","clis/douyin/_shared/timing.js": "4bdc8fc4f64015253c884540e473d780bad4f97823e9ed91dff4fe83773b905b",- "clis/douyin/_shared/tos-upload.js": "07490cd63bd14031f255d03fad3c43910edc82b42ba880d551cce136ee9f0f49",+ "clis/douyin/_shared/tos-upload.js": "00f1e6fd11be46279447d86e02560e9c7f9bbe3704103b204a6bf5006d0662ad","clis/douyin/_shared/transcode.js": "2fc7d05b9748efd4ddf5333ae8da31560f2417773a2e5cc4fffe3b9ed7306e36","clis/douyin/_shared/types.js": "8e609bb71c20b858c77f0e9f90bb1319db8477b13f9f965f1a1e18524bf50881","clis/douyin/_shared/vod-upload.js": "8030db92de71acce559e8ba4c1d89d93846e7bcf8c8f2c470def958283cf3c3c",@@ -890,10 +893,10 @@"clis/midjourney/generate.js": "370bf20986bb40e8c80f57b7b5fda61930e1b09c38433f732b25412c826ee9fb","clis/midjourney/history.js": "2ed49c8ceef4f9731014246329db5c5143e362d9d8f4c87e3ea38c67f613c36b","clis/midjourney/login.js": "f235209ecae8eea22efe41a50fff08441a1cbe8cd2b51021d961d251f0da65eb",- "clis/midjourney/quota.js": "c9be85847c01d7a0d9673dc45b2ddbadc77a2de885825530b08886fe6e310a0f",+ "clis/midjourney/quota.js": "51ea3faaadba3866a7ec9095de27fcc17da1dde1a49f63c3f4381f5e5dfa069c","clis/midjourney/settings.js": "bcec44f911c62f1621f0a8776199c7ab3918df16c648e9fa2216f11e0bfea6bf","clis/midjourney/status.js": "1382504f9b9cbe73864bc05f4d3f398ea38ae3fa18a4379428b7cdfee8ecfc2b",- "clis/midjourney/utils.js": "645e331a02a04591447c2496a4a6298eb726b7195f995c0e0dd1da43c2c337c2",+ "clis/midjourney/utils.js": "f368913a9c03b1c8c6db5e2696a542e6787a49c19bd11dee21b7a152eda4881e","clis/midjourney/whoami.js": "78424e609c5cc0022ec7c2590cc902371f4431207d2f0b1079a9cdf9fa1beea9","clis/minimax/music.js": "a192c07d35827813ca229d4fae2e4136153aaa8e987d2335db33605daaa65837","clis/minimax/utils.js": "07c258f4481a8c3524d66cc686915222a3a8f0b9879626e0a520571226974e51",@@ -1651,6 +1654,6 @@"src/verify.ts": "9ad21f961c94b750dca8db63a6ffc78689dda5186f1d443ab8f912eef30b2fc9","src/version.ts": "7bb1ede5cfc1f796e434cacd08cb9f903022f8c9375b17237aa16ad7d825aa2b","LICENSE": "0210b8b66cf00358242cb921ba2be3a46dfe0190159b1b952388a3880ce1ff54",- "cli-manifest.json": "29ae519d76909a34d71010afddca96892f27fe0980bfcfd112d62d567b27b5d7"+ "cli-manifest.json": "e3db617c4eb424df4256c1d1646a45c4b5bb7da94c170bbf1598c46e0b762fa4"}}diff --git a/packages/opencli-vendor/cindy/modules.js b/packages/opencli-vendor/cindy/modules.jsindex 2a1025820f..167a1fdc73 100644--- a/packages/opencli-vendor/cindy/modules.js+++ b/packages/opencli-vendor/cindy/modules.js@@ -469,12 +469,6 @@ import "../clis/ke/chengjiao.js";import "../clis/ke/ershoufang.js";import "../clis/ke/xiaoqu.js";import "../clis/ke/zufang.js";-import "../clis/kimi/audit-extras.js";-import "../clis/kimi/auth.js";-import "../clis/kimi/chat.js";-import "../clis/kimi/storage.js";-import "../clis/kimi/ui.js";-import "../clis/kimi/usage.js";import "../clis/lesswrong/comments.js";import "../clis/lesswrong/curated.js";import "../clis/lesswrong/frontpage.js";@@ -1503,12 +1497,6 @@ export const modules = {"ke/ershoufang.js": true,"ke/xiaoqu.js": true,"ke/zufang.js": true,- "kimi/audit-extras.js": true,- "kimi/auth.js": true,- "kimi/chat.js": true,- "kimi/storage.js": true,- "kimi/ui.js": true,- "kimi/usage.js": true,"lesswrong/comments.js": true,"lesswrong/curated.js": true,"lesswrong/frontpage.js": true,diff --git a/packages/opencli-vendor/cindy/patches.json b/packages/opencli-vendor/cindy/patches.jsonindex 6a8a0a03e3..77ce394063 100644--- a/packages/opencli-vendor/cindy/patches.json+++ b/packages/opencli-vendor/cindy/patches.json@@ -3189,5 +3189,35 @@"before": "existsSync = fs.existsSync","after": "existsSync = (file) => fs.existsSync(recipeOutputPath(file))","count": 1+ },+ {+ "file": "clis/douyin/_shared/tos-upload.js",+ "before": "import { closeRecipeFileSync, recipeOutputPath, resolveRecipePath } from '@jackwener/opencli/cindy/host';\nimport { openRecipeFileSync, readRecipeFileSync } from '@jackwener/opencli/cindy/host';\n/**\n * TOS (ByteDance Object Storage) multipart uploader with resume support.\n *\n * Uses AWS Signature V4 (HMAC-SHA256) with STS2 temporary credentials.\n * For the init multipart upload call, the pre-computed auth from TosUploadInfo is used.\n * For PUT part uploads and the final complete call, AWS4 is computed from STS2 credentials.\n */\nimport * as crypto from 'node:crypto';\nimport * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport { CommandExecutionError } from '@jackwener/opencli/errors';\nconst PART_SIZE = 5 * 1024 * 1024; // 5 MB minimum per TOS/S3 spec\nconst RESUME_DIR = path.join(os.homedir(), '.opencli', 'douyin-resume');\n// ── Resume file helpers ──────────────────────────────────────────────────────\nfunction getResumeFilePath(filePath) {\n const hash = crypto.createHash('sha256').update(filePath).digest('hex');\n return path.join(RESUME_DIR, `${hash}.json`);\n}\nfunction loadResumeState(resumePath, fileSize) {\n try {\n const raw = readRecipeFileSync(resumePath, 'utf8');\n const state = JSON.parse(raw);\n if (state.fileSize === fileSize && state.uploadId && Array.isArray(state.parts)) {\n return state;\n }\n }\n catch {\n // no valid resume state\n }\n return null;\n}\nfunction saveResumeState(resumePath, state) {\n fs.mkdirSync(recipeOutputPath(path.dirname(resumePath)), { recursive: true });\n fs.writeFileSync(recipeOutputPath(resumePath), JSON.stringify(state, null, 2), 'utf8');\n}\nfunction deleteResumeState(resumePath) {\n try {\n fs.unlinkSync(recipeOutputPath(resumePath));\n }\n catch {\n // ignore if not found\n }\n}\n",+ "after": "import { closeRecipeFileSync, openRecipeFileSync } from '@jackwener/opencli/cindy/host';\n/**\n * TOS multipart upload. Progress and upload IDs live only in this invocation;\n * no cross-call resume files are read or persisted by Cindy.\n */\nimport * as crypto from 'node:crypto';\nimport * as fs from 'node:fs';\nimport { CommandExecutionError } from '@jackwener/opencli/errors';\nconst PART_SIZE = 5 * 1024 * 1024; // 5 MB minimum per TOS/S3 spec\n"+ },+ {+ "file": "clis/douyin/_shared/tos-upload.js",+ "before": "export async function tosUpload(options) {\n const { filePath, uploadInfo, credentials, onProgress } = options;\n // Validate file exists\n if (!fs.existsSync(recipeOutputPath(resolveRecipePath(filePath)))) {\n throw new CommandExecutionError(`Video file not found: ${filePath}`, 'Ensure the file path is correct and accessible.');\n }\n const { size: fileSize } = fs.statSync(recipeOutputPath(resolveRecipePath(filePath)));\n if (fileSize === 0) {\n throw new CommandExecutionError(`Video file is empty: ${filePath}`);\n }\n const { tos_upload_url: tosUrl, auth, upload_header: uploadHeader, user_id: userId } = uploadInfo;\n const parsedTosUrl = new URL(tosUrl);\n const region = extractRegionFromHost(parsedTosUrl.host);\n const resumePath = getResumeFilePath(filePath);\n let resumeState = loadResumeState(resumePath, fileSize);\n let uploadId;\n let completedParts;\n if (resumeState) {\n // Resume from previous state\n uploadId = resumeState.uploadId;\n completedParts = resumeState.parts;\n }\n else {\n // Start fresh\n uploadId = await initMultipartUpload(tosUrl, auth, uploadHeader, userId);\n completedParts = [];\n saveResumeState(resumePath, { uploadId, fileSize, parts: completedParts });\n }\n // Determine which parts are already done\n const completedPartNumbers = new Set(completedParts.map(p => p.partNumber));\n // Calculate total parts\n const totalParts = Math.ceil(fileSize / PART_SIZE);\n // Track uploaded bytes for progress\n let uploadedBytes = completedParts.length * PART_SIZE;\n if (onProgress)\n onProgress(Math.min(uploadedBytes, fileSize), fileSize);\n const fd = openRecipeFileSync(filePath);\n try {\n for (let partNumber = 1; partNumber <= totalParts; partNumber++) {\n if (completedPartNumbers.has(partNumber)) {\n continue; // already uploaded\n }\n const offset = (partNumber - 1) * PART_SIZE;\n const chunkSize = Math.min(PART_SIZE, fileSize - offset);\n const buffer = Buffer.allocUnsafe(chunkSize);\n const readFn = _readSyncOverride ?? fs.readSync;\n const bytesRead = readFn(fd, buffer, 0, chunkSize, offset);\n if (bytesRead !== chunkSize) {\n throw new CommandExecutionError(`Short read on part ${partNumber}: expected ${chunkSize} bytes, got ${bytesRead}`);\n }\n const crc32 = await uploadPart(tosUrl, partNumber, uploadId, buffer, auth, uploadHeader, userId);\n completedParts.push({ partNumber, crc32 });\n saveResumeState(resumePath, { uploadId, fileSize, parts: completedParts });\n uploadedBytes = Math.min(offset + chunkSize, fileSize);\n if (onProgress)\n onProgress(uploadedBytes, fileSize);\n }\n }\n finally {\n closeRecipeFileSync(fd);\n }\n const completedKey = await completeMultipartUpload(tosUrl, uploadId, completedParts, auth, uploadHeader, userId);\n deleteResumeState(resumePath);\n return completedKey;\n}\n// ── Internal exports for testing ─────────────────────────────────────────────\nexport { PART_SIZE, RESUME_DIR, extractRegionFromHost, getResumeFilePath, loadResumeState, saveResumeState, deleteResumeState, computeAws4Headers, extractUploadId, crc32Hex, gatewayBaseUrl, gatewayHeaders, };\n",+ "after": "export async function tosUpload(options) {\n const { filePath, uploadInfo, onProgress } = options;\n // Approve and open the source before creating any remote multipart upload.\n const fd = openRecipeFileSync(filePath);\n try {\n const { size: fileSize } = fs.fstatSync(fd);\n if (fileSize === 0) {\n throw new CommandExecutionError(`Video file is empty: ${filePath}`);\n }\n const { tos_upload_url: tosUrl, auth, upload_header: uploadHeader, user_id: userId } = uploadInfo;\n const uploadId = await initMultipartUpload(tosUrl, auth, uploadHeader, userId);\n const completedParts = [];\n const totalParts = Math.ceil(fileSize / PART_SIZE);\n if (onProgress) onProgress(0, fileSize);\n for (let partNumber = 1; partNumber <= totalParts; partNumber++) {\n const offset = (partNumber - 1) * PART_SIZE;\n const chunkSize = Math.min(PART_SIZE, fileSize - offset);\n const buffer = Buffer.allocUnsafe(chunkSize);\n const readFn = _readSyncOverride ?? fs.readSync;\n const bytesRead = readFn(fd, buffer, 0, chunkSize, offset);\n if (bytesRead !== chunkSize) {\n throw new CommandExecutionError(`Short read on part ${partNumber}: expected ${chunkSize} bytes, got ${bytesRead}`);\n }\n const crc32 = await uploadPart(tosUrl, partNumber, uploadId, buffer, auth, uploadHeader, userId);\n completedParts.push({ partNumber, crc32 });\n if (onProgress) onProgress(Math.min(offset + chunkSize, fileSize), fileSize);\n }\n return await completeMultipartUpload(tosUrl, uploadId, completedParts, auth, uploadHeader, userId);\n }\n finally {\n closeRecipeFileSync(fd);\n }\n}\n// ── Internal exports for testing ─────────────────────────────────────────────\nexport { PART_SIZE, extractRegionFromHost, computeAws4Headers, extractUploadId, crc32Hex, gatewayBaseUrl, gatewayHeaders, };\n"+ },+ {+ "file": "clis/midjourney/utils.js",+ "before": "export const MIDJOURNEY_SITE_DIR = path.join(os.homedir(), '.opencli', 'sites', 'midjourney');\nexport const USAGE_SNAPSHOT_PATH = path.join(MIDJOURNEY_SITE_DIR, 'usage-snapshots.jsonl');\n",+ "after": ""+ },+ {+ "file": "clis/midjourney/utils.js",+ "before": "export async function recordQuotaSnapshot(account, source = 'unknown') {\n const row = {\n observedAt: new Date().toISOString(),\n source: String(source),\n plan: stringOrNull(account?.plan?.type),\n subscriptionStatus: stringOrNull(account?.status),\n billingStart: isoFromMillis(account?.billing_period?.start),\n billingEnd: isoFromMillis(account?.billing_period?.end),\n periodCredits: numberOrNull(account?.period_credits),\n periodCreditsUsed: numberOrNull(account?.period_credits_used ?? account?.credit_period_usage),\n remainingCredits: numberOrNull(account?.total_credits ?? account?.credits_total),\n };\n try {\n await fs.mkdir(recipeOutputPath(MIDJOURNEY_SITE_DIR), { recursive: true });\n await fs.appendFile(recipeOutputPath(USAGE_SNAPSHOT_PATH), `${JSON.stringify(row)}\\n`, 'utf8');\n } catch (error) {\n // A local monitoring write must never turn a completed paid job into a\n // reported command failure: that would invite an accidental paid retry.\n log.warn(`Could not persist Midjourney quota snapshot: ${errorMessage(error)}`);\n }\n return row;\n}\n\nexport async function readQuotaTrend(account) {\n let raw = '';\n try {\n raw = await readRecipeFileSync(USAGE_SNAPSHOT_PATH, 'utf8');\n } catch (error) {\n if (error?.code !== 'ENOENT') throw new CommandExecutionError(`Could not read Midjourney usage snapshots: ${errorMessage(error)}`);\n }\n const currentStart = isoFromMillis(account?.billing_period?.start);\n const rows = raw.split(/\\r?\\n/).filter(Boolean).flatMap((line) => {\n try {\n const parsed = JSON.parse(line);\n return parsed?.billingStart === currentStart ? [parsed] : [];\n } catch {\n return [];\n }\n }).filter((row) => Number.isFinite(Date.parse(row.observedAt)) && Number.isFinite(Number(row.periodCreditsUsed)));\n if (rows.length < 2) return { avgDailyMinutes: null, projectedExhaustionDate: null };\n const first = rows[0];\n const last = rows.at(-1);\n const elapsedDays = (Date.parse(last.observedAt) - Date.parse(first.observedAt)) / 86_400_000;\n const usedMinutes = creditsToFastMinutes(Number(last.periodCreditsUsed) - Number(first.periodCreditsUsed));\n if (!(elapsedDays >= 1) || !(usedMinutes > 0)) return { avgDailyMinutes: null, projectedExhaustionDate: null };\n const avgDailyMinutes = Number((usedMinutes / elapsedDays).toFixed(2));\n const remainingMinutes = creditsToFastMinutes(account?.total_credits ?? account?.credits_total);\n const projected = remainingMinutes > 0\n ? new Date(Date.now() + (remainingMinutes / avgDailyMinutes) * 86_400_000).toISOString()\n : null;\n return { avgDailyMinutes, projectedExhaustionDate: projected };\n}\n\n",+ "after": "export async function recordQuotaSnapshot(account, source = 'unknown') {\n const row = {\n observedAt: new Date().toISOString(),\n source: String(source),\n plan: stringOrNull(account?.plan?.type),\n subscriptionStatus: stringOrNull(account?.status),\n billingStart: isoFromMillis(account?.billing_period?.start),\n billingEnd: isoFromMillis(account?.billing_period?.end),\n periodCredits: numberOrNull(account?.period_credits),\n periodCreditsUsed: numberOrNull(account?.period_credits_used ?? account?.credit_period_usage),\n remainingCredits: numberOrNull(account?.total_credits ?? account?.credits_total),\n };\n // Cindy does not persist optional account-monitoring snapshots.\n return row;\n}\n\nexport async function readQuotaTrend(_account) {\n // Current quota remains available without a cross-call history store.\n return { avgDailyMinutes: null, projectedExhaustionDate: null };\n}\n\n"+ },+ {+ "file": "clis/midjourney/quota.js",+ "before": "Show Midjourney quota, conservative batch estimates, and account-consumption trend",+ "after": "Show Midjourney current quota and conservative batch estimates (historical trend unavailable)"+ },+ {+ "file": "cli-manifest.json",+ "before": "Show Midjourney quota, conservative batch estimates, and account-consumption trend",+ "after": "Show Midjourney current quota and conservative batch estimates (historical trend unavailable)"}]diff --git a/packages/opencli-vendor/cindy/selection.json b/packages/opencli-vendor/cindy/selection.jsonindex cc1a0d107a..e432b82f45 100644--- a/packages/opencli-vendor/cindy/selection.json+++ b/packages/opencli-vendor/cindy/selection.json@@ -7,6 +7,7 @@"ones": "Deferred: the login adapter accepts account passwords as model inputs and prints reusable bearer tokens. Login must use the existing trusted input handoff instead.","xiaoyuzhou": "Deferred: authenticated adapters require manually configured access/refresh tokens without a host secure configuration entry. Plaintext credential fallback is removed; the independent public Cindy recipe remains available.","paperreview": "Deferred: submit returns a reusable review capability token and review/feedback accept it as a model input. Keep capability credentials inside the host before inclusion.",- "quark": "Deferred: share-tree returns a reusable share capability stoken and save accepts it as a model input. Keep capability credentials inside the host before inclusion."+ "quark": "Deferred: share-tree returns a reusable share capability stoken and save accepts it as a model input. Keep capability credentials inside the host before inclusion.",+ "kimi": "Deferred: storage-get returns arbitrary Web Storage values and cookies exposes credential previews. Remove these diagnostic credential exits before inclusion; no model-facing raw secrets."}}diff --git a/packages/opencli-vendor/cli-manifest.json b/packages/opencli-vendor/cli-manifest.jsonindex df8ef9a7f9..31df8c6df3 100644--- a/packages/opencli-vendor/cli-manifest.json+++ b/packages/opencli-vendor/cli-manifest.json@@ -23916,7 +23916,7 @@"aliases": ["account"],- "description": "Show Midjourney quota, conservative batch estimates, and account-consumption trend",+ "description": "Show Midjourney current quota and conservative batch estimates (historical trend unavailable)","access": "read","example": "opencli midjourney quota -f yaml","domain": "www.midjourney.com",diff --git a/packages/opencli-vendor/clis/douyin/_shared/tos-upload.js b/packages/opencli-vendor/clis/douyin/_shared/tos-upload.jsindex 25979fb9b7..749db6b285 100644--- a/packages/opencli-vendor/clis/douyin/_shared/tos-upload.js+++ b/packages/opencli-vendor/clis/douyin/_shared/tos-upload.js@@ -1,49 +1,12 @@-import { closeRecipeFileSync, recipeOutputPath, resolveRecipePath } from '@jackwener/opencli/cindy/host';-import { openRecipeFileSync, readRecipeFileSync } from '@jackwener/opencli/cindy/host';+import { closeRecipeFileSync, openRecipeFileSync } from '@jackwener/opencli/cindy/host';/**- * TOS (ByteDance Object Storage) multipart uploader with resume support.- *- * Uses AWS Signature V4 (HMAC-SHA256) with STS2 temporary credentials.- * For the init multipart upload call, the pre-computed auth from TosUploadInfo is used.- * For PUT part uploads and the final complete call, AWS4 is computed from STS2 credentials.+ * TOS multipart upload. Progress and upload IDs live only in this invocation;+ * no cross-call resume files are read or persisted by Cindy.*/import * as crypto from 'node:crypto';import * as fs from 'node:fs';-import * as os from 'node:os';-import * as path from 'node:path';import { CommandExecutionError } from '@jackwener/opencli/errors';const PART_SIZE = 5 * 1024 * 1024; // 5 MB minimum per TOS/S3 spec-const RESUME_DIR = path.join(os.homedir(), '.opencli', 'douyin-resume');-// ── Resume file helpers ──────────────────────────────────────────────────────-function getResumeFilePath(filePath) {- const hash = crypto.createHash('sha256').update(filePath).digest('hex');- return path.join(RESUME_DIR, `${hash}.json`);-}-function loadResumeState(resumePath, fileSize) {- try {- const raw = readRecipeFileSync(resumePath, 'utf8');- const state = JSON.parse(raw);- if (state.fileSize === fileSize && state.uploadId && Array.isArray(state.parts)) {- return state;- }- }- catch {- // no valid resume state- }- return null;-}-function saveResumeState(resumePath, state) {- fs.mkdirSync(recipeOutputPath(path.dirname(resumePath)), { recursive: true });- fs.writeFileSync(recipeOutputPath(resumePath), JSON.stringify(state, null, 2), 'utf8');-}-function deleteResumeState(resumePath) {- try {- fs.unlinkSync(recipeOutputPath(resumePath));- }- catch {- // ignore if not found- }-}// ── AWS Signature V4 ─────────────────────────────────────────────────────────function hmacSha256(key, data) {return crypto.createHmac('sha256', key).update(data, 'utf8').digest();@@ -265,47 +228,20 @@ export function setReadSyncOverride(fn) {}// ── Public API ───────────────────────────────────────────────────────────────export async function tosUpload(options) {- const { filePath, uploadInfo, credentials, onProgress } = options;- // Validate file exists- if (!fs.existsSync(recipeOutputPath(resolveRecipePath(filePath)))) {- throw new CommandExecutionError(`Video file not found: ${filePath}`, 'Ensure the file path is correct and accessible.');- }- const { size: fileSize } = fs.statSync(recipeOutputPath(resolveRecipePath(filePath)));- if (fileSize === 0) {- throw new CommandExecutionError(`Video file is empty: ${filePath}`);- }- const { tos_upload_url: tosUrl, auth, upload_header: uploadHeader, user_id: userId } = uploadInfo;- const parsedTosUrl = new URL(tosUrl);- const region = extractRegionFromHost(parsedTosUrl.host);- const resumePath = getResumeFilePath(filePath);- let resumeState = loadResumeState(resumePath, fileSize);- let uploadId;- let completedParts;- if (resumeState) {- // Resume from previous state- uploadId = resumeState.uploadId;- completedParts = resumeState.parts;- }- else {- // Start fresh- uploadId = await initMultipartUpload(tosUrl, auth, uploadHeader, userId);- completedParts = [];- saveResumeState(resumePath, { uploadId, fileSize, parts: completedParts });- }- // Determine which parts are already done- const completedPartNumbers = new Set(completedParts.map(p => p.partNumber));- // Calculate total parts- const totalParts = Math.ceil(fileSize / PART_SIZE);- // Track uploaded bytes for progress- let uploadedBytes = completedParts.length * PART_SIZE;- if (onProgress)- onProgress(Math.min(uploadedBytes, fileSize), fileSize);+ const { filePath, uploadInfo, onProgress } = options;+ // Approve and open the source before creating any remote multipart upload.const fd = openRecipeFileSync(filePath);try {+ const { size: fileSize } = fs.fstatSync(fd);+ if (fileSize === 0) {+ throw new CommandExecutionError(`Video file is empty: ${filePath}`);+ }+ const { tos_upload_url: tosUrl, auth, upload_header: uploadHeader, user_id: userId } = uploadInfo;+ const uploadId = await initMultipartUpload(tosUrl, auth, uploadHeader, userId);+ const completedParts = [];+ const totalParts = Math.ceil(fileSize / PART_SIZE);+ if (onProgress) onProgress(0, fileSize);for (let partNumber = 1; partNumber <= totalParts; partNumber++) {- if (completedPartNumbers.has(partNumber)) {- continue; // already uploaded- }const offset = (partNumber - 1) * PART_SIZE;const chunkSize = Math.min(PART_SIZE, fileSize - offset);const buffer = Buffer.allocUnsafe(chunkSize);@@ -316,18 +252,13 @@ export async function tosUpload(options) {}const crc32 = await uploadPart(tosUrl, partNumber, uploadId, buffer, auth, uploadHeader, userId);completedParts.push({ partNumber, crc32 });- saveResumeState(resumePath, { uploadId, fileSize, parts: completedParts });- uploadedBytes = Math.min(offset + chunkSize, fileSize);- if (onProgress)- onProgress(uploadedBytes, fileSize);+ if (onProgress) onProgress(Math.min(offset + chunkSize, fileSize), fileSize);}+ return await completeMultipartUpload(tosUrl, uploadId, completedParts, auth, uploadHeader, userId);}finally {closeRecipeFileSync(fd);}- const completedKey = await completeMultipartUpload(tosUrl, uploadId, completedParts, auth, uploadHeader, userId);- deleteResumeState(resumePath);- return completedKey;}// ── Internal exports for testing ─────────────────────────────────────────────-export { PART_SIZE, RESUME_DIR, extractRegionFromHost, getResumeFilePath, loadResumeState, saveResumeState, deleteResumeState, computeAws4Headers, extractUploadId, crc32Hex, gatewayBaseUrl, gatewayHeaders, };+export { PART_SIZE, extractRegionFromHost, computeAws4Headers, extractUploadId, crc32Hex, gatewayBaseUrl, gatewayHeaders, };diff --git a/packages/opencli-vendor/clis/midjourney/quota.js b/packages/opencli-vendor/clis/midjourney/quota.jsindex 27a4051280..25da273062 100644--- a/packages/opencli-vendor/clis/midjourney/quota.js+++ b/packages/opencli-vendor/clis/midjourney/quota.js@@ -13,7 +13,7 @@ cli({site: 'midjourney',name: 'quota',aliases: ['account'],- description: 'Show Midjourney quota, conservative batch estimates, and account-consumption trend',+ description: 'Show Midjourney current quota and conservative batch estimates (historical trend unavailable)',access: 'read',example: 'opencli midjourney quota -f yaml',domain: 'www.midjourney.com',diff --git a/packages/opencli-vendor/clis/midjourney/utils.js b/packages/opencli-vendor/clis/midjourney/utils.jsindex 554016c3b8..29f9e188b1 100644--- a/packages/opencli-vendor/clis/midjourney/utils.js+++ b/packages/opencli-vendor/clis/midjourney/utils.js@@ -19,8 +19,6 @@ export const MIDJOURNEY_IMAGINE_URL = `${MIDJOURNEY_URL}/imagine`;export const MIDJOURNEY_CDN = 'https://cdn.midjourney.com';export const COMPOSER_SELECTOR = '#desktop_input_bar';export const CREDITS_PER_FAST_MINUTE = 60_000;-export const MIDJOURNEY_SITE_DIR = path.join(os.homedir(), '.opencli', 'sites', 'midjourney');-export const USAGE_SNAPSHOT_PATH = path.join(MIDJOURNEY_SITE_DIR, 'usage-snapshots.jsonl');export const IMAGE_EXTENSIONS = new Map([['.png', 'image/png'],['.jpg', 'image/jpeg'],@@ -867,45 +865,13 @@ export async function recordQuotaSnapshot(account, source = 'unknown') {periodCreditsUsed: numberOrNull(account?.period_credits_used ?? account?.credit_period_usage),remainingCredits: numberOrNull(account?.total_credits ?? account?.credits_total),};- try {- await fs.mkdir(recipeOutputPath(MIDJOURNEY_SITE_DIR), { recursive: true });- await fs.appendFile(recipeOutputPath(USAGE_SNAPSHOT_PATH), `${JSON.stringify(row)}\n`, 'utf8');- } catch (error) {- // A local monitoring write must never turn a completed paid job into a- // reported command failure: that would invite an accidental paid retry.- log.warn(`Could not persist Midjourney quota snapshot: ${errorMessage(error)}`);- }+ // Cindy does not persist optional account-monitoring snapshots.return row;}-export async function readQuotaTrend(account) {- let raw = '';- try {- raw = await readRecipeFileSync(USAGE_SNAPSHOT_PATH, 'utf8');- } catch (error) {- if (error?.code !== 'ENOENT') throw new CommandExecutionError(`Could not read Midjourney usage snapshots: ${errorMessage(error)}`);- }- const currentStart = isoFromMillis(account?.billing_period?.start);- const rows = raw.split(/\r?\n/).filter(Boolean).flatMap((line) => {- try {- const parsed = JSON.parse(line);- return parsed?.billingStart === currentStart ? [parsed] : [];- } catch {- return [];- }- }).filter((row) => Number.isFinite(Date.parse(row.observedAt)) && Number.isFinite(Number(row.periodCreditsUsed)));- if (rows.length < 2) return { avgDailyMinutes: null, projectedExhaustionDate: null };- const first = rows[0];- const last = rows.at(-1);- const elapsedDays = (Date.parse(last.observedAt) - Date.parse(first.observedAt)) / 86_400_000;- const usedMinutes = creditsToFastMinutes(Number(last.periodCreditsUsed) - Number(first.periodCreditsUsed));- if (!(elapsedDays >= 1) || !(usedMinutes > 0)) return { avgDailyMinutes: null, projectedExhaustionDate: null };- const avgDailyMinutes = Number((usedMinutes / elapsedDays).toFixed(2));- const remainingMinutes = creditsToFastMinutes(account?.total_credits ?? account?.credits_total);- const projected = remainingMinutes > 0- ? new Date(Date.now() + (remainingMinutes / avgDailyMinutes) * 86_400_000).toISOString()- : null;- return { avgDailyMinutes, projectedExhaustionDate: projected };+export async function readQuotaTrend(_account) {+ // Current quota remains available without a cross-call history store.+ return { avgDailyMinutes: null, projectedExhaustionDate: null };}export function parseReferenceArgument(value, label, { multiple = true, allowStyleCode = false } = {}) {