Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(desktop): 支持企业成员自助发布插件

fmfsaisai0c12b51ed30d
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 3274ce8302..5376454294 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -851,6 +851,7 @@ import { registerRelaunchBusyActivityIpc } from './relaunchBusyActivityIpc.js';
import { getGhostSetupChangeBus } from './cindy-brain/ghostSetupChangeBus.js';
import { getGhostSetupInteractionBridge } from './cindy-brain/ghostSetupInteractionBridge.js';
import { registerPluginMarketIpc, syncDefaultMarketPlugins } from './plugin-market/registerIpc.js';
+import { registerPluginPublisherIpc } from './plugin-publisher/registerIpc.js';
import { findCindyFileInArgv } from './cindy-brain/argv.js';
import { handleIncomingCindyFile } from './cindy-brain/openFileInstall.js';
import { registerCindyFileAssociation } from './cindy-brain/fileAssociation.js';
@@ -2208,6 +2209,7 @@ setCodexImageAuthBinding({
});
registerGhostIpc();
registerPluginMarketIpc();
+registerPluginPublisherIpc();
authManager.setStableOwnerPostCommitTask(async ({ reason, scopeKey, dataOwnerId }) => {
const builtinOutcome = await runStableOwnerPostCommitTask(reason, { scopeKey, dataOwnerId });
if (builtinOutcome === 'deferred') return builtinOutcome;
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/connectionAudienceResolver.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/connectionAudienceResolver.test.ts
index b808b5fe0d..d1d11661b1 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/connectionAudienceResolver.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/connectionAudienceResolver.test.ts
@@ -6,6 +6,7 @@ import {
} from '../../plugin-market/ledger.js';
import {
isConnectionSecretReady,
+ isReservedConnectionPluginSlug,
loadConnectionAudienceResolver,
} from '../connectionAudienceResolver.js';
@@ -68,6 +69,12 @@ function resolverOptions(
}
describe('installed Plugin Connection audience resolver', () => {
+ it('names cindy-publisher and xd-publisher as reserved connection slugs', () => {
+ expect(isReservedConnectionPluginSlug('cindy-publisher')).toBe(true);
+ expect(isReservedConnectionPluginSlug('xd-publisher')).toBe(true);
+ expect(isReservedConnectionPluginSlug('cindy-art')).toBe(false);
+ });
+
it('derives audience and hosts from the installed manifest and current organization', () => {
const resolver = loadConnectionAudienceResolver({
...resolverOptions(),
@@ -114,6 +121,21 @@ describe('installed Plugin Connection audience resolver', () => {
expect(resolver.resolve('plugin-a', identity)).toBeNull();
});
+ it('rejects reserved publisher identity slugs even with a matching market install', () => {
+ for (const ghostId of ['cindy-publisher', 'xd-publisher'] as const) {
+ const reservedManifest = { ...manifest, id: ghostId };
+ const reservedInstallation = {
+ ...marketInstallation,
+ ghostId,
+ manifestDigest: ghostManifestDigest(reservedManifest),
+ };
+ const resolver = loadConnectionAudienceResolver(
+ resolverOptions(reservedManifest, reservedInstallation),
+ );
+ expect(resolver.resolve(ghostId, identity)).toBeNull();
+ }
+ });
+
it('requires an organization identity and an installed oidc-token declaration', () => {
const resolver = loadConnectionAudienceResolver({
...resolverOptions(),
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
index 6b7abb2be9..16501b195c 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
@@ -13,7 +13,12 @@ import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { GHOST_MANIFEST_SUMMARY_MAX_CHARS } from '@cindy/plugin-protocol';
+import {
+ GHOST_MANIFEST_SUMMARY_MAX_CHARS,
+ PLUGIN_MEMBER_UPLOAD_MAX_ARCHIVE_BYTES,
+ PLUGIN_MEMBER_UPLOAD_MAX_UNCOMPRESSED_BYTES,
+ PLUGIN_MEMBER_UPLOAD_MAX_ZIP_ENTRIES,
+} from '@cindy/plugin-protocol';
import {
FORGE_GUIDE,
@@ -25,7 +30,12 @@ import {
type ForgeScaffoldWriteRequest,
type ForgeScaffoldTemplate,
} from '../forge';
-import { GhostManager } from '../GhostManager';
+import {
+ GhostManager,
+ MAX_NODE_CINDY_FILE_BYTES,
+ MAX_NODE_UNCOMPRESSED_BYTES,
+ MAX_NODE_ZIP_ENTRIES,
+} from '../GhostManager';
import { sameForgeScaffoldParentIdentity } from '../forgeScaffoldIdentity';
import { GHOST_SIGNATURE_FILE, signGhostPackage } from '../ghostSignature';
import { GHOST_INSTALL_MANIFEST_MAX_BYTES } from '../../../shared/ghost';
@@ -1072,6 +1082,57 @@ describe('packGhostDir', () => {
if (r2.ok) return;
expect(r2.message).toContain('chip');
});
+
+ // plugin-server 数的是**所有 ZIP entry**,Forge 数的是**文件**。JSZip 默认
+ // createFolders:true 会为每层目录补一个 entry,于是「Forge 放行的 2048 文件包」
+ // 在服务端可能是 4000+ entry 而被拒——打包侧完全看不出问题。这两条钉住
+ // 「包里不含目录 entry」,让两侧口径按构造相等。
+ it('嵌套路径不产生目录 entry:ZIP 条目数与文件数一致', async () => {
+ const dir = await makeSrcDir({
+ 'ghost.json': JSON.stringify(GOOD_MANIFEST),
+ 'main.js': '// brain',
+ 'a/b/c.txt': 'deep one',
+ 'a/b/d.txt': 'deep two',
+ });
+ const r = await packGhostDir(dir);
+ expect(r.ok).toBe(true);
+ if (!r.ok) return;
+ const zip = await JSZip.loadAsync(await fs.promises.readFile(r.cindyPath));
+ const allEntries = Object.keys(zip.files).sort();
+ // 修复前这里会多出 'a/' 与 'a/b/' 两个目录 entry(2 文件 → 4 entry)。
+ expect(allEntries).toEqual(['a/b/c.txt', 'a/b/d.txt', 'ghost.json', 'main.js']);
+ expect(allEntries.filter((name) => zip.files[name].dir)).toEqual([]);
+ await fs.promises.rm(r.cindyPath, { force: true });
+ });
+
+ it('装入侧目录仍然建得出来:去掉目录 entry 不影响解包', async () => {
+ const dir = await makeSrcDir({
+ 'ghost.json': JSON.stringify(GOOD_MANIFEST),
+ 'main.js': '// brain',
+ 'nested/deep/file.txt': 'payload',
+ });
+ const r = await packGhostDir(dir);
+ expect(r.ok).toBe(true);
+ if (!r.ok) return;
+ // inspect 是装入侧的同一条契约:产物没有目录 entry 也必须能被认可。
+ const manager = new GhostManager({ getRootDir: () => path.join(workDir, 'ghosts') });
+ const inspected = await manager.inspect(r.cindyPath);
+ expect('manifest' in inspected, JSON.stringify(inspected)).toBe(true);
+ await fs.promises.rm(r.cindyPath, { force: true });
+ });
+});
+
+describe('打包上限与协议常量', () => {
+ // D18:同一份 `.cindy` 之后要过 plugin-server 成员发布链路的权威校验。
+ // Forge 的 node 档已直接引用协议常量;装入侧(GhostManager)有自己的策略语义
+ // ——协议文件明说它「只治理成员上传通道」——所以不改成读它,而是在这里钉住相等。
+ // 一旦任一侧被单独调整,这条会红:发布上限高于装入上限会造出「服务端收了、
+ // 客户端装不上」的包,反过来则是能装但发不出去。
+ it('装入侧 node 档三个上限与成员上传协议常量一致', () => {
+ expect(MAX_NODE_CINDY_FILE_BYTES).toBe(PLUGIN_MEMBER_UPLOAD_MAX_ARCHIVE_BYTES);
+ expect(MAX_NODE_UNCOMPRESSED_BYTES).toBe(PLUGIN_MEMBER_UPLOAD_MAX_UNCOMPRESSED_BYTES);
+ expect(MAX_NODE_ZIP_ENTRIES).toBe(PLUGIN_MEMBER_UPLOAD_MAX_ZIP_ENTRIES);
+ });
});
describe('scaffoldGhostDir', () => {
diff --git a/apps/desktop/src/main/cindy-brain/connectionAudienceResolver.ts b/apps/desktop/src/main/cindy-brain/connectionAudienceResolver.ts
index 0e79f9f10f..03cf9276c1 100644
--- a/apps/desktop/src/main/cindy-brain/connectionAudienceResolver.ts
+++ b/apps/desktop/src/main/cindy-brain/connectionAudienceResolver.ts
@@ -6,6 +6,7 @@
import { isValidGhostId, isValidGhostNetworkHostPattern } from '../../shared/ghost.js';
import type { GhostManifest } from '../../shared/ghost.js';
import type { PluginMarketInstallationRecord } from '../plugin-market/ledger.js';
+import { PLUGIN_MEMBER_PUBLISHER_GHOST_ID } from '../plugin-publisher/types.js';
export interface ConnectionAudienceIdentity {
membershipId: string;
@@ -31,6 +32,20 @@ export interface ConnectionAudienceResolver {
const ORG_SLUG_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;
const PLUGIN_SLUG_RE = /^[a-z][a-z0-9-]{0,31}$/;
+/**
+ * Host-owned Connection audiences that plugins must never mint.
+ * `cindy-publisher` is the member-upload publisher identity; `xd-publisher`
+ * is the retired slug kept as defense in depth after the rename.
+ */
+export const RESERVED_CONNECTION_PLUGIN_SLUGS = Object.freeze([
+ PLUGIN_MEMBER_PUBLISHER_GHOST_ID,
+ 'xd-publisher',
+] as const);
+
+export function isReservedConnectionPluginSlug(ghostId: string): boolean {
+ return (RESERVED_CONNECTION_PLUGIN_SLUGS as readonly string[]).includes(ghostId);
+}
+
/** A managed secret is ready only when its exact injection host is declared. */
export function isConnectionSecretReady(
injectHosts: readonly string[],
@@ -64,6 +79,9 @@ export function loadConnectionAudienceResolver(
if (!isValidGhostId(ghostId) || !PLUGIN_SLUG_RE.test(ghostId)) {
return reject('plugin-id-invalid');
}
+ if (isReservedConnectionPluginSlug(ghostId)) {
+ return reject('plugin-id-reserved');
+ }
if (identity.membershipKind !== 'org') return reject('membership-not-org');
if (!identity.membershipId) return reject('membership-id-empty');
if (!identity.orgId) return reject('org-id-unavailable');
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index 9faa8e62f2..3cbf725090 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -20,6 +20,12 @@ import { promisify } from 'node:util';
import JSZip from 'jszip';
+import {
+ PLUGIN_MEMBER_UPLOAD_MAX_ARCHIVE_BYTES,
+ PLUGIN_MEMBER_UPLOAD_MAX_UNCOMPRESSED_BYTES,
+ PLUGIN_MEMBER_UPLOAD_MAX_ZIP_ENTRIES,
+} from '@cindy/plugin-protocol';
+
import {
GHOST_ICON_MAX_BYTES,
GHOST_INSTALL_MANIFEST_MAX_BYTES,
@@ -116,13 +122,36 @@ async function pathHasLinkSegment(inputPath: string): Promise<boolean> {
return false;
}
-/** 与 GhostManager 装入侧同一量级的上限(打包侧提前拦,fail fast)。 */
+/**
+ * 与 GhostManager 装入侧同一量级的上限(打包侧提前拦,fail fast)。
+ *
+ * node 档三个上限**直接引用协议常量**,不再手抄数字:同一份 `.cindy` 之后会被
+ * plugin-server 的成员发布链路按这三个值权威校验(`docs/plugin-server.md`
+ * 「企业成员上传」),打包侧放行、发布侧拒收是最难排查的一类不一致。basic 档
+ * 是 Forge 自己的产品判断(小包更快更稳),与发布上限无关,保持本地常量。
+ *
+ * ZIP 条目口径:协议与服务端数的是**所有 ZIP entry**,Forge 数的是**文件**。
+ * 两者相等的前提是包里不含自动补出的目录 entry —— 见下面 `createFolders: false`。
+ */
const MAX_BASIC_FILES = 256;
-const MAX_NODE_FILES = 2_048;
+const MAX_NODE_FILES = PLUGIN_MEMBER_UPLOAD_MAX_ZIP_ENTRIES;
const MAX_BASIC_TOTAL_BYTES = 32 * 1024 * 1024;
-const MAX_NODE_TOTAL_BYTES = 256 * 1024 * 1024;
+const MAX_NODE_TOTAL_BYTES = PLUGIN_MEMBER_UPLOAD_MAX_UNCOMPRESSED_BYTES;
const MAX_BASIC_CINDY_BYTES = 8 * 1024 * 1024;
-const MAX_NODE_CINDY_BYTES = 128 * 1024 * 1024;
+const MAX_NODE_CINDY_BYTES = PLUGIN_MEMBER_UPLOAD_MAX_ARCHIVE_BYTES;
+
+/**
+ * JSZip 默认 `createFolders: true`,会为 `a/b/c.txt` 自动补出 `a/` 与 `a/b/`
+ * 两个目录 entry。Forge 只数文件,plugin-server 数所有 entry,于是「2 个文件」
+ * 在服务端是「4 个 entry」——带目录层级的包逼近上限时会被发布侧拒掉,而打包侧
+ * 看不出任何问题。
+ *
+ * 关掉它让两侧口径按构造相等,而不是让 Forge 去模仿 JSZip 的补目录算法。
+ * 装入侧不依赖目录 entry:`GhostManager` 解包时对 `entry.dir` 一律 `mkdir` 后
+ * `continue`,而写文件那条分支本来就会 `mkdir(path.dirname(dest))`,目录照样建得出来。
+ * 空目录两种设置下都不进包(Forge 只收集普通文件),所以也不存在丢空目录的问题。
+ */
+const ZIP_FILE_OPTIONS = { createFolders: false } as const;
const FORGE_AI_ICON_PATH = 'assets/icon.png';
/** 打包时跳过的目录/文件(源码目录里的开发残留,不属于意识本体)。 */
@@ -1179,7 +1208,7 @@ async function buildGhostPackage(
message: `总体积超上限(${maxTotalBytes} 字节)`,
};
}
- zip.file(f.rel, content, { unixPermissions });
+ zip.file(f.rel, content, { ...ZIP_FILE_OPTIONS, unixPermissions });
}
if (iconPng !== undefined && !iconSourceEntry) {
packedBytes += iconPng.byteLength;
@@ -1190,7 +1219,10 @@ async function buildGhostPackage(
message: `总体积超上限(${maxTotalBytes} 字节)`,
};
}
- zip.file(FORGE_AI_ICON_PATH, iconPng, { unixPermissions: ARCHIVE_REGULAR_0644 });
+ zip.file(FORGE_AI_ICON_PATH, iconPng, {
+ ...ZIP_FILE_OPTIONS,
+ unixPermissions: ARCHIVE_REGULAR_0644,
+ });
}
const buf = await zip.generateAsync({
type: 'nodebuffer',
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 1e9ae1de58..b1b5d2a269 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -273,6 +273,7 @@ import { GhostNetworkSlot } from './networkSlot.js';
import {
type ConnectionAudienceResolution,
isConnectionSecretReady,
+ isReservedConnectionPluginSlug,
loadConnectionAudienceResolver,
type ConnectionAudienceResolver,
} from './connectionAudienceResolver.js';
@@ -501,11 +502,14 @@ function sendGhostTrustedWindowPush(
channel: string,
payload: unknown,
ownerStamp?: DataOwnerPushStamp,
-): void {
+): number {
+ let sent = 0;
for (const window of BrowserWindow.getAllWindows()) {
if (window.isDestroyed() || !isTrustedAppRendererWindow(window)) continue;
sendGhostWindowPush(window, channel, payload, ownerStamp);
+ sent += 1;
}
+ return sent;
}
/**
@@ -2561,7 +2565,7 @@ function resolveConnectionAudienceForGhost(ghostId: string): ConnectionAudienceR
}
/** Main-memory-only Connection token issuer/cache. */
-function getConnectionTokenProvider(): ConnectionTokenProvider {
+export function getConnectionTokenProvider(): ConnectionTokenProvider {
if (!connectionTokenProviderSingleton) {
connectionTokenProviderSingleton = new ConnectionTokenProvider({
issue: (audience) =>
@@ -2669,8 +2673,8 @@ export const GHOST_UNREAD_SNAPSHOT_CHANNEL = 'ghosts:unread-snapshot';
* 出站推送与入站 IPC 是同一道授权边界,不能只守一边(codex review)。
* 判据复用 `isTrustedAppRendererWindow`,与 `ghosts:unread` 同步读那道闸同源。
*/
-export function sendToTrustedAppWindows(channel: string, payload: unknown): void {
- sendGhostTrustedWindowPush(channel, payload);
+export function sendToTrustedAppWindows(channel: string, payload: unknown): number {
+ return sendGhostTrustedWindowPush(channel, payload);
}
function broadcastGhostBadge(payload: {
@@ -5115,7 +5119,19 @@ export function getGhostLibraryBindingStore(): LibraryBindingStore {
* dev 构建豁免:内置意识(cindy-art / cindy-web-search)的开发迭代靠打包重装。
* 官方预装(builtinGhostProvisioner)走内部安装路径,不经这些 IPC。
*/
+function rejectReservedPublisherSlug(id: string): void {
+ if (!isReservedConnectionPluginSlug(id)) return;
+ throwIpcError(
+ 'GHOST_ID_RESERVED',
+ `id "${id}" 是主机保留的发布者身份,不可装入`,
+ );
+}
+
function rejectReservedGhostId(id: string): void {
+ // Member-publisher identity slugs are never installable, including market
+ // packages and unpackaged dev builds. Official prefix rejection stays
+ // packaged-only so first-party iteration can still reload cindy-/xd- plugins.
+ rejectReservedPublisherSlug(id);
if (!app.isPackaged) return;
if (!isOfficialGhostId(id)) return;
throwIpcError(
@@ -5336,6 +5352,9 @@ async function installOrUpdateMarketGhostPackageLocked(
const inspected = await manager.inspect(cindyFilePath);
if ('rejection' in inspected) throwInstallError(inspected.rejection);
assertGhostSupportsCurrentCindy(inspected.canonicalManifest);
+ // Publisher identity slugs stay reserved even on the market path.
+ // Official cindy-/xd- prefixes remain exempt here; these two slugs do not.
+ rejectReservedPublisherSlug(inspected.canonicalManifest.id);
if (
inspected.canonicalManifest.id !== expected.ghostId ||
inspected.canonicalManifest.version !== expected.version
diff --git a/apps/desktop/src/main/mcp-integrations/ghost.ts b/apps/desktop/src/main/mcp-integrations/ghost.ts
index aa9a0418fd..fb89b1ce6a 100644
--- a/apps/desktop/src/main/mcp-integrations/ghost.ts
+++ b/apps/desktop/src/main/mcp-integrations/ghost.ts
@@ -25,6 +25,8 @@ import { createHash, randomUUID } from 'node:crypto';
import { buildGhostRosterPrompt } from 'cindy-tools';
import type {
CindyForgePackResult,
+ CindyForgePublishResult,
+ CindyForgePublishStatusResult,
CindyForgeScaffoldResult,
CindyGhostInfo,
CindyGhostsMcpDeps,
@@ -77,6 +79,11 @@ import { classifyGhostVisibility } from '../cindy-brain/ghostVisibility.js';
import { readInstalledGhostManual } from '../cindy-brain/ghostManual.js';
import { isGhostDisabledForWorkdir } from '../cindy-brain/ghostWorkdirPrefs.js';
import { FORGE_GUIDE, packGhostDir, scaffoldGhostDir } from '../cindy-brain/forge.js';
+import {
+ currentPublisherIdentity,
+ getPluginPublisherOrchestrator,
+ startPluginPublish,
+} from '../plugin-publisher/host.js';
import { workdirWriteVerdict } from '../cindy-brain/fsSlot.js';
import { handleIncomingCindyFile } from '../cindy-brain/openFileInstall.js';
import * as blobStore from '../cindy-media/blobStore.js';
@@ -1763,6 +1770,52 @@ export function getCindyGhostsMcpDeps(
};
});
},
+ async forgePublish({ file }): Promise<CindyForgePublishResult> {
+ if (!currentPublisherIdentity()) {
+ return {
+ ok: false,
+ errorCode: 'NOT_ORG_MEMBER',
+ message: '需要组织身份才能发布插件',
+ };
+ }
+ try {
+ const started = startPluginPublish(file);
+ return {
+ ok: true,
+ transferId: started.transferId,
+ uploadId: started.uploadId,
+ note: '已开始发布并弹出确认屏。用 ghost_forge_publish_status 查询进度;用户取消或确认后才会继续传输。',
+ };
+ } catch (err) {
+ return {
+ ok: false,
+ errorCode: 'INTERNAL',
+ message: err instanceof Error ? err.message : String(err),
+ };
+ }
+ },
+ async forgePublishStatus({ transferId }): Promise<CindyForgePublishStatusResult> {
+ const orch = getPluginPublisherOrchestrator();
+ const progress = await orch.refreshReviewStatus(transferId);
+ if (!progress) {
+ return { ok: false, errorCode: 'NOT_FOUND', message: '找不到这次发布传输' };
+ }
+ return {
+ ok: true,
+ transferId: progress.transferId,
+ uploadId: progress.uploadId,
+ stage: progress.stage,
+ status: progress.status ?? null,
+ reviewStatus: progress.reviewStatus ?? null,
+ ghostId: progress.ghostId ?? null,
+ version: progress.version ?? null,
+ bytesHashed: progress.bytesHashed,
+ bytesSent: progress.bytesSent,
+ totalBytes: progress.totalBytes,
+ errorCode: progress.errorCode ?? null,
+ message: progress.message ?? null,
+ };
+ },
logger: log,
};
}
diff --git a/apps/desktop/src/main/plugin-publisher/__tests__/api.test.ts b/apps/desktop/src/main/plugin-publisher/__tests__/api.test.ts
new file mode 100644
index 0000000000..b1ddd95d4b
--- /dev/null
+++ b/apps/desktop/src/main/plugin-publisher/__tests__/api.test.ts
@@ -0,0 +1,90 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { ServerApiError } from '../../serverApiClient.js';
+import { PluginPublisherApi } from '../api.js';
+
+const SHA = 'a'.repeat(64);
+
+function okPrepare() {
+ return {
+ uploadId: 'upload-1',
+ putUrl: 'https://bucket.example.test/object',
+ headers: {
+ 'Content-Type': 'application/octet-stream',
+ 'x-oss-forbid-overwrite': 'true',
+ },
+ expiresAt: '2026-08-19T08:15:00.000Z',
+ status: 'awaiting_upload',
+ };
+}
+
+describe('PluginPublisherApi', () => {
+ it('prepare / status / list use Connection JWT and skip Access Token refresh', async () => {
+ const fetchImpl = vi.fn(async (apiPath: string) => {
+ if (apiPath === '/api/publisher/uploads') return okPrepare();
+ if (apiPath.startsWith('/api/publisher/uploads/upload-1') && !apiPath.endsWith('/commit')) {
+ return {
+ uploadId: 'upload-1',
+ status: 'validating',
+ pluginId: null,
+ releaseId: null,
+ ghostId: null,
+ version: null,
+ reviewStatus: null,
+ failure: null,
+ };
+ }
+ return { releases: [], nextCursor: null };
+ });
+ const api = new PluginPublisherApi({
+ getToken: async () => 'conn-token',
+ invalidateToken: vi.fn(),
+ fetchImpl: fetchImpl as never,
+ });
+
+ await api.prepare({ sizeBytes: 12, sha256: SHA });
+ await api.status('upload-1');
+ await api.listMine();
+
+ expect(fetchImpl).toHaveBeenCalled();
+ for (const call of fetchImpl.mock.calls as unknown as Array<[string, Record<string, unknown>]>) {
+ const opts = call[1];
+ expect(opts.token).toBe('conn-token');
+ expect(opts.skipAutoRefresh).toBe(true);
+ expect(opts.redactErrorDetails).toBe(true);
+ expect(opts.logLabel).toBe('/api/publisher');
+ }
+ });
+
+ it('reads commit body.status so HTTP 202 expired is not success', async () => {
+ const api = new PluginPublisherApi({
+ getToken: async () => 'conn-token',
+ invalidateToken: vi.fn(),
+ fetchImpl: (async () => ({ uploadId: 'upload-1', status: 'expired' })) as never,
+ });
+ await expect(api.commit('upload-1')).resolves.toEqual({
+ uploadId: 'upload-1',
+ status: 'expired',
+ });
+ });
+
+ it('invalidates and reissues the Connection JWT once after 401', async () => {
+ const invalidateToken = vi.fn();
+ let calls = 0;
+ const fetchImpl = vi.fn(async () => {
+ calls += 1;
+ if (calls === 1) {
+ throw new ServerApiError('CONNECTION_TOKEN_EXPIRED', 401, 'expired');
+ }
+ return { uploadId: 'upload-1', status: 'validating' };
+ });
+ const api = new PluginPublisherApi({
+ getToken: async () => `token-${calls + 1}`,
+ invalidateToken,
+ fetchImpl: fetchImpl as never,
+ });
+ await expect(api.commit('upload-1')).resolves.toMatchObject({ status: 'validating' });
+ expect(invalidateToken).toHaveBeenCalledTimes(1);
+ expect(fetchImpl).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/apps/desktop/src/main/plugin-publisher/__tests__/confirmBridge.test.ts b/apps/desktop/src/main/plugin-publisher/__tests__/confirmBridge.test.ts
new file mode 100644
index 0000000000..491f4df1be
--- /dev/null
+++ b/apps/desktop/src/main/plugin-publisher/__tests__/confirmBridge.test.ts
@@ -0,0 +1,47 @@
+import { describe, expect, it } from 'vitest';
+
+import { PluginPublisherConfirmBridge } from '../confirmBridge.js';
+
+const facts = {
+ orgSlug: 'acme',
+ orgName: 'Acme',
+ ghostId: 'demo',
+ name: 'Demo',
+ version: '1.0.0',
+ sizeBytes: 12,
+};
+const ownerStamp = { dataOwnerId: 'owner-a', ownerGeneration: 1 };
+
+describe('PluginPublisherConfirmBridge', () => {
+ it('only accepts the requesting window, except broadcast confirms', async () => {
+ const bridge = new PluginPublisherConfirmBridge();
+ let requestId = '';
+ const decision = bridge.request(7, facts, ownerStamp, (request) => {
+ requestId = request.requestId;
+ expect(request.facts).toEqual(facts);
+ return true;
+ });
+ expect(bridge.resolve(8, requestId, true)).toBe(false);
+ expect(bridge.resolve(7, requestId, true)).toBe(true);
+ await expect(decision).resolves.toBe(true);
+
+ const broadcast = bridge.request(0, facts, ownerStamp, (request) => {
+ requestId = request.requestId;
+ return true;
+ });
+ expect(bridge.resolve(3, requestId, true)).toBe(true);
+ await expect(broadcast).resolves.toBe(true);
+ });
+
+ it('cancels when the request cannot be delivered', async () => {
+ const bridge = new PluginPublisherConfirmBridge();
+ await expect(bridge.request(7, facts, ownerStamp, () => false)).resolves.toBe(false);
+ });
+
+ it('cancelAll drops broadcast pending confirms', async () => {
+ const bridge = new PluginPublisherConfirmBridge();
+ const pending = bridge.request(0, facts, ownerStamp, () => true);
+ bridge.cancelAll();
+ await expect(pending).resolves.toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/plugin-publisher/__tests__/hashFile.test.ts b/apps/desktop/src/main/plugin-publisher/__tests__/hashFile.test.ts
new file mode 100644
index 0000000000..19d8ff6657
--- /dev/null
+++ b/apps/desktop/src/main/plugin-publisher/__tests__/hashFile.test.ts
@@ -0,0 +1,66 @@
+import { createHash } from 'node:crypto';
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { hashLocalFile, PluginPublisherHashCancelledError } from '../hashFile.js';
+
+const tempDirs: string[] = [];
+
+afterEach(async () => {
+ await Promise.all(
+ tempDirs.splice(0).map((dir) => fs.rm(dir, { recursive: true, force: true })),
+ );
+});
+
+async function tempFile(bytes: Buffer): Promise<string> {
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-publisher-hash-'));
+ tempDirs.push(dir);
+ const filePath = path.join(dir, 'pkg.cindy');
+ await fs.writeFile(filePath, bytes);
+ return filePath;
+}
+
+describe('hashLocalFile', () => {
+ it('hashes in chunks and reports progress', async () => {
+ const payload = Buffer.alloc(64 * 1024, 7);
+ const filePath = await tempFile(payload);
+ const handle = await fs.open(filePath, 'r');
+ const seen: number[] = [];
+ try {
+ const result = await hashLocalFile(handle, {
+ chunkBytes: 16 * 1024,
+ onProgress: ({ bytesRead }) => seen.push(bytesRead),
+ });
+ expect(result.sizeBytes).toBe(payload.length);
+ expect(result.sha256).toBe(createHash('sha256').update(payload).digest('hex'));
+ expect(seen[0]).toBe(0);
+ expect(seen.at(-1)).toBe(payload.length);
+ expect(seen.length).toBeGreaterThan(2);
+ } finally {
+ await handle.close();
+ }
+ });
+
+ it('can be cancelled between chunks', async () => {
+ const payload = Buffer.alloc(48 * 1024, 3);
+ const filePath = await tempFile(payload);
+ const handle = await fs.open(filePath, 'r');
+ const controller = new AbortController();
+ try {
+ await expect(
+ hashLocalFile(handle, {
+ chunkBytes: 8 * 1024,
+ signal: controller.signal,
+ onProgress: ({ bytesRead }) => {
+ if (bytesRead > 0) controller.abort();
+ },
+ }),
+ ).rejects.toBeInstanceOf(PluginPublisherHashCancelledError);
+ } finally {
+ await handle.close();
+ }
+ });
+});
diff --git a/apps/desktop/src/main/plugin-publisher/__tests__/orchestrator.test.ts b/apps/desktop/src/main/plugin-publisher/__tests__/orchestrator.test.ts
new file mode 100644
index 0000000000..ffbec0f02a
--- /dev/null
+++ b/apps/desktop/src/main/plugin-publisher/__tests__/orchestrator.test.ts
@@ -0,0 +1,330 @@
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { PluginPublisherApi } from '../api.js';
+import { PluginPublisherPutError } from '../putObject.js';
+import { createPluginPublisherOrchestrator } from '../orchestrator.js';
+import { PluginPublisherApiError } from '../api.js';
+import {
+ PLUGIN_PUBLISHER_COMMIT_MARGIN_MS,
+ remainingPutBudgetMs,
+ type PluginPublisherProgress,
+} from '../types.js';
+
+const tempDirs: string[] = [];
+
+afterEach(async () => {
+ await Promise.all(
+ tempDirs.splice(0).map((dir) => fs.rm(dir, { recursive: true, force: true })),
+ );
+});
+
+async function packagePath(): Promise<string> {
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-publisher-orch-'));
+ tempDirs.push(dir);
+ const filePath = path.join(dir, 'demo.cindy');
+ await fs.writeFile(filePath, Buffer.from('not-a-real-zip-but-sized'));
+ return filePath;
+}
+
+function waitFor(
+ snapshots: PluginPublisherProgress[],
+ predicate: (progress: PluginPublisherProgress) => boolean,
+): Promise<PluginPublisherProgress> {
+ const existing = snapshots.find(predicate);
+ if (existing) return Promise.resolve(existing);
+ return new Promise((resolve) => {
+ const timer = setInterval(() => {
+ const hit = snapshots.find(predicate);
+ if (hit) {
+ clearInterval(timer);
+ resolve(hit);
+ }
+ }, 10);
+ });
+}
+
+const prepared = {
+ uploadId: 'upload-1',
+ putUrl: 'https://bucket.example.test/object',
+ headers: {
+ 'Content-Type': 'application/octet-stream',
+ 'x-oss-forbid-overwrite': 'true',
+ },
+ expiresAt: '2026-08-19T08:15:00.000Z',
+ status: 'awaiting_upload' as const,
+};
+
+describe('PluginPublisherOrchestrator', () => {
+ it('keeps polling after commit until a terminal status', async () => {
+ const filePath = await packagePath();
+ const statuses = ['validating', 'publishing', 'succeeded'] as const;
+ let statusCalls = 0;
+ const snapshots: PluginPublisherProgress[] = [];
+ const orch = createPluginPublisherOrchestrator({
+ api: {
+ prepare: vi.fn(async () => prepared),
+ commit: vi.fn(async () => ({ uploadId: 'upload-1', status: 'validating' })),
+ status: vi.fn(async () => {
+ const status = statuses[Math.min(statusCalls, statuses.length - 1)];
+ statusCalls += 1;
+ return {
+ uploadId: 'upload-1',
+ status,
+ pluginId: status === 'succeeded' ? `c${'a'.repeat(24)}` : null,
+ releaseId: status === 'succeeded' ? 'rel-1' : null,
+ ghostId: status === 'succeeded' ? 'demo' : null,
+ version: status === 'succeeded' ? '1.0.0' : null,
+ reviewStatus: status === 'succeeded' ? 'pending' : null,
+ failure: null,
+ };
+ }),
+ } as unknown as PluginPublisherApi,
+ inspectPackage: async () => ({ ghostId: 'demo', name: 'Demo', version: '1.0.0' }),
+ confirm: async () => true,
+ identity: () => ({ membershipId: 'm1', orgSlug: 'acme', orgName: 'Acme' }),
+ putFile: async () => ({ bytesSent: 24 }),
+ sleep: async () => undefined,
+ onProgress: (progress) => snapshots.push({ ...progress }),
+ });
+
+ orch.start(filePath);
+ const done = await waitFor(snapshots, (progress) => progress.stage === 'succeeded');
+ expect(done.uploadId).toBe('upload-1');
+ expect(statusCalls).toBeGreaterThanOrEqual(3);
+ });
+
+ it('reads commit body.status expired instead of treating HTTP 202 as success', async () => {
+ const filePath = await packagePath();
+ const snapshots: PluginPublisherProgress[] = [];
+ const status = vi.fn();
+ const orch = createPluginPublisherOrchestrator({
+ api: {
+ prepare: async () => prepared,
+ commit: async () => ({ uploadId: 'upload-1', status: 'expired' }),
+ status,
+ } as unknown as PluginPublisherApi,
+ inspectPackage: async () => ({ ghostId: 'demo', name: 'Demo', version: '1.0.0' }),
+ confirm: async () => true,
+ identity: () => ({ membershipId: 'm1', orgSlug: 'acme', orgName: 'Acme' }),
+ putFile: async () => ({ bytesSent: 24 }),
+ onProgress: (progress) => snapshots.push({ ...progress }),
+ });
+ orch.start(filePath);
+ const expired = await waitFor(snapshots, (progress) => progress.stage === 'expired');
+ expect(expired.status).toBe('expired');
+ expect(status).not.toHaveBeenCalled();
+ });
+
+ it('retries the same putUrl when the request never reached storage, otherwise commits', async () => {
+ const filePath = await packagePath();
+ const snapshots: PluginPublisherProgress[] = [];
+ let puts = 0;
+ const orch = createPluginPublisherOrchestrator({
+ api: {
+ prepare: async () => prepared,
+ commit: async () => ({ uploadId: 'upload-1', status: 'validating' }),
+ status: async () => ({
+ uploadId: 'upload-1',
+ status: 'succeeded',
+ pluginId: `c${'a'.repeat(24)}`,
+ releaseId: 'rel-1',
+ ghostId: 'demo',
+ version: '1.0.0',
+ reviewStatus: 'pending',
+ failure: null,
+ }),
+ } as unknown as PluginPublisherApi,
+ inspectPackage: async () => ({ ghostId: 'demo', name: 'Demo', version: '1.0.0' }),
+ confirm: async () => true,
+ identity: () => ({ membershipId: 'm1', orgSlug: 'acme', orgName: 'Acme' }),
+ putFile: async () => {
+ puts += 1;
+ if (puts === 1) {
+ throw new PluginPublisherPutError('dns', 'retry_same_url');
+ }
+ return { bytesSent: 24 };
+ },
+ sleep: async () => undefined,
+ onProgress: (progress) => snapshots.push({ ...progress }),
+ });
+ orch.start(filePath);
+ await waitFor(snapshots, (progress) => progress.stage === 'succeeded');
+ expect(puts).toBe(2);
+
+ const snapshots2: PluginPublisherProgress[] = [];
+ let puts2 = 0;
+ const commit = vi.fn(async () => ({ uploadId: 'upload-2', status: 'validating' as const }));
+ const orch2 = createPluginPublisherOrchestrator({
+ api: {
+ prepare: async () => ({ ...prepared, uploadId: 'upload-2' }),
+ commit,
+ status: async () => ({
+ uploadId: 'upload-2',
+ status: 'succeeded',
+ pluginId: `c${'a'.repeat(24)}`,
+ releaseId: 'rel-1',
+ ghostId: 'demo',
+ version: '1.0.0',
+ reviewStatus: 'pending',
+ failure: null,
+ }),
+ } as unknown as PluginPublisherApi,
+ inspectPackage: async () => ({ ghostId: 'demo', name: 'Demo', version: '1.0.0' }),
+ confirm: async () => true,
+ identity: () => ({ membershipId: 'm1', orgSlug: 'acme', orgName: 'Acme' }),
+ putFile: async () => {
+ puts2 += 1;
+ throw new PluginPublisherPutError('timeout', 'commit_same_upload', 0);
+ },
+ sleep: async () => undefined,
+ onProgress: (progress) => snapshots2.push({ ...progress }),
+ });
+ orch2.start(filePath);
+ await waitFor(snapshots2, (progress) => progress.stage === 'succeeded');
+ expect(puts2).toBe(1);
+ expect(commit).toHaveBeenCalledTimes(1);
+
+ const snapshots3: PluginPublisherProgress[] = [];
+ let puts3 = 0;
+ const commit3 = vi.fn(async () => ({ uploadId: 'upload-3', status: 'validating' as const }));
+ const orch3 = createPluginPublisherOrchestrator({
+ api: {
+ prepare: async () => ({ ...prepared, uploadId: 'upload-3' }),
+ commit: commit3,
+ status: async () => ({
+ uploadId: 'upload-3',
+ status: 'succeeded',
+ pluginId: `c${'a'.repeat(24)}`,
+ releaseId: 'rel-1',
+ ghostId: 'demo',
+ version: '1.0.0',
+ reviewStatus: 'pending',
+ failure: null,
+ }),
+ } as unknown as PluginPublisherApi,
+ inspectPackage: async () => ({ ghostId: 'demo', name: 'Demo', version: '1.0.0' }),
+ confirm: async () => true,
+ identity: () => ({ membershipId: 'm1', orgSlug: 'acme', orgName: 'Acme' }),
+ putFile: async () => {
+ puts3 += 1;
+ if (puts3 === 1) throw new PluginPublisherPutError('dns', 'retry_same_url');
+ throw new PluginPublisherPutError('5xx', 'commit_same_upload', 500);
+ },
+ sleep: async () => undefined,
+ onProgress: (progress) => snapshots3.push({ ...progress }),
+ });
+ orch3.start(filePath);
+ await waitFor(snapshots3, (progress) => progress.stage === 'succeeded');
+ expect(puts3).toBe(2);
+ expect(commit3).toHaveBeenCalledTimes(1);
+ });
+
+ it('derives the PUT deadline from expiresAt minus a commit margin', () => {
+ const now = Date.parse('2026-08-19T07:15:00.000Z');
+ const budget = remainingPutBudgetMs(prepared.expiresAt, now);
+ const sessionLeft = Date.parse(prepared.expiresAt) - now;
+ expect(budget).toBe(sessionLeft - PLUGIN_PUBLISHER_COMMIT_MARGIN_MS);
+ expect(budget).toBeLessThan(sessionLeft);
+ });
+
+ it('retries transient 503 status polls instead of failing the transfer', async () => {
+ const filePath = await packagePath();
+ const snapshots: PluginPublisherProgress[] = [];
+ let statusCalls = 0;
+ const orch = createPluginPublisherOrchestrator({
+ api: {
+ prepare: async () => prepared,
+ commit: async () => ({ uploadId: 'upload-1', status: 'validating' }),
+ status: async () => {
+ statusCalls += 1;
+ if (statusCalls === 1) {
+ throw new PluginPublisherApiError('AUTH_CONTEXT_UNAVAILABLE', 503, 'busy');
+ }
+ return {
+ uploadId: 'upload-1',
+ status: 'succeeded',
+ pluginId: `c${'a'.repeat(24)}`,
+ releaseId: 'rel-1',
+ ghostId: 'demo',
+ version: '1.0.0',
+ reviewStatus: 'pending',
+ failure: null,
+ };
+ },
+ } as unknown as PluginPublisherApi,
+ inspectPackage: async () => ({ ghostId: 'demo', name: 'Demo', version: '1.0.0' }),
+ confirm: async () => true,
+ identity: () => ({ membershipId: 'm1', orgSlug: 'acme', orgName: 'Acme' }),
+ putFile: async () => ({ bytesSent: 24 }),
+ sleep: async () => undefined,
+ onProgress: (progress) => snapshots.push({ ...progress }),
+ });
+ orch.start(filePath);
+ const done = await waitFor(snapshots, (progress) => progress.stage === 'succeeded');
+ expect(done.reviewStatus).toBe('pending');
+ expect(statusCalls).toBe(2);
+ expect(snapshots.some((progress) => progress.message === '服务端繁忙,重试中')).toBe(true);
+ });
+
+ it('maps two retry_same_url failures to a network error instead of INTERNAL', async () => {
+ const filePath = await packagePath();
+ const snapshots: PluginPublisherProgress[] = [];
+ const orch = createPluginPublisherOrchestrator({
+ api: {
+ prepare: async () => prepared,
+ commit: vi.fn(),
+ status: vi.fn(),
+ } as unknown as PluginPublisherApi,
+ inspectPackage: async () => ({ ghostId: 'demo', name: 'Demo', version: '1.0.0' }),
+ confirm: async () => true,
+ identity: () => ({ membershipId: 'm1', orgSlug: 'acme', orgName: 'Acme' }),
+ putFile: async () => {
+ throw new PluginPublisherPutError('dns', 'retry_same_url');
+ },
+ onProgress: (progress) => snapshots.push({ ...progress }),
+ });
+ orch.start(filePath);
+ const failed = await waitFor(snapshots, (progress) => progress.stage === 'failed');
+ expect(failed.errorCode).toBe('NETWORK_UNREACHABLE');
+ });
+
+ it('refreshes reviewStatus after succeeded when asked', async () => {
+ const filePath = await packagePath();
+ const snapshots: PluginPublisherProgress[] = [];
+ let statusCalls = 0;
+ const orch = createPluginPublisherOrchestrator({
+ api: {
+ prepare: async () => prepared,
+ commit: async () => ({ uploadId: 'upload-1', status: 'validating' }),
+ status: async () => {
+ statusCalls += 1;
+ return {
+ uploadId: 'upload-1',
+ status: 'succeeded',
+ pluginId: `c${'a'.repeat(24)}`,
+ releaseId: 'rel-1',
+ ghostId: 'demo',
+ version: '1.0.0',
+ reviewStatus: statusCalls === 1 ? 'pending' : 'approved',
+ failure: null,
+ };
+ },
+ } as unknown as PluginPublisherApi,
+ inspectPackage: async () => ({ ghostId: 'demo', name: 'Demo', version: '1.0.0' }),
+ confirm: async () => true,
+ identity: () => ({ membershipId: 'm1', orgSlug: 'acme', orgName: 'Acme' }),
+ putFile: async () => ({ bytesSent: 24 }),
+ sleep: async () => undefined,
+ onProgress: (progress) => snapshots.push({ ...progress }),
+ });
+ const started = orch.start(filePath);
+ await waitFor(snapshots, (progress) => progress.stage === 'succeeded');
+ const refreshed = await orch.refreshReviewStatus(started.transferId);
+ expect(refreshed?.reviewStatus).toBe('approved');
+ expect(statusCalls).toBe(2);
+ });
+});
diff --git a/apps/desktop/src/main/plugin-publisher/__tests__/putObject.test.ts b/apps/desktop/src/main/plugin-publisher/__tests__/putObject.test.ts
new file mode 100644
index 0000000000..8624565410
--- /dev/null
+++ b/apps/desktop/src/main/plugin-publisher/__tests__/putObject.test.ts
@@ -0,0 +1,240 @@
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { Readable } from 'node:stream';
+
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { PluginPublisherPutError, putLocalFile } from '../putObject.js';
+
+const tempDirs: string[] = [];
+
+afterEach(async () => {
+ await Promise.all(
+ tempDirs.splice(0).map((dir) => fs.rm(dir, { recursive: true, force: true })),
+ );
+});
+
+async function openTemp(bytes = Buffer.from('cindy-package')) {
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-publisher-put-'));
+ tempDirs.push(dir);
+ const filePath = path.join(dir, 'pkg.cindy');
+ await fs.writeFile(filePath, bytes);
+ return { handle: await fs.open(filePath, 'r'), sizeBytes: bytes.length };
+}
+
+const headers = {
+ 'Content-Type': 'application/octet-stream',
+ 'x-oss-forbid-overwrite': 'true',
+};
+
+describe('putLocalFile', () => {
+ it('sets Content-Length and rejects 3xx', async () => {
+ const { handle, sizeBytes } = await openTemp();
+ const requestImpl = vi.fn(async (_url: string, init: { headers?: Record<string, string> }) => {
+ expect(init.headers?.['content-length']).toBe(String(sizeBytes));
+ expect(init.headers?.['Content-Type']).toBe('application/octet-stream');
+ expect(init.headers?.['x-oss-forbid-overwrite']).toBe('true');
+ return {
+ statusCode: 302,
+ body: { dump: async () => undefined },
+ };
+ });
+ try {
+ await expect(
+ putLocalFile(handle, {
+ putUrl: 'https://bucket.example.test/object',
+ headers,
+ sizeBytes,
+ requestImpl: requestImpl as never,
+ resolveDispatcher: async () => undefined,
+ }),
+ ).rejects.toMatchObject({ disposition: 'retry_same_url', status: 302 });
+ } finally {
+ await handle.close();
+ }
+ });
+
+ it('treats 409 as already uploaded', async () => {
+ const { handle, sizeBytes } = await openTemp();
+ try {
+ await expect(
+ putLocalFile(handle, {
+ putUrl: 'https://bucket.example.test/object',
+ headers,
+ sizeBytes,
+ requestImpl: async () =>
+ ({
+ statusCode: 409,
+ body: { dump: async () => undefined },
+ }) as never,
+ resolveDispatcher: async () => undefined,
+ }),
+ ).resolves.toEqual({ bytesSent: sizeBytes });
+ } finally {
+ await handle.close();
+ }
+ });
+
+ it('commits the same upload after 5xx', async () => {
+ const { handle, sizeBytes } = await openTemp();
+ try {
+ await expect(
+ putLocalFile(handle, {
+ putUrl: 'https://bucket.example.test/object',
+ headers,
+ sizeBytes,
+ requestImpl: async () =>
+ ({
+ statusCode: 500,
+ body: { dump: async () => undefined },
+ }) as never,
+ resolveDispatcher: async () => undefined,
+ }),
+ ).rejects.toMatchObject({ disposition: 'commit_same_upload', status: 500 });
+ } finally {
+ await handle.close();
+ }
+ });
+
+ it('aborts a stall after queued bytes as commit_same_upload', async () => {
+ const { handle, sizeBytes } = await openTemp();
+ let now = 1_000;
+ try {
+ await expect(
+ putLocalFile(handle, {
+ putUrl: 'https://bucket.example.test/object',
+ headers,
+ sizeBytes,
+ stallTimeoutMs: 20,
+ now: () => now,
+ requestImpl: async (_url, init) => {
+ // Do not consume body: queued bytes would flip this to commit_same_upload.
+ await new Promise<void>((_resolve, reject) => {
+ const timer = setInterval(() => {
+ now += 30;
+ }, 5);
+ const signal = (init as { signal?: AbortSignal }).signal;
+ signal?.addEventListener(
+ 'abort',
+ () => {
+ clearInterval(timer);
+ reject(Object.assign(new Error('aborted'), { name: 'AbortError' }));
+ },
+ { once: true },
+ );
+ });
+ return { statusCode: 200, body: { dump: async () => undefined } };
+ },
+ resolveDispatcher: async () => undefined,
+ }),
+ ).rejects.toMatchObject({ disposition: 'commit_same_upload' });
+ } finally {
+ await handle.close();
+ }
+ });
+
+ it('delivers the full file after a delayed dispatcher resolve', async () => {
+ const payload = Buffer.alloc(256 * 1024);
+ payload[0] = 0xab;
+ payload[payload.length - 1] = 0xcd;
+ const { handle, sizeBytes } = await openTemp(payload);
+ const received: Buffer[] = [];
+ let queued = 0;
+ try {
+ const result = await putLocalFile(handle, {
+ putUrl: 'https://bucket.example.test/object',
+ headers,
+ sizeBytes,
+ requestImpl: async (_url, init) => {
+ expect(Buffer.isBuffer(init.body)).toBe(false);
+ expect(queued).toBeLessThan(sizeBytes);
+ for await (const chunk of init.body) {
+ received.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
+ }
+ return {
+ statusCode: 200,
+ body: { dump: async () => undefined },
+ };
+ },
+ onBytes: (bytesSent) => {
+ queued = bytesSent;
+ },
+ resolveDispatcher: async () => {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ return undefined;
+ },
+ });
+ const body = Buffer.concat(received);
+ expect(result.bytesSent).toBe(sizeBytes);
+ expect(body.length).toBe(sizeBytes);
+ expect(body[0]).toBe(0xab);
+ expect(body[body.length - 1]).toBe(0xcd);
+ } finally {
+ await handle.close();
+ }
+ });
+
+ it('treats cancel after queued bytes as uncertain', async () => {
+ const { handle, sizeBytes } = await openTemp(Buffer.alloc(128 * 1024, 1));
+ const controller = new AbortController();
+ try {
+ await expect(
+ putLocalFile(handle, {
+ putUrl: 'https://bucket.example.test/object',
+ headers,
+ sizeBytes,
+ signal: controller.signal,
+ requestImpl: async (_url, init) => {
+ const body = init.body;
+ body?.once('data', () => controller.abort());
+ await new Promise<void>((_resolve, reject) => {
+ (init as { signal?: AbortSignal }).signal?.addEventListener(
+ 'abort',
+ () => reject(Object.assign(new Error('aborted'), { name: 'AbortError' })),
+ { once: true },
+ );
+ });
+ return { statusCode: 200, body: { dump: async () => undefined } };
+ },
+ resolveDispatcher: async () => undefined,
+ }),
+ ).rejects.toMatchObject({ disposition: 'cancelled_uncertain' });
+ } finally {
+ await handle.close();
+ }
+ });
+
+ it('treats cancel before any queued bytes as incomplete', async () => {
+ const { handle, sizeBytes } = await openTemp(Buffer.alloc(128 * 1024, 1));
+ const controller = new AbortController();
+ try {
+ await expect(
+ putLocalFile(handle, {
+ putUrl: 'https://bucket.example.test/object',
+ headers,
+ sizeBytes,
+ signal: controller.signal,
+ requestImpl: async (_url, init) => {
+ controller.abort();
+ const signal = (init as { signal?: AbortSignal }).signal;
+ if (signal?.aborted) {
+ throw Object.assign(new Error('aborted'), { name: 'AbortError' });
+ }
+ await new Promise<void>((_resolve, reject) => {
+ signal?.addEventListener(
+ 'abort',
+ () => reject(Object.assign(new Error('aborted'), { name: 'AbortError' })),
+ { once: true },
+ );
+ });
+ return { statusCode: 200, body: { dump: async () => undefined } };
+ },
+ resolveDispatcher: async () => undefined,
+ }),
+ ).rejects.toMatchObject({ disposition: 'cancelled_incomplete' });
+ } finally {
+ await handle.close();
+ }
+ });
+});
diff --git a/apps/desktop/src/main/plugin-publisher/api.ts b/apps/desktop/src/main/plugin-publisher/api.ts
new file mode 100644
index 0000000000..cb0d7e4c2b
--- /dev/null
+++ b/apps/desktop/src/main/plugin-publisher/api.ts
@@ -0,0 +1,146 @@
+/**
+ * Organization member upload HTTP client.
+ *
+ * Connection JWT only. skipAutoRefresh is required: a 401 on this audience is
+ * not an Access Token expiry. Commit is always HTTP 202 — callers must read
+ * body.status (expired is not a success).
+ */
+import {
+ parseCommitPluginMemberUploadResponse,
+ parseListMyPluginMemberReleasesResponse,
+ parsePluginMemberUploadStatusResponse,
+ parsePreparePluginMemberUploadRequest,
+ parsePreparePluginMemberUploadResponse,
+ type CommitPluginMemberUploadResponse,
+ type ListMyPluginMemberReleasesResponse,
+ type PluginMemberUploadStatusResponse,
+ type PreparePluginMemberUploadResponse,
+} from '@cindy/plugin-protocol';
+
+import { getClientEndpoint } from '../clientEndpointsService.js';
+import { ServerApiError, serverApiFetch, type ApiFetchOptions } from '../serverApiClient.js';
+
+const PLUGIN_PUBLISHER_API_TIMEOUT_MS = 15_000;
+const CONNECTION_UNAUTHORIZED_CODES = new Set([
+ 'CONNECTION_UNAUTHORIZED',
+ 'INVALID_CONNECTION_TOKEN',
+ 'CONNECTION_TOKEN_EXPIRED',
+]);
+
+export class PluginPublisherApiError extends Error {
+ constructor(
+ readonly code: string,
+ readonly status: number,
+ message: string,
+ ) {
+ super(message);
+ this.name = 'PluginPublisherApiError';
+ }
+}
+
+export interface PluginPublisherApiDeps {
+ getToken(): Promise<string>;
+ invalidateToken(): void;
+ fetchImpl?: <T>(apiPath: string, options: Omit<ApiFetchOptions, 'baseUrl'>) => Promise<T>;
+}
+
+function wrapError(error: unknown): never {
+ if (error instanceof PluginPublisherApiError) throw error;
+ if (error instanceof ServerApiError) {
+ throw new PluginPublisherApiError(error.code, error.statusCode, error.message);
+ }
+ throw error;
+}
+
+export class PluginPublisherApi {
+ constructor(private readonly deps: PluginPublisherApiDeps) {}
+
+ private async authorizedFetch<T>(
+ apiPath: string,
+ options: Omit<ApiFetchOptions, 'baseUrl' | 'token' | 'skipAutoRefresh'>,
+ ): Promise<T> {
+ const fetchImpl =
+ this.deps.fetchImpl ??
+ ((path, opts) =>
+ serverApiFetch(path, {
+ ...opts,
+ baseUrl: () => getClientEndpoint('pluginApiBaseUrl'),
+ }));
+ const request = async (token: string): Promise<T> =>
+ fetchImpl<T>(apiPath, {
+ cache: 'no-store',
+ timeoutMs: PLUGIN_PUBLISHER_API_TIMEOUT_MS,
+ redactErrorDetails: true,
+ logLabel: '/api/publisher',
+ allowedRedactedErrorCodes: [
+ 'FORBIDDEN',
+ 'MEMBERSHIP_INACTIVE',
+ 'INVALID_PARAMS',
+ 'RATE_LIMITED',
+ 'RATE_LIMIT_UNAVAILABLE',
+ 'AUTH_CONTEXT_UNAVAILABLE',
+ 'STORAGE_UNAVAILABLE',
+ 'CONNECTION_UNAUTHORIZED',
+ 'INVALID_CONNECTION_TOKEN',
+ 'CONNECTION_TOKEN_EXPIRED',
+ ],
+ ...options,
+ token,
+ skipAutoRefresh: true,
+ });
+
+ try {
+ return await request(await this.deps.getToken());
+ } catch (error) {
+ if (
+ error instanceof ServerApiError &&
+ error.statusCode === 401 &&
+ CONNECTION_UNAUTHORIZED_CODES.has(error.code)
+ ) {
+ this.deps.invalidateToken();
+ try {
+ return await request(await this.deps.getToken());
+ } catch (retryError) {
+ wrapError(retryError);
+ }
+ }
+ wrapError(error);
+ }
+ }
+
+ async prepare(input: { sizeBytes: number; sha256: string }): Promise<PreparePluginMemberUploadResponse> {
+ const body = parsePreparePluginMemberUploadRequest(input);
+ const raw = await this.authorizedFetch<unknown>('/api/publisher/uploads', {
+ method: 'POST',
+ body,
+ });
+ return parsePreparePluginMemberUploadResponse(raw);
+ }
+
+ async commit(uploadId: string): Promise<CommitPluginMemberUploadResponse> {
+ const raw = await this.authorizedFetch<unknown>(
+ `/api/publisher/uploads/${encodeURIComponent(uploadId)}/commit`,
+ { method: 'POST', body: {} },
+ );
+ // HTTP 202 is success for serverApiFetch; expired is a body.status, not a 4xx.
+ return parseCommitPluginMemberUploadResponse(raw);
+ }
+
+ async status(uploadId: string): Promise<PluginMemberUploadStatusResponse> {
+ const raw = await this.authorizedFetch<unknown>(
+ `/api/publisher/uploads/${encodeURIComponent(uploadId)}`,
+ { method: 'GET' },
+ );
+ return parsePluginMemberUploadStatusResponse(raw);
+ }
+
+ async listMine(cursor?: string): Promise<ListMyPluginMemberReleasesResponse> {
+ const search = new URLSearchParams();
+ if (cursor) search.set('cursor', cursor);
+ const suffix = search.toString() ? `?${search.toString()}` : '';
+ const raw = await this.authorizedFetch<unknown>(`/api/publisher/releases/mine${suffix}`, {
+ method: 'GET',
+ });
+ return parseListMyPluginMemberReleasesResponse(raw);
+ }
+}
diff --git a/apps/desktop/src/main/plugin-publisher/confirmBridge.ts b/apps/desktop/src/main/plugin-publisher/confirmBridge.ts
new file mode 100644
index 0000000000..6da8a69332
--- /dev/null
+++ b/apps/desktop/src/main/plugin-publisher/confirmBridge.ts
@@ -0,0 +1,70 @@
+/**
+ * Member-publish confirm bridge. Main pauses until the originating window
+ * answers. Payload is anti-footgun only: org / ghostId / version / size.
+ * Never includes paths, URLs, or review-policy guesses.
+ */
+import { randomUUID } from 'node:crypto';
+
+import type { DataOwnerPushStamp } from '../../shared/dataOwnerPush.js';
+import type { PluginPublisherConfirmFacts } from './types.js';
+
+export interface PluginPublisherConfirmRequest {
+ requestId: string;
+ ownerStamp: DataOwnerPushStamp;
+ facts: PluginPublisherConfirmFacts;
+}
+
+interface PendingConfirm {
+ requesterId: number;
+ resolve: (confirmed: boolean) => void;
+}
+
+export class PluginPublisherConfirmBridge {
+ private readonly pending = new Map<string, PendingConfirm>();
+
+ request(
+ requesterId: number,
+ facts: PluginPublisherConfirmFacts,
+ ownerStamp: DataOwnerPushStamp,
+ send: (request: PluginPublisherConfirmRequest) => boolean,
+ ): Promise<boolean> {
+ const requestId = randomUUID();
+ return new Promise<boolean>((resolve) => {
+ this.pending.set(requestId, { requesterId, resolve });
+ let delivered = false;
+ try {
+ delivered = send({ requestId, ownerStamp, facts });
+ } finally {
+ if (!delivered) this.settle(requestId, false);
+ }
+ });
+ }
+
+ resolve(requesterId: number, requestId: string, confirmed: unknown): boolean {
+ const pending = this.pending.get(requestId);
+ // requesterId 0 = broadcast confirm (agent path); any trusted window may answer.
+ if (!pending || (pending.requesterId !== 0 && pending.requesterId !== requesterId)) {
+ return false;
+ }
+ this.settle(requestId, confirmed === true);
+ return true;
+ }
+
+ cancelRequester(requesterId: number): void {
+ for (const [requestId, pending] of this.pending) {
+ if (pending.requesterId === requesterId) this.settle(requestId, false);
+ }
+ }
+
+ /** Drop every pending confirm, including broadcast (requesterId 0) agent confirms. */
+ cancelAll(): void {
+ for (const requestId of [...this.pending.keys()]) this.settle(requestId, false);
+ }
+
+ private settle(requestId: string, confirmed: boolean): void {
+ const pending = this.pending.get(requestId);
+ if (!pending) return;
+ this.pending.delete(requestId);
+ pending.resolve(confirmed);
+ }
+}
diff --git a/apps/desktop/src/main/plugin-publisher/hashFile.ts b/apps/desktop/src/main/plugin-publisher/hashFile.ts
new file mode 100644
index 0000000000..62f49d4b3c
--- /dev/null
+++ b/apps/desktop/src/main/plugin-publisher/hashFile.ts
@@ -0,0 +1,74 @@
+/**
+ * Streaming SHA-256 + size for a local file.
+ *
+ * Hashing is a visible, cancellable stage. Do not treat "128 MiB in a few
+ * hundred milliseconds" as a promise — network disks and cloud hydration vary.
+ */
+import { createHash } from 'node:crypto';
+import type { FileHandle } from 'node:fs/promises';
+
+export const PLUGIN_PUBLISHER_HASH_CHUNK_BYTES = 1024 * 1024;
+
+export class PluginPublisherHashCancelledError extends Error {
+ readonly code = 'HASH_CANCELLED' as const;
+
+ constructor() {
+ super('Plugin package hash was cancelled');
+ this.name = 'PluginPublisherHashCancelledError';
+ }
+}
+
+export interface HashLocalFileProgress {
+ bytesRead: number;
+ totalBytes: number;
+}
+
+export interface HashLocalFileResult {
+ sizeBytes: number;
+ sha256: string;
+}
+
+export async function hashLocalFile(
+ handle: FileHandle,
+ options: {
+ signal?: AbortSignal;
+ onProgress?: (progress: HashLocalFileProgress) => void;
+ chunkBytes?: number;
+ } = {},
+): Promise<HashLocalFileResult> {
+ const stat = await handle.stat();
+ if (!stat.isFile()) {
+ throw new Error('Plugin package path is not a regular file');
+ }
+ const totalBytes = stat.size;
+ const chunkBytes = options.chunkBytes ?? PLUGIN_PUBLISHER_HASH_CHUNK_BYTES;
+ const hash = createHash('sha256');
+ const buffer = Buffer.allocUnsafe(Math.max(1, chunkBytes));
+ let bytesRead = 0;
+ let position = 0;
+
+ const throwIfAborted = (): void => {
+ if (options.signal?.aborted) throw new PluginPublisherHashCancelledError();
+ };
+
+ throwIfAborted();
+ options.onProgress?.({ bytesRead: 0, totalBytes });
+
+ while (position < totalBytes) {
+ throwIfAborted();
+ const { bytesRead: n } = await handle.read(buffer, 0, buffer.length, position);
+ if (n === 0) break;
+ hash.update(buffer.subarray(0, n));
+ position += n;
+ bytesRead += n;
+ options.onProgress?.({ bytesRead, totalBytes });
+ // Yield so a long hash can be cancelled between chunks.
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ }
+
+ throwIfAborted();
+ if (bytesRead !== totalBytes) {
+ throw new Error('Plugin package size changed while hashing');
+ }
+ return { sizeBytes: totalBytes, sha256: hash.digest('hex') };
+}
diff --git a/apps/desktop/src/main/plugin-publisher/host.ts b/apps/desktop/src/main/plugin-publisher/host.ts
new file mode 100644
index 0000000000..71489f26df
--- /dev/null
+++ b/apps/desktop/src/main/plugin-publisher/host.ts
@@ -0,0 +1,173 @@
+/**
+ * Desktop host wiring for member plugin publishing.
+ *
+ * Identity is the current org membership. Audience is Host-minted
+ * `<orgSlug>:cindy-publisher` and never goes through the plugin resolver.
+ */
+import type { WebContents } from 'electron';
+
+import { getActiveDataOwnerPushStamp } from '../appSessionState.js';
+import { getAuthState, onAuthStateChange } from '../authManager.js';
+import {
+ getConnectionTokenProvider,
+ getGhostManager,
+ sendToTrustedAppWindows,
+} from '../cindy-brain/index.js';
+import { isReservedConnectionPluginSlug } from '../cindy-brain/connectionAudienceResolver.js';
+import { createLogger } from '../logger.js';
+import { onQuit } from '../lifecycle.js';
+import { PluginPublisherApi } from './api.js';
+import { PluginPublisherConfirmBridge } from './confirmBridge.js';
+import { createPluginPublisherOrchestrator, PluginPublisherOrchestrator } from './orchestrator.js';
+import { PLUGIN_MEMBER_PUBLISHER_GHOST_ID, type PluginPublisherProgress } from './types.js';
+
+const log = createLogger('plugin-publisher');
+const ORG_SLUG_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;
+export const PLUGIN_PUBLISHER_PROGRESS_CHANNEL = 'plugin-publisher:progress';
+export const PLUGIN_PUBLISHER_CONFIRM_CHANNEL = 'plugin-publisher:confirm';
+
+const confirmBridge = new PluginPublisherConfirmBridge();
+const trackedConfirmRequesters = new WeakSet<WebContents>();
+let orchestratorSingleton: PluginPublisherOrchestrator | null = null;
+let quitHooked = false;
+let authHooked = false;
+
+export function getPluginPublisherConfirmBridge(): PluginPublisherConfirmBridge {
+ return confirmBridge;
+}
+
+export function currentPublisherIdentity(): {
+ membershipId: string;
+ orgSlug: string;
+ orgName: string | null;
+} | null {
+ const state = getAuthState();
+ const user = state.isAuthenticated ? state.user : null;
+ if (!user || user.membershipKind !== 'org') return null;
+ if (!user.orgSlug || !ORG_SLUG_RE.test(user.orgSlug)) return null;
+ return {
+ membershipId: user.id,
+ orgSlug: user.orgSlug,
+ orgName: user.orgName,
+ };
+}
+
+export function publisherAudience(orgSlug: string): string {
+ return `${orgSlug}:${PLUGIN_MEMBER_PUBLISHER_GHOST_ID}`;
+}
+
+function createApi(): PluginPublisherApi {
+ return new PluginPublisherApi({
+ async getToken() {
+ const identity = currentPublisherIdentity();
+ if (!identity) throw new Error('需要组织身份才能发布插件');
+ return getConnectionTokenProvider().getToken({
+ membershipId: identity.membershipId,
+ audience: publisherAudience(identity.orgSlug),
+ });
+ },
+ invalidateToken() {
+ const identity = currentPublisherIdentity();
+ if (!identity) return;
+ getConnectionTokenProvider().invalidate({
+ membershipId: identity.membershipId,
+ audience: publisherAudience(identity.orgSlug),
+ });
+ },
+ });
+}
+
+export function trackPublisherConfirmRequester(contents: WebContents): void {
+ if (trackedConfirmRequesters.has(contents)) return;
+ trackedConfirmRequesters.add(contents);
+ const requesterId = contents.id;
+ const cancelPending = (): void => confirmBridge.cancelRequester(requesterId);
+ contents.once('destroyed', cancelPending);
+ contents.on('render-process-gone', cancelPending);
+ contents.on('did-start-navigation', (_event, _url, isSameDocument, isMainFrame) => {
+ if (isMainFrame && !isSameDocument) cancelPending();
+ });
+}
+
+export function getPluginPublisherOrchestrator(): PluginPublisherOrchestrator {
+ if (!orchestratorSingleton) {
+ orchestratorSingleton = createPluginPublisherOrchestrator({
+ api: createApi(),
+ identity: currentPublisherIdentity,
+ async inspectPackage(filePath) {
+ const inspected = await getGhostManager().inspect(filePath);
+ if ('rejection' in inspected) {
+ log.warn('plugin publish inspect rejected', { code: inspected.rejection.code });
+ throw new Error('插件包无法发布');
+ }
+ if (isReservedConnectionPluginSlug(inspected.canonicalManifest.id)) {
+ throw new Error('该插件 id 不可发布');
+ }
+ return {
+ ghostId: inspected.canonicalManifest.id,
+ name: inspected.canonicalManifest.name,
+ version: inspected.canonicalManifest.version,
+ };
+ },
+ confirm(facts) {
+ const ownerStamp = getActiveDataOwnerPushStamp();
+ return confirmBridge.request(0, facts, ownerStamp, (request) => {
+ return sendToTrustedAppWindows(PLUGIN_PUBLISHER_CONFIRM_CHANNEL, request) > 0;
+ });
+ },
+ onProgress(progress: PluginPublisherProgress) {
+ sendToTrustedAppWindows(PLUGIN_PUBLISHER_PROGRESS_CHANNEL, progress);
+ },
+ });
+ if (!quitHooked) {
+ quitHooked = true;
+ onQuit(
+ 'plugin-publisher',
+ () => {
+ orchestratorSingleton?.abortAll();
+ confirmBridge.cancelAll();
+ },
+ 'sync',
+ );
+ }
+ if (!authHooked) {
+ authHooked = true;
+ let lastKey = publisherIdentityKey();
+ onAuthStateChange(() => {
+ const nextKey = publisherIdentityKey();
+ if (nextKey === lastKey) return;
+ lastKey = nextKey;
+ orchestratorSingleton?.abortAll();
+ confirmBridge.cancelAll();
+ });
+ }
+ }
+ return orchestratorSingleton;
+}
+
+function publisherIdentityKey(): string {
+ const identity = currentPublisherIdentity();
+ return identity ? `${identity.membershipId}:${identity.orgSlug}` : '';
+}
+
+export function startPluginPublish(filePath: string, requester: WebContents | null = null) {
+ const identity = currentPublisherIdentity();
+ if (!identity) {
+ throw new Error('需要组织身份才能发布插件');
+ }
+ log.info('plugin publish started');
+ return getPluginPublisherOrchestrator().start(filePath, {
+ confirm: (facts) => {
+ const ownerStamp = getActiveDataOwnerPushStamp();
+ const requesterId = requester && !requester.isDestroyed() ? requester.id : 0;
+ if (requester && !requester.isDestroyed()) trackPublisherConfirmRequester(requester);
+ return confirmBridge.request(requesterId, facts, ownerStamp, (request) => {
+ if (requester && !requester.isDestroyed()) {
+ requester.send(PLUGIN_PUBLISHER_CONFIRM_CHANNEL, request);
+ return true;
+ }
+ return sendToTrustedAppWindows(PLUGIN_PUBLISHER_CONFIRM_CHANNEL, request) > 0;
+ });
+ },
+ });
+}
diff --git a/apps/desktop/src/main/plugin-publisher/orchestrator.ts b/apps/desktop/src/main/plugin-publisher/orchestrator.ts
new file mode 100644
index 0000000000..eab17e09c4
--- /dev/null
+++ b/apps/desktop/src/main/plugin-publisher/orchestrator.ts
@@ -0,0 +1,557 @@
+/**
+ * Member-upload transfer table + orchestration.
+ *
+ * Keys are Host-minted transferIds, never MCP callIds. Pipeline:
+ * hash → prepare → PUT → commit → keep polling until a terminal upload
+ * status. Polling is a driver: GET during validating/publishing reschedules
+ * the server worker with a fresh Connection JWT.
+ */
+import { randomUUID } from 'node:crypto';
+import fs from 'node:fs';
+import fsPromises from 'node:fs/promises';
+import path from 'node:path';
+
+import {
+ PLUGIN_MEMBER_UPLOAD_MAX_ARCHIVE_BYTES,
+ type PluginMemberUploadStatusResponse,
+} from '@cindy/plugin-protocol';
+
+import { PluginPublisherApi, PluginPublisherApiError } from './api.js';
+import { hashLocalFile, PluginPublisherHashCancelledError } from './hashFile.js';
+import { PluginPublisherPutError, putLocalFile } from './putObject.js';
+import {
+ PLUGIN_PUBLISHER_MAX_CONCURRENT,
+ PLUGIN_PUBLISHER_POLL_INTERVAL_MS,
+ PLUGIN_PUBLISHER_POLL_MAX_TRANSIENT_RETRIES,
+ PLUGIN_PUBLISHER_POLL_TRANSIENT_BACKOFF_MS,
+ remainingPutBudgetMs,
+ type PluginPublisherProgress,
+ type PluginPublisherStage,
+ type PluginPublisherStartResult,
+} from './types.js';
+
+const TERMINAL_UPLOAD_STATUSES = new Set(['succeeded', 'failed', 'expired']);
+
+export interface PluginPublisherOrchestratorDeps {
+ api: PluginPublisherApi;
+ inspectPackage(filePath: string): Promise<{
+ ghostId: string;
+ name: string;
+ version: string;
+ }>;
+ confirm(facts: {
+ orgSlug: string;
+ orgName: string | null;
+ ghostId: string;
+ name: string;
+ version: string;
+ sizeBytes: number;
+ }): Promise<boolean>;
+ identity(): { membershipId: string; orgSlug: string; orgName: string | null } | null;
+ now?: () => number;
+ sleep?: (ms: number, signal: AbortSignal) => Promise<void>;
+ onProgress?: (progress: PluginPublisherProgress) => void;
+ putFile?: typeof putLocalFile;
+ inspectGate?: { acquire(signal: AbortSignal): Promise<void>; release(): void };
+}
+
+interface TransferRecord {
+ transferId: string;
+ uploadId: string | null;
+ filePath: string;
+ controller: AbortController;
+ progress: PluginPublisherProgress;
+ run: Promise<void>;
+}
+
+function defaultSleep(ms: number, signal: AbortSignal): Promise<void> {
+ return new Promise((resolve, reject) => {
+ if (signal.aborted) {
+ reject(Object.assign(new Error('aborted'), { name: 'AbortError' }));
+ return;
+ }
+ const timer = setTimeout(() => {
+ signal.removeEventListener('abort', onAbort);
+ resolve();
+ }, ms);
+ const onAbort = (): void => {
+ clearTimeout(timer);
+ reject(Object.assign(new Error('aborted'), { name: 'AbortError' }));
+ };
+ signal.addEventListener('abort', onAbort, { once: true });
+ });
+}
+
+function isPathSafeForPublish(filePath: string): boolean {
+ if (!path.isAbsolute(filePath)) return false;
+ if (filePath.includes('\0')) return false;
+ return path.extname(filePath).toLowerCase() === '.cindy';
+}
+
+class SerialGate {
+ private active = false;
+ private readonly waiters: Array<() => void> = [];
+
+ async acquire(signal: AbortSignal): Promise<void> {
+ if (!this.active) {
+ this.active = true;
+ return;
+ }
+ await new Promise<void>((resolve, reject) => {
+ const waiter = (): void => {
+ signal.removeEventListener('abort', onAbort);
+ this.active = true;
+ resolve();
+ };
+ const onAbort = (): void => {
+ const index = this.waiters.indexOf(waiter);
+ if (index >= 0) this.waiters.splice(index, 1);
+ reject(Object.assign(new Error('aborted'), { name: 'AbortError' }));
+ };
+ this.waiters.push(waiter);
+ signal.addEventListener('abort', onAbort, { once: true });
+ });
+ }
+
+ release(): void {
+ const next = this.waiters.shift();
+ if (next) next();
+ else this.active = false;
+ }
+}
+
+export class PluginPublisherOrchestrator {
+ private readonly transfers = new Map<string, TransferRecord>();
+ private activeCount = 0;
+ private readonly waiters: Array<() => void> = [];
+ private readonly now: () => number;
+ private readonly sleep: (ms: number, signal: AbortSignal) => Promise<void>;
+ private readonly inspectGate: { acquire(signal: AbortSignal): Promise<void>; release(): void };
+
+ constructor(private readonly deps: PluginPublisherOrchestratorDeps) {
+ this.now = deps.now ?? Date.now;
+ this.sleep = deps.sleep ?? defaultSleep;
+ this.inspectGate = deps.inspectGate ?? new SerialGate();
+ }
+
+ start(
+ filePath: string,
+ extras?: {
+ confirm?: PluginPublisherOrchestratorDeps['confirm'];
+ },
+ ): PluginPublisherStartResult {
+ const transferId = randomUUID();
+ const controller = new AbortController();
+ const progress: PluginPublisherProgress = {
+ transferId,
+ uploadId: null,
+ stage: 'confirming',
+ };
+ const record: TransferRecord = {
+ transferId,
+ uploadId: null,
+ filePath,
+ controller,
+ progress,
+ run: Promise.resolve(),
+ };
+ this.transfers.set(transferId, record);
+ record.run = this.run(record, extras?.confirm ?? this.deps.confirm).catch(() => undefined);
+ this.emit(record);
+ return { transferId, uploadId: null };
+ }
+
+ snapshot(transferId: string): PluginPublisherProgress | null {
+ return this.transfers.get(transferId)?.progress ?? null;
+ }
+
+ listActive(): PluginPublisherProgress[] {
+ return [...this.transfers.values()]
+ .map((record) => record.progress)
+ .filter((progress) => !isTerminalStage(progress.stage));
+ }
+
+ cancel(transferId: string): { cancelled: boolean } {
+ const record = this.transfers.get(transferId);
+ if (!record || isTerminalStage(record.progress.stage)) return { cancelled: false };
+ record.controller.abort();
+ return { cancelled: true };
+ }
+
+ abortAll(): void {
+ for (const record of this.transfers.values()) {
+ if (!isTerminalStage(record.progress.stage)) record.controller.abort();
+ }
+ }
+
+ private emit(record: TransferRecord): void {
+ this.deps.onProgress?.(record.progress);
+ }
+
+ private update(record: TransferRecord, patch: Partial<PluginPublisherProgress>): void {
+ record.progress = { ...record.progress, ...patch, transferId: record.transferId };
+ if (patch.uploadId) record.uploadId = patch.uploadId;
+ this.emit(record);
+ }
+
+ private async acquireSlot(signal: AbortSignal): Promise<void> {
+ if (this.activeCount < PLUGIN_PUBLISHER_MAX_CONCURRENT) {
+ this.activeCount += 1;
+ return;
+ }
+ await new Promise<void>((resolve, reject) => {
+ const waiter = (): void => {
+ signal.removeEventListener('abort', onAbort);
+ this.activeCount += 1;
+ resolve();
+ };
+ const onAbort = (): void => {
+ const index = this.waiters.indexOf(waiter);
+ if (index >= 0) this.waiters.splice(index, 1);
+ reject(Object.assign(new Error('aborted'), { name: 'AbortError' }));
+ };
+ this.waiters.push(waiter);
+ signal.addEventListener('abort', onAbort, { once: true });
+ });
+ }
+
+ private releaseSlot(): void {
+ this.activeCount = Math.max(0, this.activeCount - 1);
+ const next = this.waiters.shift();
+ next?.();
+ }
+
+ private async run(
+ record: TransferRecord,
+ confirm: PluginPublisherOrchestratorDeps['confirm'],
+ ): Promise<void> {
+ const signal = record.controller.signal;
+ let handle: fsPromises.FileHandle | null = null;
+ try {
+ if (!isPathSafeForPublish(record.filePath)) {
+ this.fail(record, 'INVALID_PARAMS', '只能发布 .cindy 插件包');
+ return;
+ }
+ const identity = this.deps.identity();
+ if (!identity) {
+ this.fail(record, 'NOT_ORG_MEMBER', '需要组织身份才能发布插件');
+ return;
+ }
+
+ await this.inspectGate.acquire(signal);
+ let inspected: { ghostId: string; name: string; version: string };
+ try {
+ inspected = await this.deps.inspectPackage(record.filePath);
+ } finally {
+ this.inspectGate.release();
+ }
+ handle = await fsPromises.open(record.filePath, fs.constants.O_RDONLY);
+ const stat = await handle.stat();
+ if (!stat.isFile()) {
+ this.fail(record, 'INVALID_PARAMS', '只能发布普通文件');
+ return;
+ }
+ if (stat.size <= 0 || stat.size > PLUGIN_MEMBER_UPLOAD_MAX_ARCHIVE_BYTES) {
+ this.fail(record, 'TOO_LARGE', '插件包超过 128 MiB');
+ return;
+ }
+
+ this.update(record, {
+ stage: 'confirming',
+ ghostId: inspected.ghostId,
+ version: inspected.version,
+ pluginName: inspected.name,
+ orgSlug: identity.orgSlug,
+ totalBytes: stat.size,
+ });
+ const confirmed = await confirm({
+ orgSlug: identity.orgSlug,
+ orgName: identity.orgName,
+ ghostId: inspected.ghostId,
+ name: inspected.name,
+ version: inspected.version,
+ sizeBytes: stat.size,
+ });
+ if (!confirmed || signal.aborted) {
+ this.update(record, {
+ stage: signal.aborted ? 'cancelled' : 'failed',
+ errorCode: signal.aborted ? null : 'CONFIRM_UNAVAILABLE',
+ message: signal.aborted
+ ? cancelMessage(record.uploadId !== null)
+ : '请在 Cindy 窗口内重试',
+ });
+ return;
+ }
+
+ await this.acquireSlot(signal);
+ try {
+ this.update(record, { stage: 'hashing', bytesHashed: 0, totalBytes: stat.size });
+ const digest = await hashLocalFile(handle, {
+ signal,
+ onProgress: ({ bytesRead, totalBytes }) => {
+ this.update(record, { stage: 'hashing', bytesHashed: bytesRead, totalBytes });
+ },
+ });
+ if (digest.sizeBytes !== stat.size) {
+ this.fail(record, 'UPLOAD_SIZE_MISMATCH', '文件在校验期间被修改,请重新选择');
+ return;
+ }
+
+ this.update(record, { stage: 'preparing', totalBytes: digest.sizeBytes });
+ const prepared = await this.deps.api.prepare({
+ sizeBytes: digest.sizeBytes,
+ sha256: digest.sha256,
+ });
+ this.update(record, { uploadId: prepared.uploadId, stage: 'uploading', bytesSent: 0 });
+
+ const putFile = this.deps.putFile ?? putLocalFile;
+ const openHandle = handle;
+ const putDeadlineMs = remainingPutBudgetMs(prepared.expiresAt, this.now());
+ const putOnce = () =>
+ putFile(openHandle, {
+ putUrl: prepared.putUrl,
+ headers: prepared.headers,
+ sizeBytes: digest.sizeBytes,
+ signal,
+ maxTotalMs: putDeadlineMs,
+ onBytes: (bytesSent) => {
+ this.update(record, { stage: 'uploading', bytesSent, totalBytes: digest.sizeBytes });
+ },
+ });
+ const putOutcome = await this.putWithRecovery(putOnce);
+ if (putOutcome === 'cancelled_incomplete' || putOutcome === 'cancelled_uncertain') {
+ this.update(record, {
+ stage: 'cancelled',
+ message:
+ putOutcome === 'cancelled_uncertain'
+ ? '已取消,上传结果不确定'
+ : '已取消发布',
+ });
+ return;
+ }
+ if (putOutcome === 'network_unreachable') {
+ this.fail(record, 'NETWORK_UNREACHABLE', '网络无法连接,可以重试');
+ return;
+ }
+
+ this.update(record, { stage: 'committing' });
+ const committed = await this.commitWithRetry(record, prepared.uploadId, signal);
+ if (committed === 'cancelled') return;
+ if (committed.status === 'expired') {
+ this.update(record, { stage: 'expired', status: 'expired', message: '上传会话已过期' });
+ return;
+ }
+ await this.pollUntilTerminal(record, prepared.uploadId, signal);
+ } finally {
+ this.releaseSlot();
+ }
+ } catch (error) {
+ if (signal.aborted || error instanceof PluginPublisherHashCancelledError) {
+ this.update(record, {
+ stage: 'cancelled',
+ message: cancelMessage(record.uploadId !== null && record.progress.stage !== 'uploading'),
+ });
+ return;
+ }
+ if (error instanceof PluginPublisherApiError) {
+ this.fail(record, error.code, mapPublisherApiMessage(error));
+ return;
+ }
+ this.fail(record, 'INTERNAL', '发布失败');
+ } finally {
+ await handle?.close().catch(() => undefined);
+ }
+ }
+
+ private async pollUntilTerminal(
+ record: TransferRecord,
+ uploadId: string,
+ signal: AbortSignal,
+ ): Promise<void> {
+ let transientRetries = 0;
+ while (!signal.aborted) {
+ try {
+ const status = await this.deps.api.status(uploadId);
+ transientRetries = 0;
+ this.applyStatus(record, status);
+ if (TERMINAL_UPLOAD_STATUSES.has(status.status)) return;
+ await this.sleep(PLUGIN_PUBLISHER_POLL_INTERVAL_MS, signal);
+ } catch (error) {
+ if (signal.aborted) break;
+ if (isTransientPublisherApiError(error)) {
+ transientRetries += 1;
+ if (transientRetries > PLUGIN_PUBLISHER_POLL_MAX_TRANSIENT_RETRIES) {
+ this.fail(record, 'SERVER_BUSY', '服务端繁忙,请稍后重试');
+ return;
+ }
+ this.update(record, {
+ stage: 'processing',
+ message: '服务端繁忙,重试中',
+ });
+ await this.sleep(
+ PLUGIN_PUBLISHER_POLL_TRANSIENT_BACKOFF_MS * transientRetries,
+ signal,
+ );
+ continue;
+ }
+ if (error instanceof PluginPublisherApiError && isTerminalPublisherClientError(error)) {
+ this.fail(record, error.code, mapPublisherApiMessage(error));
+ return;
+ }
+ throw error;
+ }
+ }
+ this.update(record, {
+ stage: 'cancelled',
+ message: '已停止跟踪,服务端仍在处理',
+ });
+ }
+
+ async refreshReviewStatus(transferId: string): Promise<PluginPublisherProgress | null> {
+ const record = this.transfers.get(transferId);
+ if (!record) return null;
+ if (record.progress.stage !== 'succeeded' || record.progress.reviewStatus !== 'pending') {
+ return record.progress;
+ }
+ const uploadId = record.uploadId;
+ if (!uploadId) return record.progress;
+ try {
+ const status = await this.deps.api.status(uploadId);
+ this.applyStatus(record, status);
+ } catch {
+ // Keep the last snapshot; the next status call can retry.
+ }
+ return record.progress;
+ }
+
+ private async commitWithRetry(
+ record: TransferRecord,
+ uploadId: string,
+ signal: AbortSignal,
+ ) {
+ let transientRetries = 0;
+ while (!signal.aborted) {
+ try {
+ return await this.deps.api.commit(uploadId);
+ } catch (error) {
+ if (isTransientPublisherApiError(error)) {
+ transientRetries += 1;
+ if (transientRetries > PLUGIN_PUBLISHER_POLL_MAX_TRANSIENT_RETRIES) {
+ this.fail(record, 'SERVER_BUSY', '服务端繁忙,请稍后重试');
+ return 'cancelled';
+ }
+ this.update(record, { stage: 'committing', message: '服务端繁忙,重试中' });
+ await this.sleep(
+ PLUGIN_PUBLISHER_POLL_TRANSIENT_BACKOFF_MS * transientRetries,
+ signal,
+ );
+ continue;
+ }
+ throw error;
+ }
+ }
+ this.update(record, {
+ stage: 'cancelled',
+ message: '已停止跟踪,服务端仍在处理',
+ });
+ return 'cancelled';
+ }
+
+ private async putWithRecovery(
+ putOnce: () => Promise<{ bytesSent: number }>,
+ ): Promise<
+ | 'ok'
+ | 'commit_same_upload'
+ | 'cancelled_incomplete'
+ | 'cancelled_uncertain'
+ | 'network_unreachable'
+ > {
+ let retried = false;
+ for (;;) {
+ try {
+ await putOnce();
+ return 'ok';
+ } catch (error) {
+ if (!(error instanceof PluginPublisherPutError)) throw error;
+ if (error.disposition === 'commit_same_upload') return 'commit_same_upload';
+ if (error.disposition === 'cancelled_incomplete' || error.disposition === 'cancelled_uncertain') {
+ return error.disposition;
+ }
+ if (error.disposition === 'retry_same_url' && !retried) {
+ retried = true;
+ continue;
+ }
+ return 'network_unreachable';
+ }
+ }
+ }
+
+ private applyStatus(record: TransferRecord, status: PluginMemberUploadStatusResponse): void {
+ const stage: PluginPublisherStage =
+ status.status === 'succeeded'
+ ? 'succeeded'
+ : status.status === 'failed'
+ ? 'failed'
+ : status.status === 'expired'
+ ? 'expired'
+ : 'processing';
+ this.update(record, {
+ uploadId: status.uploadId,
+ stage,
+ status: status.status,
+ reviewStatus: status.reviewStatus,
+ ghostId: status.ghostId,
+ version: status.version,
+ failure: status.failure,
+ errorCode: status.failure?.code ?? null,
+ message: status.failure?.message ?? (status.status === 'expired' ? '上传会话已过期' : null),
+ });
+ }
+
+ private fail(record: TransferRecord, errorCode: string, message: string): void {
+ this.update(record, { stage: 'failed', errorCode, message });
+ }
+}
+
+function cancelMessage(commitAlreadySent: boolean): string {
+ return commitAlreadySent ? '已停止跟踪,服务端仍在处理' : '已取消发布';
+}
+
+function isTerminalStage(stage: PluginPublisherStage): boolean {
+ return (
+ stage === 'succeeded' ||
+ stage === 'failed' ||
+ stage === 'expired' ||
+ stage === 'cancelled'
+ );
+}
+
+function isTransientPublisherApiError(error: unknown): boolean {
+ if (!(error instanceof PluginPublisherApiError)) return false;
+ if (error.status >= 500) return true;
+ return (
+ error.code === 'RATE_LIMIT_UNAVAILABLE' ||
+ error.code === 'STORAGE_UNAVAILABLE' ||
+ error.code === 'AUTH_CONTEXT_UNAVAILABLE'
+ );
+}
+
+function isTerminalPublisherClientError(error: PluginPublisherApiError): boolean {
+ return error.status === 403 || error.status === 404;
+}
+
+function mapPublisherApiMessage(error: PluginPublisherApiError): string {
+ if (error.status === 403 && error.code === 'FORBIDDEN') {
+ return '本企业未开启成员发布,请联系管理员';
+ }
+ if (error.code === 'MEMBERSHIP_INACTIVE') return '当前成员身份已不可用,请联系管理员';
+ if (error.code === 'RATE_LIMITED') return '发布次数过多,请稍后再试';
+ if (error.status === 403 || error.status === 404) return '找不到这次发布或无权查看';
+ return '发布请求失败';
+}
+
+export function createPluginPublisherOrchestrator(
+ deps: PluginPublisherOrchestratorDeps,
+): PluginPublisherOrchestrator {
+ return new PluginPublisherOrchestrator(deps);
+}
diff --git a/apps/desktop/src/main/plugin-publisher/putObject.ts b/apps/desktop/src/main/plugin-publisher/putObject.ts
new file mode 100644
index 0000000000..6c60aae9d5
--- /dev/null
+++ b/apps/desktop/src/main/plugin-publisher/putObject.ts
@@ -0,0 +1,206 @@
+/**
+ * Streaming raw PUT of a local file to a trusted pre-signed URL.
+ *
+ * Must carry the two signed headers exactly as issued. Content-Length is not
+ * signed and must be set precisely. Do not use outboundFetch: its proxy path
+ * buffers the whole body. 3xx is rejected because a consumed stream cannot
+ * be replayed by following Location. 3xx is refused (`maxRedirections: 0`)
+ * and treated as retry_same_url because the PUT did not execute a write.
+ *
+ * `bytesSent` is bytes queued into the Transform, not bytes acknowledged by
+ * OSS. That bias is conservative: abort after enqueue may commit and then
+ * see UPLOAD_OBJECT_MISSING, never overwrite or double-publish.
+ */
+import type { FileHandle } from 'node:fs/promises';
+import { Transform, type Readable } from 'node:stream';
+import { request, type Dispatcher } from 'undici';
+
+import { resolveOutboundDispatcher } from '../maker-host/outbound-fetch.js';
+import { PLUGIN_PUBLISHER_UPLOAD_TTL_MS } from './types.js';
+
+export const PLUGIN_PUBLISHER_PUT_STALL_TIMEOUT_MS = 60_000;
+export const PLUGIN_PUBLISHER_PUT_MAX_TOTAL_MS = PLUGIN_PUBLISHER_UPLOAD_TTL_MS;
+export const PLUGIN_PUBLISHER_PUT_HIGH_WATER_MARK = 64 * 1024;
+
+export type PluginPublisherPutDisposition =
+ | 'retry_same_url'
+ | 'commit_same_upload'
+ | 'cancelled_incomplete'
+ | 'cancelled_uncertain';
+
+export class PluginPublisherPutError extends Error {
+ constructor(
+ message: string,
+ readonly disposition: PluginPublisherPutDisposition,
+ readonly status = 0,
+ ) {
+ super(message);
+ this.name = 'PluginPublisherPutError';
+ }
+}
+
+export interface PutRequestResponse {
+ statusCode: number;
+ body: { dump(): Promise<unknown> };
+}
+
+export interface PutRequestInit {
+ method: 'PUT';
+ body: Readable;
+ headers: Record<string, string>;
+ signal?: AbortSignal;
+ dispatcher?: Dispatcher;
+}
+
+export interface PutLocalFileOptions {
+ putUrl: string;
+ headers: Record<string, string>;
+ sizeBytes: number;
+ signal?: AbortSignal;
+ stallTimeoutMs?: number;
+ maxTotalMs?: number;
+ onBytes?: (bytesSent: number) => void;
+ now?: () => number;
+ requestImpl?: (url: string, init: PutRequestInit) => Promise<PutRequestResponse>;
+ resolveDispatcher?: (url: string, opts: { signal?: AbortSignal }) => Promise<Dispatcher | undefined>;
+}
+
+function classifyNetworkFailure(error: unknown): PluginPublisherPutDisposition {
+ const text = error instanceof Error ? `${error.name} ${error.message}` : String(error);
+ if (/ENOTFOUND|EAI_AGAIN|CERT_|ERR_TLS|UNABLE_TO_VERIFY|ERR_INVALID_URL|TypeError/i.test(text)) {
+ return 'retry_same_url';
+ }
+ return 'commit_same_upload';
+}
+
+export async function putLocalFile(
+ handle: FileHandle,
+ options: PutLocalFileOptions,
+): Promise<{ bytesSent: number }> {
+ const stallTimeoutMs = options.stallTimeoutMs ?? PLUGIN_PUBLISHER_PUT_STALL_TIMEOUT_MS;
+ const maxTotalMs = options.maxTotalMs ?? PLUGIN_PUBLISHER_PUT_MAX_TOTAL_MS;
+ const now = options.now ?? Date.now;
+ const startedAt = now();
+ let lastProgressAt = startedAt;
+ let bytesSent = 0;
+ let settled = false;
+
+ const throwIfAborted = (uncertain: boolean): void => {
+ if (!options.signal?.aborted) return;
+ throw new PluginPublisherPutError(
+ 'Plugin package upload was cancelled',
+ uncertain ? 'cancelled_uncertain' : 'cancelled_incomplete',
+ );
+ };
+
+ throwIfAborted(false);
+
+ const stream = handle.createReadStream({
+ autoClose: false,
+ start: 0,
+ highWaterMark: PLUGIN_PUBLISHER_PUT_HIGH_WATER_MARK,
+ });
+ const counting = new Transform({
+ highWaterMark: PLUGIN_PUBLISHER_PUT_HIGH_WATER_MARK,
+ transform(chunk: Buffer, _enc, cb) {
+ bytesSent += chunk.length;
+ lastProgressAt = now();
+ options.onBytes?.(bytesSent);
+ cb(null, chunk);
+ },
+ });
+ stream.on('error', (err) => counting.destroy(err));
+ const body = stream.pipe(counting);
+
+ const abortController = new AbortController();
+ const onOuterAbort = (): void => abortController.abort();
+ options.signal?.addEventListener('abort', onOuterAbort, { once: true });
+
+ const stallTimer = setInterval(() => {
+ if (settled) return;
+ const t = now();
+ if (t - lastProgressAt >= stallTimeoutMs || t - startedAt >= maxTotalMs) {
+ abortController.abort();
+ }
+ }, 1_000);
+
+ try {
+ const dispatcher = await (options.resolveDispatcher ?? resolveOutboundDispatcher)(options.putUrl, {
+ signal: abortController.signal,
+ });
+ throwIfAborted(false);
+ const requestImpl =
+ options.requestImpl ??
+ ((url, init) =>
+ request(url, {
+ ...init,
+ // Streamed bodies cannot be replayed; refuse OSS 3xx instead of following.
+ maxRedirections: 0,
+ } as Parameters<typeof request>[1]));
+ const response = await requestImpl(options.putUrl, {
+ method: 'PUT',
+ body,
+ headers: {
+ ...options.headers,
+ 'content-length': String(options.sizeBytes),
+ },
+ signal: abortController.signal,
+ ...(dispatcher ? { dispatcher } : {}),
+ });
+ settled = true;
+ const status = response.statusCode;
+ await response.body.dump().catch(() => undefined);
+
+ if (status >= 300 && status < 400) {
+ throw new PluginPublisherPutError(
+ 'Pre-signed upload redirected; streamed PUT does not follow redirects',
+ 'retry_same_url',
+ status,
+ );
+ }
+ if (status === 409) {
+ // x-oss-forbid-overwrite hit: the object is already there. Commit.
+ return { bytesSent: options.sizeBytes };
+ }
+ if (status === 200) return { bytesSent };
+ if (status >= 500) {
+ throw new PluginPublisherPutError(
+ `Pre-signed upload returned ${status}`,
+ 'commit_same_upload',
+ status,
+ );
+ }
+ throw new PluginPublisherPutError(
+ `Pre-signed upload returned ${status}`,
+ 'retry_same_url',
+ status,
+ );
+ } catch (error) {
+ settled = true;
+ if (error instanceof PluginPublisherPutError) throw error;
+ if (options.signal?.aborted) {
+ throw new PluginPublisherPutError(
+ 'Plugin package upload was cancelled',
+ bytesSent > 0 ? 'cancelled_uncertain' : 'cancelled_incomplete',
+ );
+ }
+ if (abortController.signal.aborted) {
+ throw new PluginPublisherPutError(
+ bytesSent > 0
+ ? 'Plugin package upload stalled or exceeded the session window'
+ : 'Plugin package upload stalled before any bytes were sent',
+ bytesSent > 0 ? 'commit_same_upload' : 'retry_same_url',
+ );
+ }
+ throw new PluginPublisherPutError(
+ error instanceof Error ? error.message : String(error),
+ classifyNetworkFailure(error),
+ );
+ } finally {
+ settled = true;
+ clearInterval(stallTimer);
+ options.signal?.removeEventListener('abort', onOuterAbort);
+ stream.destroy();
+ counting.destroy();
+ }
+}
diff --git a/apps/desktop/src/main/plugin-publisher/registerIpc.ts b/apps/desktop/src/main/plugin-publisher/registerIpc.ts
new file mode 100644
index 0000000000..ef5371b5da
--- /dev/null
+++ b/apps/desktop/src/main/plugin-publisher/registerIpc.ts
@@ -0,0 +1,107 @@
+import { ipcMain } from 'electron';
+
+import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';
+import { requireObject, requireString, throwIpcError } from '../utils/ipcValidate.js';
+import { PluginPublisherApi, PluginPublisherApiError } from './api.js';
+import {
+ currentPublisherIdentity,
+ getPluginPublisherConfirmBridge,
+ getPluginPublisherOrchestrator,
+ publisherAudience,
+ startPluginPublish,
+ trackPublisherConfirmRequester,
+} from './host.js';
+import { getConnectionTokenProvider } from '../cindy-brain/index.js';
+
+let registered = false;
+
+function publisherApi(): PluginPublisherApi {
+ return new PluginPublisherApi({
+ async getToken() {
+ const identity = currentPublisherIdentity();
+ if (!identity) throwIpcError('PERMISSION_DENIED', '需要组织身份才能查看发布');
+ return getConnectionTokenProvider().getToken({
+ membershipId: identity.membershipId,
+ audience: publisherAudience(identity.orgSlug),
+ });
+ },
+ invalidateToken() {
+ const identity = currentPublisherIdentity();
+ if (!identity) return;
+ getConnectionTokenProvider().invalidate({
+ membershipId: identity.membershipId,
+ audience: publisherAudience(identity.orgSlug),
+ });
+ },
+ });
+}
+
+function mapListError(error: unknown): never {
+ if (error instanceof PluginPublisherApiError) {
+ if (error.status === 403 && error.code === 'FORBIDDEN') {
+ throwIpcError('PERMISSION_DENIED', '本企业未开启成员发布,请联系管理员');
+ }
+ throwIpcError('INTERNAL', error.message || '发布列表加载失败');
+ }
+ throwIpcError('INTERNAL', '发布列表加载失败');
+}
+
+export function registerPluginPublisherIpc(): void {
+ if (registered) return;
+ registered = true;
+
+ ipcMain.handle('plugin-publisher:start', async (event, filePath: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ if (typeof filePath !== 'string' || filePath.trim().length === 0) {
+ throwIpcError('INVALID_PARAMS', 'filePath must be a non-empty string');
+ }
+ if (!currentPublisherIdentity()) {
+ throwIpcError('PERMISSION_DENIED', '需要组织身份才能发布插件');
+ }
+ trackPublisherConfirmRequester(event.sender);
+ return startPluginPublish(filePath, event.sender);
+ });
+
+ ipcMain.handle('plugin-publisher:status', (event, transferId: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ const id = requireString(transferId, 'transferId');
+ return { progress: getPluginPublisherOrchestrator().snapshot(id) };
+ });
+
+ ipcMain.handle('plugin-publisher:cancel', (event, transferId: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ const id = requireString(transferId, 'transferId');
+ return getPluginPublisherOrchestrator().cancel(id);
+ });
+
+ ipcMain.handle('plugin-publisher:list-mine', async (event, raw: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ if (!currentPublisherIdentity()) {
+ throwIpcError('PERMISSION_DENIED', '需要组织身份才能查看发布');
+ }
+ const cursor =
+ raw && typeof raw === 'object' && typeof (raw as { cursor?: unknown }).cursor === 'string'
+ ? (raw as { cursor: string }).cursor
+ : undefined;
+ try {
+ return await publisherApi().listMine(cursor);
+ } catch (error) {
+ mapListError(error);
+ }
+ });
+
+ ipcMain.handle('plugin-publisher:resolve-confirm', (event, raw: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ trackPublisherConfirmRequester(event.sender);
+ const payload = requireObject(raw);
+ const requestId = requireString(payload.requestId, 'requestId');
+ if (requestId.length > 128) throwIpcError('INVALID_PARAMS', 'requestId is too long');
+ return {
+ handled: getPluginPublisherConfirmBridge().resolve(
+ event.sender.id,
+ requestId,
+ payload.confirmed,
+ ),
+ };
+ });
+}
diff --git a/apps/desktop/src/main/plugin-publisher/types.ts b/apps/desktop/src/main/plugin-publisher/types.ts
new file mode 100644
index 0000000000..deabe1692c
--- /dev/null
+++ b/apps/desktop/src/main/plugin-publisher/types.ts
@@ -0,0 +1,67 @@
+import type {
+ PluginMemberReleaseReviewStatus,
+ PluginMemberUploadFailure,
+ PluginMemberUploadStatus,
+} from '@cindy/plugin-protocol';
+
+export const PLUGIN_MEMBER_PUBLISHER_GHOST_ID = 'cindy-publisher';
+
+export type PluginPublisherStage =
+ | 'confirming'
+ | 'hashing'
+ | 'preparing'
+ | 'uploading'
+ | 'committing'
+ | 'processing'
+ | 'succeeded'
+ | 'failed'
+ | 'expired'
+ | 'cancelled';
+
+export interface PluginPublisherProgress {
+ transferId: string;
+ uploadId: string | null;
+ stage: PluginPublisherStage;
+ bytesHashed?: number;
+ bytesSent?: number;
+ totalBytes?: number;
+ status?: PluginMemberUploadStatus;
+ reviewStatus?: PluginMemberReleaseReviewStatus | null;
+ ghostId?: string | null;
+ version?: string | null;
+ pluginName?: string | null;
+ orgSlug?: string | null;
+ failure?: PluginMemberUploadFailure | null;
+ errorCode?: string | null;
+ message?: string | null;
+}
+
+export interface PluginPublisherConfirmFacts {
+ orgSlug: string;
+ orgName: string | null;
+ ghostId: string;
+ name: string;
+ version: string;
+ sizeBytes: number;
+}
+
+export interface PluginPublisherStartResult {
+ transferId: string;
+ uploadId: string | null;
+}
+
+export const PLUGIN_PUBLISHER_POLL_INTERVAL_MS = 2_500;
+export const PLUGIN_PUBLISHER_MAX_CONCURRENT = 2;
+export const PLUGIN_PUBLISHER_UPLOAD_TTL_MS = 60 * 60_000;
+/** Leave this much of the session TTL for commit after PUT. */
+export const PLUGIN_PUBLISHER_COMMIT_MARGIN_MS = 90_000;
+export const PLUGIN_PUBLISHER_POLL_MAX_TRANSIENT_RETRIES = 8;
+export const PLUGIN_PUBLISHER_POLL_TRANSIENT_BACKOFF_MS = 2_000;
+
+export function remainingPutBudgetMs(expiresAt: string, now: number): number {
+ const expiresAtMs = Date.parse(expiresAt);
+ const remaining = Number.isFinite(expiresAtMs)
+ ? expiresAtMs - now - PLUGIN_PUBLISHER_COMMIT_MARGIN_MS
+ : PLUGIN_PUBLISHER_UPLOAD_TTL_MS - PLUGIN_PUBLISHER_COMMIT_MARGIN_MS;
+ return Math.max(1_000, remaining);
+}
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index c59a755973..afa37ee8f6 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -575,6 +575,8 @@ const fanOutLayoutChanged = createIpcFanOut('layout:changed');
// 意识仓库变化广播 (install/uninstall 后 main 推全量已装清单,多窗口热更新;
// 见 main/cindy-brain/index.ts)。
const fanOutGhostsChanged = createIpcFanOut('ghosts:changed');
+const fanOutPluginPublisherProgress = createIpcFanOut('plugin-publisher:progress');
+const fanOutPluginPublisherConfirm = createIpcFanOut('plugin-publisher:confirm');
const fanOutGhostSetupNavigate = createIpcFanOut('maker:plugin-setup:navigate');
// Plugin 顶部已安装快捷行的最近使用顺序,多窗口同步。
const fanOutGhostRecentUsageChanged = createIpcFanOut('ghosts:recent-usage-changed');
@@ -1403,6 +1405,20 @@ contextBridge.exposeInMainWorld('electronAPI', {
gitPreflight: (): Promise<{ ok: boolean; version: string | null }> =>
ipcRenderer.invoke('plugin-market:git-preflight'),
},
+ pluginPublisher: {
+ start: (filePath: string): Promise<{ transferId: string; uploadId: string | null }> =>
+ ipcRenderer.invoke('plugin-publisher:start', filePath),
+ status: (transferId: string): Promise<{ progress: unknown }> =>
+ ipcRenderer.invoke('plugin-publisher:status', transferId),
+ cancel: (transferId: string): Promise<{ cancelled: boolean }> =>
+ ipcRenderer.invoke('plugin-publisher:cancel', transferId),
+ listMine: (cursor?: string): Promise<{ releases: unknown[]; nextCursor: string | null }> =>
+ ipcRenderer.invoke('plugin-publisher:list-mine', cursor ? { cursor } : {}),
+ onProgress: fanOutPluginPublisherProgress,
+ onConfirm: fanOutPluginPublisherConfirm,
+ resolveConfirm: (requestId: string, confirmed: boolean): Promise<{ handled: boolean }> =>
+ ipcRenderer.invoke('plugin-publisher:resolve-confirm', { requestId, confirmed }),
+ },
voiceInput: {
prewarm: (payload?: {
sourceLanguage?: string;
diff --git a/apps/desktop/src/renderer/App.tsx b/apps/desktop/src/renderer/App.tsx
index 1c243bbc0e..8e9ad311c8 100644
--- a/apps/desktop/src/renderer/App.tsx
+++ b/apps/desktop/src/renderer/App.tsx
@@ -28,6 +28,7 @@ import { FindInPageBar } from '@/components/find-in-page/FindInPageBar';
import { ProjectAutomationNotifyBridge } from '@/features/scheduler/components/ProjectAutomationNotifyBridge';
import { GhostConfirmDialogHost } from '@/cindy-brain/GhostConfirmDialogHost';
import { PluginMarketPermissionReviewHost } from '@/features/plugin/PluginMarketPermissionReviewHost';
+import { PluginPublisherConfirmHost } from '@/features/plugin/PluginPublisherConfirmHost';
import { makerChatStore } from '@/lib/makerChatStore';
import {
initializePromptRecommendationStore,
@@ -373,6 +374,7 @@ export function App() {
都挂、谁收到谁弹,不按窗口类型 gate。 */}
<GhostConfirmDialogHost />
<PluginMarketPermissionReviewHost />
+ <PluginPublisherConfirmHost />
<OwnerScopedRouter />
</EnvCheckGuard>
</LoginHandoffHost>
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
index 63c6a5f076..7a3c7c0b4d 100644
--- a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
@@ -106,6 +106,7 @@ import {
sortInstalledForDisplay,
type GhostPluginListItem,
} from './lib/ghostPluginViewModel';
+import { MyPublishesSection } from './MyPublishesSection';
import { ignoredRoundStorageKey, isBatchFinished, updateRoundKey } from './lib/updateAllModel';
import {
approveUpdateExpansion,
@@ -997,6 +998,21 @@ export function GhostPluginPage({
setUpdateDialogOpen(true);
}, [updatableInstalledItems]);
+ const handlePublish = useCallback(async () => {
+ const picked = await window.electronAPI.ghosts.pickFile().catch(() => null);
+ if (!picked || 'canceled' in picked) return;
+ try {
+ await window.electronAPI.pluginPublisher.start(picked.filePath);
+ } catch (error) {
+ const decoded = extractIpcError(error);
+ toast.error(
+ decoded?.code === 'PERMISSION_DENIED'
+ ? t('settings.ghosts.publish.disabled')
+ : t('settings.ghosts.publish.startFailed'),
+ );
+ }
+ }, [t]);
+
const handleInstall = useCallback(async () => {
const picked = await window.electronAPI.ghosts.pickFile().catch(() => null);
if (!picked || 'canceled' in picked) return;
@@ -1667,6 +1683,8 @@ export function GhostPluginPage({
) : null}
</section>
+ <MyPublishesSection enabled={showEnterprise} onPublish={() => void handlePublish()} />
+
{availableMarketItems.length > 0 ||
searchedAvailableMarketItems.length > 0 ||
marketSnapshot?.unavailableReason ||
diff --git a/apps/desktop/src/renderer/features/plugin/MyPublishesSection.tsx b/apps/desktop/src/renderer/features/plugin/MyPublishesSection.tsx
new file mode 100644
index 0000000000..eaa4e395e0
--- /dev/null
+++ b/apps/desktop/src/renderer/features/plugin/MyPublishesSection.tsx
@@ -0,0 +1,215 @@
+import { useCallback, useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { extractIpcError } from '@/utils/ipcError';
+import { cn } from '@/lib/utils';
+
+interface ReleaseRow {
+ uploadId: string;
+ status: string;
+ reviewStatus: string | null;
+ ghostId: string | null;
+ version: string | null;
+ createdAt?: string;
+ updatedAt?: string;
+ failure?: { code: string; message: string } | null;
+}
+
+interface TransferProgress {
+ transferId: string;
+ uploadId: string | null;
+ stage: string;
+ bytesHashed?: number;
+ bytesSent?: number;
+ totalBytes?: number;
+ status?: string;
+ reviewStatus?: string | null;
+ ghostId?: string | null;
+ version?: string | null;
+ pluginName?: string | null;
+ message?: string | null;
+}
+
+function isProgress(value: unknown): value is TransferProgress {
+ return Boolean(value && typeof value === 'object' && typeof (value as { transferId?: unknown }).transferId === 'string');
+}
+
+function badgeKey(status: string, reviewStatus: string | null): string {
+ if (status === 'validating' || status === 'publishing') return 'validating';
+ if (status === 'succeeded' && reviewStatus === 'pending') return 'pending';
+ if (status === 'succeeded' && reviewStatus === 'approved') return 'approved';
+ if (status === 'succeeded' && reviewStatus === 'rejected') return 'rejected';
+ if (status === 'failed') return 'failed';
+ if (status === 'expired') return 'expired';
+ return 'processing';
+}
+
+export function MyPublishesSection({
+ enabled,
+ onPublish,
+}: {
+ enabled: boolean;
+ onPublish: () => void;
+}) {
+ const { t } = useTranslation();
+ const [expanded, setExpanded] = useState(true);
+ const [releases, setReleases] = useState<ReleaseRow[]>([]);
+ const [disabledReason, setDisabledReason] = useState<string | null>(null);
+ const [active, setActive] = useState<TransferProgress | null>(null);
+
+ const refresh = useCallback(async () => {
+ if (!enabled) return;
+ try {
+ const page = await window.electronAPI.pluginPublisher.listMine();
+ setDisabledReason(null);
+ setReleases(
+ page.releases.map((raw) => ({
+ uploadId: String(raw.uploadId ?? ''),
+ status: String(raw.status ?? ''),
+ reviewStatus: typeof raw.reviewStatus === 'string' ? raw.reviewStatus : null,
+ ghostId: typeof raw.ghostId === 'string' ? raw.ghostId : null,
+ version: typeof raw.version === 'string' ? raw.version : null,
+ createdAt: typeof raw.createdAt === 'string' ? raw.createdAt : undefined,
+ updatedAt: typeof raw.updatedAt === 'string' ? raw.updatedAt : undefined,
+ failure:
+ raw.failure && typeof raw.failure === 'object'
+ ? {
+ code: String((raw.failure as { code?: unknown }).code ?? ''),
+ message: String((raw.failure as { message?: unknown }).message ?? ''),
+ }
+ : null,
+ })),
+ );
+ } catch (error) {
+ const decoded = extractIpcError(error);
+ if (decoded?.code === 'PERMISSION_DENIED') {
+ setDisabledReason(t('settings.ghosts.publish.disabled'));
+ setReleases([]);
+ return;
+ }
+ setDisabledReason(t('settings.ghosts.publish.loadFailed'));
+ }
+ }, [enabled, t]);
+
+ useEffect(() => {
+ void refresh();
+ }, [refresh]);
+
+ useEffect(() => {
+ if (!enabled) return;
+ const timer = window.setInterval(() => {
+ void refresh();
+ }, 8_000);
+ return () => window.clearInterval(timer);
+ }, [enabled, refresh]);
+
+ useEffect(() => {
+ return window.electronAPI.pluginPublisher.onProgress((raw) => {
+ if (!isProgress(raw)) return;
+ setActive(raw.stage === 'succeeded' || raw.stage === 'failed' || raw.stage === 'expired' || raw.stage === 'cancelled' ? null : raw);
+ if (raw.stage === 'succeeded' || raw.stage === 'failed' || raw.stage === 'expired') {
+ void refresh();
+ }
+ });
+ }, [refresh]);
+
+ if (!enabled) return null;
+
+ const percent =
+ active?.totalBytes && active.totalBytes > 0
+ ? Math.min(100, Math.round(((active.bytesSent ?? active.bytesHashed ?? 0) / active.totalBytes) * 100))
+ : null;
+
+ return (
+ <section className="plugin-motion-page-section mt-10 min-w-0">
+ <div className="mb-4 flex items-center justify-between gap-3">
+ <button
+ type="button"
+ onClick={() => setExpanded((value) => !value)}
+ className="flex min-w-0 items-baseline gap-2 text-left"
+ >
+ <h2 className="text-20 font-medium text-[var(--text-primary)]">
+ {t('settings.ghosts.publish.section')}
+ </h2>
+ <span className="text-13 tabular-nums text-[var(--text-tertiary)]">{releases.length}</span>
+ </button>
+ <button
+ type="button"
+ onClick={onPublish}
+ className="inline-flex h-9 shrink-0 items-center rounded-full border border-[var(--border-default)] bg-[var(--surface-elevated)] px-4 text-12 font-medium text-[var(--text-primary)] transition-colors hover:bg-[var(--surface-hover-soft)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
+ >
+ {t('settings.ghosts.publish.action')}
+ </button>
+ </div>
+ {expanded ? (
+ <div className="space-y-2">
+ {disabledReason ? (
+ <p className="rounded-xl border border-[var(--border-default)] bg-[var(--surface-chip)] px-4 py-3 text-12 text-[var(--text-secondary)]">
+ {disabledReason}
+ </p>
+ ) : null}
+ {active ? (
+ <div className="flex items-center justify-between gap-3 rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-4 py-3">
+ <div className="min-w-0">
+ <p className="truncate text-13 font-medium text-[var(--text-primary)]">
+ {active.pluginName ?? active.ghostId ?? t('settings.ghosts.publish.uploading')}
+ </p>
+ <p className="text-12 text-[var(--text-secondary)]">
+ {t(`settings.ghosts.publish.stage.${active.stage}`)}
+ {percent !== null ? ` · ${percent}%` : ''}
+ </p>
+ </div>
+ <button
+ type="button"
+ onClick={() => void window.electronAPI.pluginPublisher.cancel(active.transferId)}
+ className="shrink-0 rounded-full px-3 py-1 text-12 text-[var(--text-secondary)] hover:bg-[var(--surface-hover-soft)]"
+ >
+ {t('settings.ghosts.publish.cancel')}
+ </button>
+ </div>
+ ) : null}
+ {releases.map((release) => {
+ const key = badgeKey(release.status, release.reviewStatus);
+ return (
+ <div
+ key={release.uploadId}
+ className="flex items-center justify-between gap-3 rounded-xl border-[0.5px] border-[var(--border-default)] bg-[var(--surface-elevated)] px-4 py-3"
+ >
+ <div className="min-w-0">
+ <p className="truncate text-13 font-medium text-[var(--text-primary)]">
+ {release.ghostId ?? t('settings.ghosts.publish.unknownPlugin')}
+ {release.version ? ` · ${release.version}` : ''}
+ </p>
+ {release.failure?.message ? (
+ <p className="truncate text-12 text-[var(--text-secondary)]">{release.failure.message}</p>
+ ) : (
+ <p className="text-12 text-[var(--text-tertiary)]">
+ {release.updatedAt ?? release.createdAt ?? ''}
+ </p>
+ )}
+ </div>
+ <span
+ className={cn(
+ 'shrink-0 rounded-full px-2.5 py-1 text-11',
+ key === 'approved'
+ ? 'bg-[var(--success-soft)] text-[var(--success)]'
+ : key === 'failed' || key === 'rejected' || key === 'expired'
+ ? 'bg-[var(--danger-soft)] text-[var(--danger)]'
+ : 'bg-[var(--surface-chip)] text-[var(--text-secondary)]',
+ )}
+ >
+ {t(`settings.ghosts.publish.badge.${key}`)}
+ </span>
+ </div>
+ );
+ })}
+ {!disabledReason && releases.length === 0 && !active ? (
+ <p className="rounded-xl border-[0.5px] border-[var(--border-default)] px-5 py-8 text-center text-13 text-[var(--text-secondary)]">
+ {t('settings.ghosts.publish.empty')}
+ </p>
+ ) : null}
+ </div>
+ ) : null}
+ </section>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/plugin/PluginPublisherConfirmHost.tsx b/apps/desktop/src/renderer/features/plugin/PluginPublisherConfirmHost.tsx
new file mode 100644
index 0000000000..915abf00b4
--- /dev/null
+++ b/apps/desktop/src/renderer/features/plugin/PluginPublisherConfirmHost.tsx
@@ -0,0 +1,112 @@
+import { useEffect } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
+import { isDataOwnerPushStampCurrent } from '@/contexts/dataOwnerGeneration';
+
+interface ConfirmFacts {
+ orgSlug: string;
+ orgName: string | null;
+ ghostId: string;
+ name: string;
+ version: string;
+ sizeBytes: number;
+}
+
+interface ConfirmRequest {
+ requestId: string;
+ ownerStamp: { dataOwnerId: string; ownerGeneration: number };
+ facts: ConfirmFacts;
+}
+
+function isConfirmRequest(value: unknown): value is ConfirmRequest {
+ if (!value || typeof value !== 'object') return false;
+ const raw = value as Record<string, unknown>;
+ if (typeof raw.requestId !== 'string') return false;
+ if (!raw.ownerStamp || typeof raw.ownerStamp !== 'object') return false;
+ if (!raw.facts || typeof raw.facts !== 'object') return false;
+ const facts = raw.facts as Record<string, unknown>;
+ return (
+ typeof facts.orgSlug === 'string' &&
+ typeof facts.ghostId === 'string' &&
+ typeof facts.name === 'string' &&
+ typeof facts.version === 'string' &&
+ typeof facts.sizeBytes === 'number'
+ );
+}
+
+function formatBytes(sizeBytes: number): string {
+ if (sizeBytes < 1024) return `${sizeBytes} B`;
+ if (sizeBytes < 1024 * 1024) return `${(sizeBytes / 1024).toFixed(1)} KB`;
+ return `${(sizeBytes / (1024 * 1024)).toFixed(1)} MB`;
+}
+
+export function PluginPublisherConfirmHost() {
+ const { t } = useTranslation();
+ const { confirm } = useConfirmDialog();
+
+ useEffect(() => {
+ return window.electronAPI.pluginPublisher.onConfirm((raw) => {
+ if (!isConfirmRequest(raw)) return;
+ void (async () => {
+ let confirmed = false;
+ let unsubscribeAuth: () => void = () => undefined;
+ try {
+ if (!isDataOwnerPushStampCurrent(raw.ownerStamp)) return;
+ const abort = new AbortController();
+ unsubscribeAuth = window.electronAPI.onAuthStateChange((state) => {
+ if (
+ state.dataOwnerId !== raw.ownerStamp.dataOwnerId ||
+ state.ownerGeneration !== raw.ownerStamp.ownerGeneration
+ ) {
+ abort.abort();
+ }
+ });
+ if (!isDataOwnerPushStampCurrent(raw.ownerStamp)) abort.abort();
+ confirmed = await confirm(
+ {
+ title: t('settings.ghosts.publish.confirmTitle', { name: raw.facts.name }),
+ description: t('settings.ghosts.publish.confirmDescription'),
+ content: (
+ <dl className="space-y-2 text-13 text-[var(--text-secondary)]">
+ <div className="flex justify-between gap-4">
+ <dt>{t('settings.ghosts.publish.org')}</dt>
+ <dd className="text-[var(--text-primary)]">
+ {raw.facts.orgName ?? raw.facts.orgSlug}
+ </dd>
+ </div>
+ <div className="flex justify-between gap-4">
+ <dt>{t('settings.ghosts.publish.pluginId')}</dt>
+ <dd className="text-[var(--text-primary)]">{raw.facts.ghostId}</dd>
+ </div>
+ <div className="flex justify-between gap-4">
+ <dt>{t('settings.ghosts.publish.version')}</dt>
+ <dd className="text-[var(--text-primary)]">{raw.facts.version}</dd>
+ </div>
+ <div className="flex justify-between gap-4">
+ <dt>{t('settings.ghosts.publish.size')}</dt>
+ <dd className="text-[var(--text-primary)]">{formatBytes(raw.facts.sizeBytes)}</dd>
+ </div>
+ </dl>
+ ),
+ maxWidth: 480,
+ confirmText: t('settings.ghosts.publish.confirm'),
+ cancelText: t('settings.ghosts.publish.cancel'),
+ autoFocusConfirm: true,
+ },
+ abort.signal,
+ );
+ } finally {
+ unsubscribeAuth();
+ try {
+ await window.electronAPI.pluginPublisher.resolveConfirm(raw.requestId, confirmed);
+ } catch {
+ // Window teardown cancels the pending confirm in Main.
+ }
+ }
+ })();
+ });
+ }, [confirm, t]);
+
+ return null;
+}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 885f788204..6ea892c724 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -4627,6 +4627,46 @@
"reviewOutdated": "Review outdated",
"approve": "Approve",
"skip": "Skip"
+ },
+ "publish": {
+ "section": "My publishes",
+ "action": "Publish plugin…",
+ "confirmTitle": "Publish {{name}}",
+ "confirmDescription": "After you confirm, the package is uploaded to the current organization.",
+ "org": "Organization",
+ "pluginId": "Plugin id",
+ "version": "Version",
+ "size": "Size",
+ "confirm": "Publish",
+ "cancel": "Cancel",
+ "disabled": "This organization has not enabled member publishing. Contact an admin.",
+ "loadFailed": "Could not load your publishes",
+ "startFailed": "Could not start publishing",
+ "empty": "No publishes yet",
+ "unknownPlugin": "Plugin",
+ "uploading": "Publishing",
+ "badge": {
+ "validating": "Checking",
+ "processing": "Processing",
+ "pending": "Pending review",
+ "approved": "Published",
+ "rejected": "Rejected",
+ "failed": "Failed",
+ "expired": "Expired"
+ },
+ "stage": {
+ "confirming": "Waiting for confirmation",
+ "hashing": "Checking the file",
+ "preparing": "Creating the upload",
+ "uploading": "Uploading",
+ "committing": "Submitting",
+ "processing": "Processing",
+ "succeeded": "Finished",
+ "failed": "Failed",
+ "expired": "Expired",
+ "cancelled": "Cancelled",
+ "cancelledTracking": "Stopped watching. The server is still processing."
+ }
}
},
"mcp": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index a0c05e99ac..ccc58c136a 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -4626,6 +4626,46 @@
"reviewOutdated": "レビュー期限切れ",
"approve": "承認",
"skip": "スキップ"
+ },
+ "publish": {
+ "section": "自分の公開",
+ "action": "プラグインを公開…",
+ "confirmTitle": "{{name}} を公開",
+ "confirmDescription": "確認後、現在の組織へアップロードします。",
+ "org": "組織",
+ "pluginId": "プラグイン id",
+ "version": "バージョン",
+ "size": "サイズ",
+ "confirm": "公開",
+ "cancel": "キャンセル",
+ "disabled": "この組織ではメンバー公開が有効になっていません。管理者に連絡してください。",
+ "loadFailed": "公開一覧を読み込めません",
+ "startFailed": "公開を開始できません",
+ "empty": "公開履歴はまだありません",
+ "unknownPlugin": "プラグイン",
+ "uploading": "公開中",
+ "badge": {
+ "validating": "検証中",
+ "processing": "処理中",
+ "pending": "審査待ち",
+ "approved": "公開済み",
+ "rejected": "却下",
+ "failed": "失敗",
+ "expired": "期限切れ"
+ },
+ "stage": {
+ "confirming": "確認待ち",
+ "hashing": "ファイルを検証中",
+ "preparing": "アップロードを作成中",
+ "uploading": "アップロード中",
+ "committing": "送信中",
+ "processing": "処理中",
+ "succeeded": "完了",
+ "failed": "失敗",
+ "expired": "期限切れ",
+ "cancelled": "キャンセル済み",
+ "cancelledTracking": "追跡を停止しました。サーバー側では処理が続いています。"
+ }
}
},
"mcp": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index cb757e4f87..2486c27103 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -4626,6 +4626,46 @@
"reviewOutdated": "검토 기간 만료",
"approve": "승인",
"skip": "건너뛰기"
+ },
+ "publish": {
+ "section": "내 게시",
+ "action": "플러그인 게시…",
+ "confirmTitle": "{{name}} 게시",
+ "confirmDescription": "확인하면 현재 조직으로 업로드가 시작됩니다.",
+ "org": "조직",
+ "pluginId": "플러그인 id",
+ "version": "버전",
+ "size": "크기",
+ "confirm": "게시",
+ "cancel": "취소",
+ "disabled": "이 조직은 구성원 게시를 켜지 않았습니다. 관리자에게 문의하세요.",
+ "loadFailed": "게시 목록을 불러올 수 없습니다",
+ "startFailed": "게시를 시작할 수 없습니다",
+ "empty": "아직 게시 기록이 없습니다",
+ "unknownPlugin": "플러그인",
+ "uploading": "게시 중",
+ "badge": {
+ "validating": "검사 중",
+ "processing": "처리 중",
+ "pending": "검토 대기",
+ "approved": "게시됨",
+ "rejected": "거절됨",
+ "failed": "실패",
+ "expired": "만료됨"
+ },
+ "stage": {
+ "confirming": "확인 대기",
+ "hashing": "파일 검사 중",
+ "preparing": "업로드 생성 중",
+ "uploading": "업로드 중",
+ "committing": "제출 중",
+ "processing": "처리 중",
+ "succeeded": "완료",
+ "failed": "실패",
+ "expired": "만료됨",
+ "cancelled": "취소됨",
+ "cancelledTracking": "추적을 멈췄습니다. 서버는 계속 처리 중입니다."
+ }
}
},
"mcp": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index b791b384d9..4c6870769f 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -4626,6 +4626,46 @@
"reviewOutdated": "审查过期",
"approve": "同意",
"skip": "跳过"
+ },
+ "publish": {
+ "section": "我的发布",
+ "action": "发布插件…",
+ "confirmTitle": "发布 {{name}}",
+ "confirmDescription": "确认后开始上传到当前组织。",
+ "org": "组织",
+ "pluginId": "插件 id",
+ "version": "版本",
+ "size": "大小",
+ "confirm": "发布",
+ "cancel": "取消",
+ "disabled": "本企业未开启成员发布,请联系管理员",
+ "loadFailed": "发布列表暂时不可用",
+ "startFailed": "无法开始发布",
+ "empty": "还没有发布记录",
+ "unknownPlugin": "插件",
+ "uploading": "正在发布",
+ "badge": {
+ "validating": "校验中",
+ "processing": "处理中",
+ "pending": "待审核",
+ "approved": "已上架",
+ "rejected": "被驳回",
+ "failed": "失败",
+ "expired": "已过期"
+ },
+ "stage": {
+ "confirming": "等待确认",
+ "hashing": "正在校验文件",
+ "preparing": "正在创建上传",
+ "uploading": "正在上传",
+ "committing": "正在提交",
+ "processing": "正在处理",
+ "succeeded": "已完成",
+ "failed": "失败",
+ "expired": "已过期",
+ "cancelled": "已取消",
+ "cancelledTracking": "已停止跟踪,服务端仍在处理"
+ }
}
},
"mcp": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 668e475d44..82914434b9 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -4626,6 +4626,46 @@
"reviewOutdated": "審查過期",
"approve": "同意",
"skip": "跳過"
+ },
+ "publish": {
+ "section": "我的發佈",
+ "action": "發佈插件…",
+ "confirmTitle": "發佈 {{name}}",
+ "confirmDescription": "確認後開始上傳到目前組織。",
+ "org": "組織",
+ "pluginId": "插件 id",
+ "version": "版本",
+ "size": "大小",
+ "confirm": "發佈",
+ "cancel": "取消",
+ "disabled": "本企業未開啟成員發佈,請聯絡管理員",
+ "loadFailed": "發佈列表暫時無法使用",
+ "startFailed": "無法開始發佈",
+ "empty": "還沒有發佈記錄",
+ "unknownPlugin": "插件",
+ "uploading": "正在發佈",
+ "badge": {
+ "validating": "校驗中",
+ "processing": "處理中",
+ "pending": "待審核",
+ "approved": "已上架",
+ "rejected": "被駁回",
+ "failed": "失敗",
+ "expired": "已過期"
+ },
+ "stage": {
+ "confirming": "等待確認",
+ "hashing": "正在校驗檔案",
+ "preparing": "正在建立上傳",
+ "uploading": "正在上傳",
+ "committing": "正在提交",
+ "processing": "正在處理",
+ "succeeded": "已完成",
+ "failed": "失敗",
+ "expired": "已過期",
+ "cancelled": "已取消",
+ "cancelledTracking": "已停止追蹤,伺服器仍在處理"
+ }
}
},
"mcp": {
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index cc25cb2b68..ababa4b748 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -1641,6 +1641,18 @@ interface ElectronAPI {
refreshSource: (name: string) => Promise<import('../shared/pluginMarket').MarketSourceSummary>;
gitPreflight: () => Promise<{ ok: boolean; version: string | null }>;
};
+ pluginPublisher: {
+ start: (filePath: string) => Promise<{ transferId: string; uploadId: string | null }>;
+ status: (transferId: string) => Promise<{ progress: unknown }>;
+ cancel: (transferId: string) => Promise<{ cancelled: boolean }>;
+ listMine: (cursor?: string) => Promise<{
+ releases: Array<Record<string, unknown>>;
+ nextCursor: string | null;
+ }>;
+ onProgress: (callback: (progress: unknown) => void) => () => void;
+ onConfirm: (callback: (request: unknown) => void) => () => void;
+ resolveConfirm: (requestId: string, confirmed: boolean) => Promise<{ handled: boolean }>;
+ };
voiceInput: {
prewarm: (payload?: {
sourceLanguage?: string;
diff --git a/packages/cindy-tools/src/__tests__/ghostMcp.test.ts b/packages/cindy-tools/src/__tests__/ghostMcp.test.ts
index 9de39df692..23e476c1d5 100644
--- a/packages/cindy-tools/src/__tests__/ghostMcp.test.ts
+++ b/packages/cindy-tools/src/__tests__/ghostMcp.test.ts
@@ -7,6 +7,8 @@ import {
ghostSetupPlanInputSchema,
handleForgeGuide,
handleForgePack,
+ handleForgePublish,
+ handleForgePublishStatus,
handleForgeScaffold,
handleGhostCall,
handleGhostInfo,
@@ -70,6 +72,18 @@ function fakeDeps(
version: "1.0.0",
note: "pending confirm",
}),
+ forgePublish: async () => ({
+ ok: true,
+ transferId: "transfer-1",
+ uploadId: null,
+ note: "started",
+ }),
+ forgePublishStatus: async () => ({
+ ok: true,
+ transferId: "transfer-1",
+ uploadId: "upload-1",
+ stage: "processing",
+ }),
...overrides,
};
}
@@ -1150,7 +1164,7 @@ describe("cindy · media MCP 边界", () => {
});
describe("cindy_ghosts · server 构建", () => {
- it("四件插件发现/读取/调用工具、三件锻造工具与 Core media 固定注册", () => {
+ it("四件插件发现/读取/调用工具、锻造工具与 Core media 固定注册", () => {
const server = createCindyGhostsMcpServer(fakeDeps()) as unknown as {
_registeredTools: Record<string, { description?: string } | undefined>;
};
@@ -1158,6 +1172,8 @@ describe("cindy_ghosts · server 构建", () => {
"ghost_call",
"ghost_forge_guide",
"ghost_forge_pack",
+ "ghost_forge_publish",
+ "ghost_forge_publish_status",
"ghost_forge_scaffold",
"ghost_info",
"ghost_list",
@@ -1483,6 +1499,43 @@ describe("cindy_ghosts · ghost_forge(锻造)", () => {
]);
});
+ it("forge_publish 立即透传 transferId;失败标 isError", async () => {
+ const okResult = await handleForgePublish(fakeDeps(), {
+ file: "/tmp/x.cindy",
+ });
+ expect(parsePayload(okResult)).toMatchObject({
+ ok: true,
+ transferId: "transfer-1",
+ });
+
+ const failed = await handleForgePublish(
+ fakeDeps({
+ forgePublish: async () => ({
+ ok: false,
+ errorCode: "NOT_ORG_MEMBER",
+ message: "需要组织身份",
+ }),
+ }),
+ { file: "/tmp/x.cindy" },
+ );
+ expect(failed.isError).toBe(true);
+ expect(parsePayload(failed)).toMatchObject({
+ ok: false,
+ errorCode: "NOT_ORG_MEMBER",
+ });
+ });
+
+ it("forge_publish_status 透传后台阶段", async () => {
+ const result = await handleForgePublishStatus(fakeDeps(), {
+ transferId: "transfer-1",
+ });
+ expect(parsePayload(result)).toMatchObject({
+ ok: true,
+ stage: "processing",
+ uploadId: "upload-1",
+ });
+ });
+
it("forge_pack 描述明确图片工具结果字段", () => {
const server = createCindyGhostsMcpServer(fakeDeps()) as unknown as {
_registeredTools: Record<string, { description?: string } | undefined>;
diff --git a/packages/cindy-tools/src/ghost/mcpServer.ts b/packages/cindy-tools/src/ghost/mcpServer.ts
index 2d7a38cc45..54bbd642f3 100644
--- a/packages/cindy-tools/src/ghost/mcpServer.ts
+++ b/packages/cindy-tools/src/ghost/mcpServer.ts
@@ -131,6 +131,22 @@ const D_GHOST_FORGE_PACK = [
"按 message 修正源码后重新打包即可。打包成功 ≠ 已装入:告知用户去点确认框。",
].join("\n");
+const D_GHOST_FORGE_PUBLISH = [
+ "把一个本机 .cindy 插件包发布到当前登录组织。file 传绝对路径。",
+ "本工具立即返回 transferId(以及稍后才有的 uploadId),传输在后台跑;",
+ "用 ghost_forge_publish_status 查阶段与结果。不要把它和 ghost_forge_pack 混成一次调用:",
+ "打包失败和发布失败语义不同。主机会弹出确认屏(组织 / 插件 id / 版本 / 大小),",
+ "用户确认后才真正开传。立即失败只有 NOT_ORG_MEMBER / INTERNAL;传输开始后的失败看 status 的 message,",
+ "不要按固定枚举分支。",
+].join("\n");
+
+const D_GHOST_FORGE_PUBLISH_STATUS = [
+ "查询一次 ghost_forge_publish 后台传输的当前状态。transferId 来自 publish 的立即返回。",
+ "status 变成 succeeded 之后 reviewStatus 仍可能从 pending 变为 approved / rejected,",
+ "需要继续查到审核终态再向用户收口。errorCode / message 是自由字符串,读 message 向用户说明,",
+ "不要按固定枚举分支。",
+].join("\n");
+
/**
* 花名册 recall 召回线索(whenToUse 优先、description 回落)的截断上限,
* 与 manifest 的 description / whenToUse 校验同源。
@@ -1039,6 +1055,55 @@ export async function handleForgePack(
}
}
+/** ghost_forge_publish 的 handler 主体(导出供单测)。 */
+export async function handleForgePublish(
+ deps: CindyGhostsMcpDeps,
+ input: { file: string },
+): Promise<McpTextResult> {
+ try {
+ const result = await deps.forgePublish({ file: input.file });
+ if (!result.ok) {
+ deps.logger?.warn("ghost_forge_publish rejected", {
+ errorCode: result.errorCode,
+ });
+ return textResult(result, true);
+ }
+ return textResult(result);
+ } catch (err) {
+ return textResult(
+ {
+ ok: false,
+ errorCode: "INTERNAL",
+ message: err instanceof Error ? err.message : String(err),
+ },
+ true,
+ );
+ }
+}
+
+/** ghost_forge_publish_status 的 handler 主体(导出供单测)。 */
+export async function handleForgePublishStatus(
+ deps: CindyGhostsMcpDeps,
+ input: { transferId: string },
+): Promise<McpTextResult> {
+ try {
+ const result = await deps.forgePublishStatus({ transferId: input.transferId });
+ if (!result.ok) {
+ return textResult(result, true);
+ }
+ return textResult(result);
+ } catch (err) {
+ return textResult(
+ {
+ ok: false,
+ errorCode: "INTERNAL",
+ message: err instanceof Error ? err.message : String(err),
+ },
+ true,
+ );
+ }
+}
+
/** 构建 cindy_ghosts MCP server(host 在会话装配时按 provider 惯例创建实例)。 */
export function createCindyGhostsMcpServer(
deps: CindyGhostsMcpDeps,
@@ -1221,5 +1286,23 @@ export function createCindyGhostsMcpServer(
async (input) => handleForgePack(deps, input),
);
+ server.tool(
+ "ghost_forge_publish",
+ D_GHOST_FORGE_PUBLISH,
+ {
+ file: z.string().describe("要发布的 .cindy 包绝对路径"),
+ },
+ async (input) => handleForgePublish(deps, input),
+ );
+
+ server.tool(
+ "ghost_forge_publish_status",
+ D_GHOST_FORGE_PUBLISH_STATUS,
+ {
+ transferId: z.string().describe("ghost_forge_publish 立即返回的 transferId"),
+ },
+ async (input) => handleForgePublishStatus(deps, input),
+ );
+
return server;
}
diff --git a/packages/cindy-tools/src/index.ts b/packages/cindy-tools/src/index.ts
index b8a2083e6a..7ff7b3cff7 100644
--- a/packages/cindy-tools/src/index.ts
+++ b/packages/cindy-tools/src/index.ts
@@ -3,6 +3,8 @@ export {
createCindyGhostsMcpServer,
handleForgeGuide,
handleForgePack,
+ handleForgePublish,
+ handleForgePublishStatus,
handleForgeScaffold,
handleGhostCall,
handleGhostInfo,
@@ -14,6 +16,9 @@ export {
export type {
CindyForgePackErrorCode,
CindyForgePackResult,
+ CindyForgePublishErrorCode,
+ CindyForgePublishResult,
+ CindyForgePublishStatusResult,
CindyForgeScaffoldResult,
CindyForgeScaffoldTemplate,
CindyGhostCallErrorCode,
diff --git a/packages/cindy-tools/src/types.ts b/packages/cindy-tools/src/types.ts
index c206a53ea3..0dad78220e 100644
--- a/packages/cindy-tools/src/types.ts
+++ b/packages/cindy-tools/src/types.ts
@@ -245,6 +245,36 @@ export type CindyForgePackResult =
}
| { ok: false; errorCode: CindyForgePackErrorCode; message: string };
+/** ghost_forge_publish 立即返回时的失败分类。传输开始后的失败走 status.errorCode。 */
+export type CindyForgePublishErrorCode = 'NOT_ORG_MEMBER' | 'INTERNAL';
+
+export type CindyForgePublishResult =
+ | {
+ ok: true;
+ transferId: string;
+ uploadId: string | null;
+ note: string;
+ }
+ | { ok: false; errorCode: CindyForgePublishErrorCode; message: string };
+
+export type CindyForgePublishStatusResult =
+ | {
+ ok: true;
+ transferId: string;
+ uploadId: string | null;
+ stage: string;
+ status?: string | null;
+ reviewStatus?: string | null;
+ ghostId?: string | null;
+ version?: string | null;
+ bytesHashed?: number;
+ bytesSent?: number;
+ totalBytes?: number;
+ errorCode?: string | null;
+ message?: string | null;
+ }
+ | { ok: false; errorCode: 'NOT_FOUND' | 'INTERNAL'; message: string };
+
/** ghost_forge_scaffold 可生成的四种起步模板。 */
export type CindyForgeScaffoldTemplate =
| 'plain'
@@ -403,6 +433,13 @@ export interface CindyGhostsMcpDeps {
*/
iconSource?: string;
}): Promise<CindyForgePackResult>;
+ /**
+ * 把一个本机 .cindy 包提交到当前组织发布。立即返回 transferId / uploadId,
+ * 传输在后台跑;用 forgePublishStatus 查进度。
+ */
+ forgePublish(request: { file: string }): Promise<CindyForgePublishResult>;
+ /** 查询一次后台发布传输的当前状态。 */
+ forgePublishStatus(request: { transferId: string }): Promise<CindyForgePublishStatusResult>;
logger?: {
info: (msg: string, meta?: Record<string, unknown>) => void;
warn: (msg: string, meta?: Record<string, unknown>) => void;