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。

fix(desktop): bind agent publishing to forge tickets

fmfsaisai29b1b443687e
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 ce3d09c825..fdb297bccf 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
@@ -1434,6 +1434,13 @@ describe('scaffoldGhostDir', () => {
});
describe('FORGE_GUIDE', () => {
+ it('documents the org-only token publish flow without exposing a file path handoff', () => {
+ expect(FORGE_GUIDE).toContain("intent: 'publish'");
+ expect(FORGE_GUIDE).toContain('一次性 `publishToken`');
+ expect(FORGE_GUIDE).toContain("ghost_forge_publish({ token: '<publishToken>' })");
+ expect(FORGE_GUIDE).toContain('仅企业组织成员可用,个人账号不可用');
+ });
+
it('开场白必读口径与 createPrompt 一致:三章且卡槽总览带真实章号', () => {
// 聊天里直接说"帮我做个插件"的路径只看到手册,看不到 createPrompt;
// 两处必读口径分叉会让不同入口的 agent 走出不同的阅读深度。
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forgePackPublishConsume.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forgePackPublishConsume.test.ts
new file mode 100644
index 0000000000..a4276132e6
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/forgePackPublishConsume.test.ts
@@ -0,0 +1,102 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { consumeForgePackForPublish } from '../forgePackPublishConsume.js';
+import { createForgePackStagingController, FORGE_PACK_TICKET_TTL_MS } from '../forgePackStaging.js';
+
+const roots: string[] = [];
+const owner = { mode: 'cloud' as const, dataOwnerId: 'member-1', generation: 7 };
+
+afterEach(() => {
+ for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true });
+});
+
+function harness(nowValue = 1_000) {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'forge-publish-consume-'));
+ roots.push(root);
+ let now = nowValue;
+ const controller = createForgePackStagingController({
+ getTempDir: () => root,
+ now: () => now,
+ ttlMs: FORGE_PACK_TICKET_TTL_MS,
+ randomId: (() => {
+ let sequence = 0;
+ return () => `token-${++sequence}`;
+ })(),
+ scheduleTimeout: () => ({ cancel() {} }),
+ });
+ const staged = controller.stage({
+ buf: Buffer.from('packed bytes'),
+ manifestId: 'acme-demo',
+ owner,
+ operationKind: 'install',
+ });
+ return { controller, staged, setNow: (value: number) => (now = value) };
+}
+
+describe('consumeForgePackForPublish', () => {
+ it('checks the session boundary before consuming the one-shot ticket', () => {
+ const { controller, staged } = harness();
+ expect(
+ consumeForgePackForPublish(controller, {
+ token: staged.ticket,
+ currentOwner: owner,
+ boundaryPending: true,
+ }),
+ ).toEqual({ kind: 'rejected', reason: 'session-boundary-pending' });
+ // Excludes the wrong order "consume then check boundary": the same ticket remains usable.
+ expect(
+ consumeForgePackForPublish(controller, {
+ token: staged.ticket,
+ currentOwner: owner,
+ boundaryPending: false,
+ }).kind,
+ ).toBe('accepted');
+ });
+
+ it('rejects owner mismatch and deletes staging bytes', () => {
+ const { controller, staged } = harness();
+ expect(
+ consumeForgePackForPublish(controller, {
+ token: staged.ticket,
+ currentOwner: { ...owner, generation: owner.generation + 1 },
+ boundaryPending: false,
+ }),
+ ).toEqual({ kind: 'rejected', reason: 'owner-mismatch' });
+ expect(fs.existsSync(staged.stagingPath)).toBe(false);
+ });
+
+ it('rejects replay after one accepted consume', () => {
+ const { controller, staged } = harness();
+ expect(
+ consumeForgePackForPublish(controller, {
+ token: staged.ticket,
+ currentOwner: owner,
+ boundaryPending: false,
+ }).kind,
+ ).toBe('accepted');
+ expect(
+ consumeForgePackForPublish(controller, {
+ token: staged.ticket,
+ currentOwner: owner,
+ boundaryPending: false,
+ }),
+ ).toEqual({ kind: 'rejected', reason: 'ticket-invalid' });
+ });
+
+ it('rejects the pack ticket at its own 10-minute expiry', () => {
+ const { controller, staged, setNow } = harness();
+ setNow(1_000 + FORGE_PACK_TICKET_TTL_MS);
+ expect(
+ consumeForgePackForPublish(controller, {
+ token: staged.ticket,
+ currentOwner: owner,
+ boundaryPending: false,
+ }),
+ ).toEqual({ kind: 'rejected', reason: 'ticket-invalid' });
+ expect(fs.existsSync(staged.stagingPath)).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index e8eff2782b..002088a1c3 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -1399,7 +1399,7 @@ export const FORGE_GUIDE = `# 意识(Ghost)编写手册
主机叠加:AI 可调用的工具、常驻界面面板、模型代办能力。本手册教你(agent)替用户
写一个意识。**流程:先取手册目录 → 按 §0 用提问卡片和用户对齐设计 → 按需用 section
读透相关章(动手前至少读完 §2 卡槽总览、"沙箱红线"与"打包与测试"三章) → 在工作目录写源码文件 →
-ghost_forge_pack 打包 → 用户在弹窗上确认装入。**
+ghost_forge_pack 打包 → 用户在弹窗上确认装入;需要发布时改用 publish intent 取得一次性票据。**
从零开始时优先调用 \`ghost_forge_scaffold\` 生成一份不会覆盖现有文件的骨架,再在
骨架上修改。可选模板:\`plain\`(普通沙箱工具)、\`agent-action\`(卡片点击后让 Agent
@@ -4225,6 +4225,14 @@ const opened = await cindy.iosSimulator.request({
(记得 bump ghost.json 的 version);
5. 验证:让用户 \`$<command> <内容>\` 试一单,看聊天图卡/面板是否符合预期。
+企业组织成员需要发布时,调用 \`ghost_forge_pack({ dir: '<绝对路径>', intent: 'publish' })\`。
+该意图不会弹装入确认,也不会返回可供自行拼接的 Host 路径;它只返回绑定本次包 id 与
+完整字节的一次性 \`publishToken\`。随后把该票据传给
+\`ghost_forge_publish({ token: '<publishToken>' })\`,工具会立即返回 \`transferId\`,发布在
+后台继续;用 \`ghost_forge_publish_status\` 查询传输与审核状态。发布确认屏仍由用户明确
+确认。成员发布仅企业组织成员可用,个人账号不可用;票据过期、换账号或重复使用后须重新
+以 publish intent 打包,不能改传文件路径绕过。
+
## 8. 发布签名与审核
\`ghost_forge_pack\` 默认只负责本地制作和试装,生成的是**未签名包**。未签名不等于
diff --git a/apps/desktop/src/main/cindy-brain/forgePackPublishConsume.ts b/apps/desktop/src/main/cindy-brain/forgePackPublishConsume.ts
new file mode 100644
index 0000000000..c578f6ea34
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/forgePackPublishConsume.ts
@@ -0,0 +1,40 @@
+/**
+ * Consume a forge-pack ticket for Agent-initiated publishing.
+ *
+ * The order is deliberate: an account boundary must not burn a valid ticket;
+ * after the one-shot consume, the captured owner must still match the current
+ * session. Package id and bytes stay bound by the publisher pipeline itself.
+ */
+import type { ActiveAppSession } from '../appSessionState.js';
+import type { ForgePackIntegrityTicket, ForgePackStagingController } from './forgePackStaging.js';
+
+export type ForgePackPublishConsume =
+ | { kind: 'accepted'; ticket: ForgePackIntegrityTicket }
+ | {
+ kind: 'rejected';
+ reason: 'session-boundary-pending' | 'ticket-invalid' | 'owner-mismatch';
+ };
+
+function sameOwner(a: ActiveAppSession, b: ActiveAppSession): boolean {
+ return a.mode === b.mode && a.dataOwnerId === b.dataOwnerId && a.generation === b.generation;
+}
+
+export function consumeForgePackForPublish(
+ controller: ForgePackStagingController,
+ input: {
+ token: string;
+ currentOwner: ActiveAppSession;
+ boundaryPending: boolean;
+ },
+): ForgePackPublishConsume {
+ if (input.boundaryPending) {
+ return { kind: 'rejected', reason: 'session-boundary-pending' };
+ }
+ const ticket = controller.consume(input.token);
+ if (!ticket) return { kind: 'rejected', reason: 'ticket-invalid' };
+ if (!sameOwner(ticket.owner, input.currentOwner)) {
+ controller.releaseStaging(ticket.stagingPath);
+ return { kind: 'rejected', reason: 'owner-mismatch' };
+ }
+ return { kind: 'accepted', ticket };
+}
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts
index f3151a1ae6..de21d33bfd 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts
@@ -30,6 +30,30 @@ const logWarnMock = vi.fn();
const logInfoMock = vi.fn();
const grantAttachmentsMock = vi.fn();
const { packGhostDirMock } = vi.hoisted(() => ({ packGhostDirMock: vi.fn() }));
+const { handleIncomingCindyFileMock, completeForgePackStagingMock } = vi.hoisted(() => ({
+ handleIncomingCindyFileMock: vi.fn(async () => undefined),
+ completeForgePackStagingMock: vi.fn(() => ({
+ ticket: 'publish-token-1',
+ installPath: '/host/staging/demo.cindy',
+ agentCindyPath: 'demo-1.0.0.cindy',
+ packageSha256: 'a'.repeat(64),
+ })),
+}));
+const {
+ publishTicketConsumeMock,
+ releaseForgePackStagingMock,
+ startPluginPublishMock,
+ currentPublisherIdentityMock,
+} = vi.hoisted(() => ({
+ publishTicketConsumeMock: vi.fn(),
+ releaseForgePackStagingMock: vi.fn(),
+ startPluginPublishMock: vi.fn(() => ({ transferId: 'transfer-1', uploadId: null })),
+ currentPublisherIdentityMock: vi.fn(() => ({
+ membershipId: 'member-1',
+ orgSlug: 'acme',
+ orgName: 'Acme',
+ })),
+}));
const releaseMutationMock = vi.fn();
const captureMutationOwnerMock = vi.fn(() => ({
mode: 'local' as const,
@@ -80,6 +104,8 @@ const resolvedAttachmentOrigins: Array<'user' | 'tool' | undefined> = [];
vi.mock('electron', () => ({ app: { getPath: () => tmpUserData } }));
vi.mock('../../appSessionState.js', () => ({
ownerScopedUserDataPath: (...parts: string[]) => path.join(tmpUserData, ...parts),
+ getActiveAppSession: () => ({ mode: 'cloud', dataOwnerId: 'member-1', generation: 7 }),
+ isAppSessionBoundaryPending: () => false,
}));
vi.mock('../../maker-host/logger-adapter.js', () => {
const createMakerLogger = () => ({
@@ -175,9 +201,26 @@ vi.mock('../../cindy-brain/forge.js', () => ({
packGhostDir: packGhostDirMock,
scaffoldGhostDir: vi.fn(),
}));
-vi.mock('../../cindy-brain/openFileInstall.js', () => ({ handleIncomingCindyFile: vi.fn() }));
+vi.mock('../../cindy-brain/forgePackStaging.js', () => ({
+ completeForgePackStaging: completeForgePackStagingMock,
+ getForgePackStagingController: () => ({
+ consume: publishTicketConsumeMock,
+ releaseStaging: releaseForgePackStagingMock,
+ }),
+ invalidateForgePackTicket: vi.fn(),
+ releaseForgePackStaging: releaseForgePackStagingMock,
+}));
+vi.mock('../../cindy-brain/openFileInstall.js', () => ({
+ handleIncomingCindyFile: handleIncomingCindyFileMock,
+}));
vi.mock('../../localDb/ipc/sessions.js', () => ({
getSessionFsSnapshot: sessionSnapshotMock,
+ getSessionTitle: vi.fn(async () => 'Test session'),
+}));
+vi.mock('../../plugin-publisher/host.js', () => ({
+ currentPublisherIdentity: currentPublisherIdentityMock,
+ getPluginPublisherOrchestrator: vi.fn(),
+ startPluginPublish: startPluginPublishMock,
}));
vi.mock('../../cindy-media/blobStore.js', () => ({ mimeForExt: () => 'image/png' }));
vi.mock('../../cindy-media/ledger.js', () => ({
@@ -364,6 +407,20 @@ beforeEach(() => {
errorCode: 'MANIFEST_INVALID',
message: 'stop after gate assertion',
});
+ handleIncomingCindyFileMock.mockClear();
+ completeForgePackStagingMock.mockClear();
+ publishTicketConsumeMock.mockReset();
+ publishTicketConsumeMock.mockReturnValue({
+ owner: { mode: 'cloud', dataOwnerId: 'member-1', generation: 7 },
+ operationKind: 'install',
+ stagingPath: '/host/staging/demo.cindy',
+ packageSha256: 'a'.repeat(64),
+ manifestId: 'demo',
+ packExpiresAt: Date.now() + 600_000,
+ });
+ releaseForgePackStagingMock.mockClear();
+ startPluginPublishMock.mockClear();
+ currentPublisherIdentityMock.mockClear();
clearAllPrefs();
});
@@ -385,6 +442,62 @@ describe('Forge session workdir gate', () => {
});
});
+ it('keeps default intent on the install-confirm path without exposing a publish token', async () => {
+ packGhostDirMock.mockResolvedValueOnce({
+ ok: true,
+ buf: Buffer.from('packed'),
+ cindyPath: path.join(WORKDIR, 'plugin-src', 'demo-1.0.0.cindy'),
+ manifest: { id: 'demo', name: 'Demo', version: '1.0.0' },
+ });
+ const result = await makeDeps().forgePack({ dir: path.join(WORKDIR, 'plugin-src') });
+ expect(result).toMatchObject({ ok: true, cindyPath: 'demo-1.0.0.cindy' });
+ expect(result).not.toHaveProperty('publishToken');
+ expect(handleIncomingCindyFileMock).toHaveBeenCalledWith(
+ '/host/staging/demo.cindy',
+ 'ghost-forge',
+ expect.objectContaining({ kind: 'agent-forge' }),
+ );
+ });
+
+ it('returns the one-shot token for publish intent without opening install confirmation', async () => {
+ packGhostDirMock.mockResolvedValueOnce({
+ ok: true,
+ buf: Buffer.from('packed'),
+ cindyPath: path.join(WORKDIR, 'plugin-src', 'demo-1.0.0.cindy'),
+ manifest: { id: 'demo', name: 'Demo', version: '1.0.0' },
+ });
+ const result = await makeDeps().forgePack({
+ dir: path.join(WORKDIR, 'plugin-src'),
+ intent: 'publish',
+ });
+ expect(result).toMatchObject({ ok: true, publishToken: 'publish-token-1' });
+ expect(handleIncomingCindyFileMock).not.toHaveBeenCalled();
+ });
+
+ it('consumes the publish token and binds publisher input to ticket id, SHA and cleanup', async () => {
+ const result = await makeDeps().forgePublish({ token: 'publish-token-1' });
+ expect(result).toMatchObject({ ok: true, transferId: 'transfer-1', uploadId: null });
+ expect(publishTicketConsumeMock).toHaveBeenCalledWith('publish-token-1');
+ expect(startPluginPublishMock).toHaveBeenCalledWith(
+ '/host/staging/demo.cindy',
+ null,
+ expect.objectContaining({
+ manifestId: 'demo',
+ packageSha256: 'a'.repeat(64),
+ onTerminal: expect.any(Function),
+ }),
+ );
+ const binding = (
+ startPluginPublishMock.mock.calls as unknown as Array<[
+ string,
+ null,
+ { onTerminal: () => void },
+ ]>
+ )[0]?.[2];
+ binding?.onTerminal();
+ expect(releaseForgePackStagingMock).toHaveBeenCalledWith('/host/staging/demo.cindy');
+ });
+
it('rejects remote workdirs before touching local Forge fs', async () => {
sessionSnapshotMock.mockResolvedValueOnce({
workingDir: '/remote/project',
diff --git a/apps/desktop/src/main/mcp-integrations/ghost.ts b/apps/desktop/src/main/mcp-integrations/ghost.ts
index 81739ee987..2867617f65 100644
--- a/apps/desktop/src/main/mcp-integrations/ghost.ts
+++ b/apps/desktop/src/main/mcp-integrations/ghost.ts
@@ -11,8 +11,8 @@
* - callGhostTool:透传给管子派发器(pipeDispatcher),资格审/按需拉起/
* 配对超时/崩溃收卷全在那边,错误码两侧同构直接原样交回;
* - forgeGuide / forgeScaffold / forgePack:意识锻造(agent 帮用户做意识)——
- * 手册、骨架与打包真身在 cindy-brain/forge.ts,打包成功后经双击转交
- * 通道弹装入确认框(与拖入/双击完全同一个弹窗,装不装永远由用户点头)。
+ * 手册、骨架与打包真身在 cindy-brain/forge.ts。缺省打包经双击转交
+ * 通道弹装入确认框;publish intent 改签一次性发布票据。
*
* cindy-tools 是意识系统工具集,包内零 Electron
* 依赖,全部能力经本文件注入(设计规范规则 2)。
@@ -55,6 +55,7 @@ import {
import { classifyLocalAttachmentPath } from '../cindy-brain/ghostLocalPathGrant.js';
import { toolNotFoundMessage } from '../cindy-brain/pipeDispatcher.js';
import { getSessionFsSnapshot, getSessionTitle } from '../localDb/ipc/sessions.js';
+import { getActiveAppSession, isAppSessionBoundaryPending } from '../appSessionState.js';
import {
deriveGhostSessionContext,
type GhostSessionContextInjected,
@@ -81,8 +82,11 @@ import { isGhostDisabledForWorkdir } from '../cindy-brain/ghostWorkdirPrefs.js';
import { FORGE_GUIDE, packGhostDir, scaffoldGhostDir } from '../cindy-brain/forge.js';
import {
completeForgePackStaging,
+ getForgePackStagingController,
invalidateForgePackTicket,
+ releaseForgePackStaging,
} from '../cindy-brain/forgePackStaging.js';
+import { consumeForgePackForPublish } from '../cindy-brain/forgePackPublishConsume.js';
import {
currentPublisherIdentity,
getPluginPublisherOrchestrator,
@@ -1717,7 +1721,7 @@ export function getCindyGhostsMcpDeps(
return result;
});
},
- async forgePack({ dir, iconSource }): Promise<CindyForgePackResult> {
+ async forgePack({ dir, iconSource, intent = 'install' }): Promise<CindyForgePackResult> {
return withForgeOwnerLease(async () => {
const gate = await getForgeSessionFsGate(resolveSessionContext());
if (!gate.ok) return gate;
@@ -1805,6 +1809,18 @@ export function getCindyGhostsMcpDeps(
message: err instanceof Error ? err.message : String(err),
};
}
+ if (intent === 'publish') {
+ log.info('ghost forge packed for publish', { dir, id: packed.manifest.id });
+ return {
+ ok: true,
+ cindyPath: staged.agentCindyPath,
+ id: packed.manifest.id,
+ name: packed.manifest.name,
+ version: packed.manifest.version,
+ publishToken: staged.ticket,
+ note: `${iconNote}已打包为待发布产物。仅企业组织成员可用 ghost_forge_publish 提交;个人账号不可用。`,
+ };
+ }
try {
// 与双击 .cindy 同一条转交通道:renderer 弹标准确认框(同 id 已装则
// 自动转"更新 vX → vY"),用户点头才真装。lease 持到转交完成。带上 agent
@@ -1834,8 +1850,32 @@ export function getCindyGhostsMcpDeps(
};
});
},
- async forgePublish({ file }): Promise<CindyForgePublishResult> {
+ async forgePublish({ token }): Promise<CindyForgePublishResult> {
+ const boundaryPending = isAppSessionBoundaryPending();
+ const consumed = consumeForgePackForPublish(getForgePackStagingController(), {
+ token,
+ currentOwner: getActiveAppSession(),
+ boundaryPending,
+ });
+ if (consumed.kind === 'rejected') {
+ const errorCode =
+ consumed.reason === 'session-boundary-pending'
+ ? 'SESSION_BOUNDARY_PENDING'
+ : consumed.reason === 'owner-mismatch'
+ ? 'PUBLISH_TOKEN_OWNER_MISMATCH'
+ : 'PUBLISH_TOKEN_INVALID';
+ return {
+ ok: false,
+ errorCode,
+ message:
+ consumed.reason === 'session-boundary-pending'
+ ? '账号切换中,请稍后重试'
+ : '发布票据无效、已过期或已被使用,请重新打包',
+ };
+ }
+ const ticket = consumed.ticket;
if (!currentPublisherIdentity()) {
+ releaseForgePackStaging(ticket.stagingPath);
return {
ok: false,
errorCode: 'NOT_ORG_MEMBER',
@@ -1843,7 +1883,11 @@ export function getCindyGhostsMcpDeps(
};
}
try {
- const started = startPluginPublish(file);
+ const started = startPluginPublish(ticket.stagingPath, null, {
+ manifestId: ticket.manifestId,
+ packageSha256: ticket.packageSha256,
+ onTerminal: () => releaseForgePackStaging(ticket.stagingPath),
+ });
return {
ok: true,
transferId: started.transferId,
@@ -1851,6 +1895,7 @@ export function getCindyGhostsMcpDeps(
note: '已开始发布并弹出确认屏。用 ghost_forge_publish_status 查询进度;用户取消或确认后才会继续传输。',
};
} catch (err) {
+ releaseForgePackStaging(ticket.stagingPath);
return {
ok: false,
errorCode: 'INTERNAL',
diff --git a/apps/desktop/src/main/plugin-publisher/__tests__/orchestrator.test.ts b/apps/desktop/src/main/plugin-publisher/__tests__/orchestrator.test.ts
index ffbec0f02a..2d4904517b 100644
--- a/apps/desktop/src/main/plugin-publisher/__tests__/orchestrator.test.ts
+++ b/apps/desktop/src/main/plugin-publisher/__tests__/orchestrator.test.ts
@@ -1,4 +1,5 @@
import fs from 'node:fs/promises';
+import { createHash } from 'node:crypto';
import os from 'node:os';
import path from 'node:path';
@@ -30,6 +31,12 @@ async function packagePath(): Promise<string> {
return filePath;
}
+async function fileSha256(filePath: string): Promise<string> {
+ return createHash('sha256')
+ .update(await fs.readFile(filePath))
+ .digest('hex');
+}
+
function waitFor(
snapshots: PluginPublisherProgress[],
predicate: (progress: PluginPublisherProgress) => boolean,
@@ -59,6 +66,25 @@ const prepared = {
};
describe('PluginPublisherOrchestrator', () => {
+ it('returns immediately while confirmation and transfer continue in the background', async () => {
+ const filePath = await packagePath();
+ let resolveConfirm!: (confirmed: boolean) => void;
+ const confirm = new Promise<boolean>((resolve) => {
+ resolveConfirm = resolve;
+ });
+ const orch = createPluginPublisherOrchestrator({
+ api: { prepare: vi.fn(), commit: vi.fn(), status: vi.fn() } as unknown as PluginPublisherApi,
+ inspectPackage: async () => ({ ghostId: 'demo', name: 'Demo', version: '1.0.0' }),
+ confirm: () => confirm,
+ identity: () => ({ membershipId: 'm1', orgSlug: 'acme', orgName: 'Acme' }),
+ });
+ const started = orch.start(filePath);
+ expect(started.uploadId).toBeNull();
+ expect(orch.snapshot(started.transferId)?.stage).toBe('confirming');
+ resolveConfirm(false);
+ await vi.waitFor(() => expect(orch.snapshot(started.transferId)?.stage).toBe('failed'));
+ });
+
it('keeps polling after commit until a terminal status', async () => {
const filePath = await packagePath();
const statuses = ['validating', 'publishing', 'succeeded'] as const;
@@ -327,4 +353,152 @@ describe('PluginPublisherOrchestrator', () => {
expect(refreshed?.reviewStatus).toBe('approved');
expect(statusCalls).toBe(2);
});
+
+ it('rejects an inspected manifest id that differs from the consumed pack ticket', async () => {
+ const filePath = await packagePath();
+ const prepare = vi.fn();
+ const confirm = vi.fn(async () => true);
+ const cleanup = vi.fn();
+ const snapshots: PluginPublisherProgress[] = [];
+ const orch = createPluginPublisherOrchestrator({
+ api: { prepare, commit: vi.fn(), status: vi.fn() } as unknown as PluginPublisherApi,
+ inspectPackage: async () => ({ ghostId: 'other-id', name: 'Other', version: '1.0.0' }),
+ confirm,
+ identity: () => ({ membershipId: 'm1', orgSlug: 'acme', orgName: 'Acme' }),
+ onProgress: (progress) => snapshots.push({ ...progress }),
+ });
+ orch.start(filePath, {
+ sourceBinding: {
+ manifestId: 'demo',
+ packageSha256: await fileSha256(filePath),
+ onTerminal: cleanup,
+ },
+ });
+ const failed = await waitFor(snapshots, (progress) => progress.stage === 'failed');
+ expect(failed.errorCode).toBe('PUBLISH_PACKAGE_ID_MISMATCH');
+ expect(confirm).not.toHaveBeenCalled();
+ expect(prepare).not.toHaveBeenCalled();
+ await vi.waitFor(() => expect(cleanup).toHaveBeenCalledOnce());
+ });
+
+ it('rejects rewritten staging bytes before prepare or PUT', async () => {
+ const filePath = await packagePath();
+ const expectedSha256 = await fileSha256(filePath);
+ await fs.writeFile(filePath, Buffer.from('rewritten-staging-package'));
+ expect(await fileSha256(filePath)).not.toBe(expectedSha256);
+ const prepare = vi.fn();
+ const putFile = vi.fn();
+ const snapshots: PluginPublisherProgress[] = [];
+ const orch = createPluginPublisherOrchestrator({
+ api: { prepare, 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,
+ onProgress: (progress) => snapshots.push({ ...progress }),
+ });
+ orch.start(filePath, {
+ sourceBinding: { manifestId: 'demo', packageSha256: expectedSha256 },
+ });
+ const failed = await waitFor(snapshots, (progress) => progress.stage === 'failed');
+ expect(failed.errorCode).toBe('PUBLISH_PACKAGE_SHA256_MISMATCH');
+ expect(prepare).not.toHaveBeenCalled();
+ expect(putFile).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { label: 'success', confirm: true, inspectFails: false, terminal: 'succeeded' },
+ { label: 'failure', confirm: true, inspectFails: true, terminal: 'failed' },
+ ])(
+ 'releases forge staging at the $label terminal outcome',
+ async ({ confirm, inspectFails, terminal }) => {
+ const filePath = await packagePath();
+ const cleanup = vi.fn();
+ const snapshots: PluginPublisherProgress[] = [];
+ 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 () => {
+ if (inspectFails) throw new Error('inspect failed');
+ return { ghostId: 'demo', name: 'Demo', version: '1.0.0' };
+ },
+ confirm: async () => confirm,
+ identity: () => ({ membershipId: 'm1', orgSlug: 'acme', orgName: 'Acme' }),
+ putFile: async () => ({ bytesSent: 24 }),
+ sleep: async () => undefined,
+ onProgress: (progress) => snapshots.push({ ...progress }),
+ });
+ orch.start(filePath, {
+ sourceBinding: {
+ manifestId: 'demo',
+ packageSha256: await fileSha256(filePath),
+ onTerminal: cleanup,
+ },
+ });
+ await waitFor(snapshots, (progress) => progress.stage === terminal);
+ await vi.waitFor(() => expect(cleanup).toHaveBeenCalledOnce());
+ },
+ );
+
+ it('releases forge staging when the background transfer is cancelled', async () => {
+ const filePath = await packagePath();
+ const cleanup = vi.fn();
+ const snapshots: PluginPublisherProgress[] = [];
+ const orch = createPluginPublisherOrchestrator({
+ api: { prepare: vi.fn(), 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' }),
+ onProgress: (progress) => snapshots.push({ ...progress }),
+ });
+ const started = orch.start(filePath, {
+ sourceBinding: {
+ manifestId: 'demo',
+ packageSha256: await fileSha256(filePath),
+ onTerminal: cleanup,
+ },
+ });
+ expect(orch.cancel(started.transferId)).toEqual({ cancelled: true });
+ await waitFor(snapshots, (progress) => progress.stage === 'cancelled');
+ await vi.waitFor(() => expect(cleanup).toHaveBeenCalledOnce());
+ });
+
+ it.each([
+ { status: 404, code: 'INTERNAL_ERROR', expected: 'PUBLISH_UNSUPPORTED' },
+ { status: 405, code: 'INTERNAL_ERROR', expected: 'PUBLISH_UNSUPPORTED' },
+ { status: 503, code: 'INTERNAL_ERROR', expected: 'PUBLISH_UNSUPPORTED' },
+ { status: 503, code: 'RATE_LIMIT_UNAVAILABLE', expected: 'RATE_LIMIT_UNAVAILABLE' },
+ { status: 503, code: 'STORAGE_UNAVAILABLE', expected: 'STORAGE_UNAVAILABLE' },
+ ])('maps prepare $status/$code to $expected', async ({ status, code, expected }) => {
+ const filePath = await packagePath();
+ const snapshots: PluginPublisherProgress[] = [];
+ const orch = createPluginPublisherOrchestrator({
+ api: {
+ prepare: async () => {
+ throw new PluginPublisherApiError(code, status, 'redacted');
+ },
+ 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' }),
+ onProgress: (progress) => snapshots.push({ ...progress }),
+ });
+ orch.start(filePath);
+ const failed = await waitFor(snapshots, (progress) => progress.stage === 'failed');
+ expect(failed.errorCode).toBe(expected);
+ });
});
diff --git a/apps/desktop/src/main/plugin-publisher/host.ts b/apps/desktop/src/main/plugin-publisher/host.ts
index 71489f26df..fe5615f41b 100644
--- a/apps/desktop/src/main/plugin-publisher/host.ts
+++ b/apps/desktop/src/main/plugin-publisher/host.ts
@@ -18,7 +18,11 @@ 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 {
+ createPluginPublisherOrchestrator,
+ PluginPublisherOrchestrator,
+ type PluginPublisherSourceBinding,
+} from './orchestrator.js';
import { PLUGIN_MEMBER_PUBLISHER_GHOST_ID, type PluginPublisherProgress } from './types.js';
const log = createLogger('plugin-publisher');
@@ -150,13 +154,18 @@ function publisherIdentityKey(): string {
return identity ? `${identity.membershipId}:${identity.orgSlug}` : '';
}
-export function startPluginPublish(filePath: string, requester: WebContents | null = null) {
+export function startPluginPublish(
+ filePath: string,
+ requester: WebContents | null = null,
+ sourceBinding?: PluginPublisherSourceBinding,
+) {
const identity = currentPublisherIdentity();
if (!identity) {
throw new Error('需要组织身份才能发布插件');
}
log.info('plugin publish started');
return getPluginPublisherOrchestrator().start(filePath, {
+ ...(sourceBinding ? { sourceBinding } : {}),
confirm: (facts) => {
const ownerStamp = getActiveDataOwnerPushStamp();
const requesterId = requester && !requester.isDestroyed() ? requester.id : 0;
diff --git a/apps/desktop/src/main/plugin-publisher/orchestrator.ts b/apps/desktop/src/main/plugin-publisher/orchestrator.ts
index eab17e09c4..b2e09840f8 100644
--- a/apps/desktop/src/main/plugin-publisher/orchestrator.ts
+++ b/apps/desktop/src/main/plugin-publisher/orchestrator.ts
@@ -55,6 +55,13 @@ export interface PluginPublisherOrchestratorDeps {
inspectGate?: { acquire(signal: AbortSignal): Promise<void>; release(): void };
}
+export interface PluginPublisherSourceBinding {
+ manifestId: string;
+ packageSha256: string;
+ /** Agent forge staging is released once this background transfer terminates. */
+ onTerminal?: () => void | Promise<void>;
+}
+
interface TransferRecord {
transferId: string;
uploadId: string | null;
@@ -138,6 +145,7 @@ export class PluginPublisherOrchestrator {
filePath: string,
extras?: {
confirm?: PluginPublisherOrchestratorDeps['confirm'];
+ sourceBinding?: PluginPublisherSourceBinding;
},
): PluginPublisherStartResult {
const transferId = randomUUID();
@@ -156,7 +164,11 @@ export class PluginPublisherOrchestrator {
run: Promise.resolve(),
};
this.transfers.set(transferId, record);
- record.run = this.run(record, extras?.confirm ?? this.deps.confirm).catch(() => undefined);
+ record.run = this.run(
+ record,
+ extras?.confirm ?? this.deps.confirm,
+ extras?.sourceBinding,
+ ).catch(() => undefined);
this.emit(record);
return { transferId, uploadId: null };
}
@@ -224,6 +236,7 @@ export class PluginPublisherOrchestrator {
private async run(
record: TransferRecord,
confirm: PluginPublisherOrchestratorDeps['confirm'],
+ sourceBinding?: PluginPublisherSourceBinding,
): Promise<void> {
const signal = record.controller.signal;
let handle: fsPromises.FileHandle | null = null;
@@ -245,6 +258,10 @@ export class PluginPublisherOrchestrator {
} finally {
this.inspectGate.release();
}
+ if (sourceBinding && inspected.ghostId !== sourceBinding.manifestId) {
+ this.fail(record, 'PUBLISH_PACKAGE_ID_MISMATCH', '打包票据与待发布插件 id 不一致');
+ return;
+ }
handle = await fsPromises.open(record.filePath, fs.constants.O_RDONLY);
const stat = await handle.stat();
if (!stat.isFile()) {
@@ -296,12 +313,25 @@ export class PluginPublisherOrchestrator {
this.fail(record, 'UPLOAD_SIZE_MISMATCH', '文件在校验期间被修改,请重新选择');
return;
}
+ if (sourceBinding && digest.sha256 !== sourceBinding.packageSha256) {
+ this.fail(record, 'PUBLISH_PACKAGE_SHA256_MISMATCH', '待发布插件字节已不是本次打包产物');
+ return;
+ }
this.update(record, { stage: 'preparing', totalBytes: digest.sizeBytes });
- const prepared = await this.deps.api.prepare({
- sizeBytes: digest.sizeBytes,
- sha256: digest.sha256,
- });
+ let prepared: Awaited<ReturnType<PluginPublisherApi['prepare']>>;
+ try {
+ prepared = await this.deps.api.prepare({
+ sizeBytes: digest.sizeBytes,
+ sha256: digest.sha256,
+ });
+ } catch (error) {
+ if (isUnsupportedPrepareEndpoint(error)) {
+ this.fail(record, 'PUBLISH_UNSUPPORTED', '当前企业服务端不支持成员发布');
+ return;
+ }
+ throw error;
+ }
this.update(record, { uploadId: prepared.uploadId, stage: 'uploading', bytesSent: 0 });
const putFile = this.deps.putFile ?? putLocalFile;
@@ -360,6 +390,11 @@ export class PluginPublisherOrchestrator {
this.fail(record, 'INTERNAL', '发布失败');
} finally {
await handle?.close().catch(() => undefined);
+ try {
+ await sourceBinding?.onTerminal?.();
+ } catch {
+ // Cleanup must never rewrite the already-final transfer outcome.
+ }
}
}
@@ -550,6 +585,14 @@ function mapPublisherApiMessage(error: PluginPublisherApiError): string {
return '发布请求失败';
}
+function isUnsupportedPrepareEndpoint(error: unknown): boolean {
+ if (!(error instanceof PluginPublisherApiError)) return false;
+ if (error.status === 404 || error.status === 405) return true;
+ // A legacy ingress without this route can surface an HTML 503. Redacted
+ // structured service failures retain their own business codes.
+ return error.status === 503 && error.code === 'INTERNAL_ERROR';
+}
+
export function createPluginPublisherOrchestrator(
deps: PluginPublisherOrchestratorDeps,
): PluginPublisherOrchestrator {
diff --git a/packages/cindy-tools/src/__tests__/ghostMcp.test.ts b/packages/cindy-tools/src/__tests__/ghostMcp.test.ts
index 10fef62f90..abff598006 100644
--- a/packages/cindy-tools/src/__tests__/ghostMcp.test.ts
+++ b/packages/cindy-tools/src/__tests__/ghostMcp.test.ts
@@ -4,6 +4,7 @@ import { GHOST_MANIFEST_SUMMARY_MAX_CHARS } from "@cindy/plugin-protocol";
import {
createCindyGhostsMcpServer,
extractAgentToolUseId,
+ ghostForgePublishInputSchema,
ghostSetupPlanInputSchema,
handleForgeGuide,
handleForgePack,
@@ -1451,8 +1452,9 @@ describe("cindy_ghosts · ghost_forge(锻造)", () => {
version: "1.0.0",
cindyPath: "x-1.0.0.cindy",
});
- expect(parsePayload(okResult).cindyPath.includes("/")).toBe(false);
- expect(parsePayload(okResult).cindyPath.includes("\\")).toBe(false);
+ const cindyPath = String(parsePayload(okResult).cindyPath);
+ expect(cindyPath.includes("/")).toBe(false);
+ expect(cindyPath.includes("\\")).toBe(false);
const failed = await handleForgePack(
fakeDeps({
@@ -1471,8 +1473,12 @@ describe("cindy_ghosts · ghost_forge(锻造)", () => {
});
});
- it("forge_pack 仅在传入时把 icon_source 映射给 host", async () => {
- const requests: Array<{ dir: string; iconSource?: string }> = [];
+ it("forge_pack 仅在传入时把 icon_source / intent 映射给 host", async () => {
+ const requests: Array<{
+ dir: string;
+ iconSource?: string;
+ intent?: "install" | "publish";
+ }> = [];
const deps = fakeDeps({
forgePack: async (request) => {
requests.push(request);
@@ -1492,6 +1498,7 @@ describe("cindy_ghosts · ghost_forge(锻造)", () => {
icon_source: `cindy-media://blobs/${"a".repeat(64)}.png`,
});
await handleForgePack(deps, { dir: "/src/default" });
+ await handleForgePack(deps, { dir: "/src/publish", intent: "publish" });
expect(requests).toEqual([
{
@@ -1499,12 +1506,14 @@ describe("cindy_ghosts · ghost_forge(锻造)", () => {
iconSource: `cindy-media://blobs/${"a".repeat(64)}.png`,
},
{ dir: "/src/default" },
+ { dir: "/src/publish", intent: "publish" },
]);
});
- it("forge_publish 立即透传 transferId;失败标 isError", async () => {
+ it("forge_publish 只透传 opaque token 并立即返回 transferId;失败标 isError", async () => {
+ const requests: Array<{ token: string }> = [];
const okResult = await handleForgePublish(fakeDeps(), {
- file: "/tmp/x.cindy",
+ token: "publish-token-1",
});
expect(parsePayload(okResult)).toMatchObject({
ok: true,
@@ -1513,19 +1522,39 @@ describe("cindy_ghosts · ghost_forge(锻造)", () => {
const failed = await handleForgePublish(
fakeDeps({
- forgePublish: async () => ({
- ok: false,
- errorCode: "NOT_ORG_MEMBER",
- message: "需要组织身份",
- }),
+ forgePublish: async (request) => {
+ requests.push(request);
+ return {
+ ok: false,
+ errorCode: "NOT_ORG_MEMBER",
+ message: "需要组织身份",
+ };
+ },
}),
- { file: "/tmp/x.cindy" },
+ { token: "publish-token-2" },
);
expect(failed.isError).toBe(true);
expect(parsePayload(failed)).toMatchObject({
ok: false,
errorCode: "NOT_ORG_MEMBER",
});
+ expect(requests).toEqual([{ token: "publish-token-2" }]);
+ });
+
+ it("forge_publish schema rejects the old file path shape before Host and accepts token only", () => {
+ // Excludes a runtime-only path rejection: the public MCP schema itself has no file field.
+ expect(
+ ghostForgePublishInputSchema.safeParse({ file: "/tmp/arbitrary.cindy" }).success,
+ ).toBe(false);
+ expect(
+ ghostForgePublishInputSchema.safeParse({
+ token: "publish-token-1",
+ file: "/tmp/arbitrary.cindy",
+ }).success,
+ ).toBe(false);
+ expect(
+ ghostForgePublishInputSchema.safeParse({ token: "publish-token-1" }),
+ ).toMatchObject({ success: true });
});
it("forge_publish_status 透传后台阶段", async () => {
@@ -1539,7 +1568,7 @@ describe("cindy_ghosts · ghost_forge(锻造)", () => {
});
});
- it("forge_pack 描述明确图片工具结果字段", () => {
+ it("forge_pack / publish 描述明确图片字段、发布意图与组织身份限制", () => {
const server = createCindyGhostsMcpServer(fakeDeps()) as unknown as {
_registeredTools: Record<string, { description?: string } | undefined>;
};
@@ -1547,6 +1576,11 @@ describe("cindy_ghosts · ghost_forge(锻造)", () => {
expect(description).toContain("xdt_image_url");
expect(description).toContain("xdt_image_urls");
expect(description).toContain("icon_source");
+ expect(description).toContain("intent=publish");
+ const publishDescription = server._registeredTools.ghost_forge_publish?.description ?? "";
+ expect(publishDescription).toContain("publishToken");
+ expect(publishDescription).toContain("仅企业组织成员可用");
+ expect(publishDescription).toContain("个人账号不可用");
});
});
diff --git a/packages/cindy-tools/src/ghost/mcpServer.ts b/packages/cindy-tools/src/ghost/mcpServer.ts
index 54bbd642f3..9dbbec4398 100644
--- a/packages/cindy-tools/src/ghost/mcpServer.ts
+++ b/packages/cindy-tools/src/ghost/mcpServer.ts
@@ -122,21 +122,22 @@ const D_GHOST_FORGE_SCAFFOLD = [
].join("\n");
const D_GHOST_FORGE_PACK = [
- "把一个插件源码目录校验并打包成 .cindy,随后主机会弹出装入确认框(同 id 已装则显示",
- '"更新 vX → vY")——装不装永远由用户在弹窗上决定,本工具不会私自装入。',
+ "把一个插件源码目录校验并打包成 .cindy。缺省 intent=install,随后主机会弹出装入确认框",
+ '(同 id 已装则显示"更新 vX → vY");intent=publish 时不装入,只返回一次性 publishToken。',
"dir 传源码目录的绝对路径(目录里须有 ghost.json;打包自动跳过 .git / node_modules /",
"隐藏文件 / *.cindy)。仅当用户明确选择 AI 生成图标时,可把图片工具结果的",
"xdt_image_url 取单张地址;若只有 xdt_image_urls 则取数组第一项,再把得到的 cindy-media:// 地址传给 icon_source;主机会 best-effort 嵌入,失败保留默认图标继续打包。",
"失败返回结构化错误(MANIFEST_INVALID 等,message 带具体原因),",
- "按 message 修正源码后重新打包即可。打包成功 ≠ 已装入:告知用户去点确认框。",
+ "按 message 修正源码后重新打包即可。install 打包成功 ≠ 已装入:告知用户去点确认框;publish 不会触发装入。",
].join("\n");
const D_GHOST_FORGE_PUBLISH = [
- "把一个本机 .cindy 插件包发布到当前登录组织。file 传绝对路径。",
+ "把 ghost_forge_pack(intent=publish) 刚打出的确切插件包发布到当前登录组织。token 传 pack 返回的一次性 publishToken,不能传文件路径。",
+ "仅企业组织成员可用;个人账号不可用。",
"本工具立即返回 transferId(以及稍后才有的 uploadId),传输在后台跑;",
"用 ghost_forge_publish_status 查阶段与结果。不要把它和 ghost_forge_pack 混成一次调用:",
"打包失败和发布失败语义不同。主机会弹出确认屏(组织 / 插件 id / 版本 / 大小),",
- "用户确认后才真正开传。立即失败只有 NOT_ORG_MEMBER / INTERNAL;传输开始后的失败看 status 的 message,",
+ "用户确认后才真正开传。立即失败会返回结构化 code;传输开始后的失败看 status 的 message,",
"不要按固定枚举分支。",
].join("\n");
@@ -147,6 +148,15 @@ const D_GHOST_FORGE_PUBLISH_STATUS = [
"不要按固定枚举分支。",
].join("\n");
+export const ghostForgePublishInputSchema = z
+ .object({
+ token: z
+ .string()
+ .min(1)
+ .describe("ghost_forge_pack(intent=publish) 返回的一次性 publishToken"),
+ })
+ .strict();
+
/**
* 花名册 recall 召回线索(whenToUse 优先、description 回落)的截断上限,
* 与 manifest 的 description / whenToUse 校验同源。
@@ -1028,11 +1038,12 @@ export async function handleForgeScaffold(
/** ghost_forge_pack 的 handler 主体(导出供单测)。 */
export async function handleForgePack(
deps: CindyGhostsMcpDeps,
- input: { dir: string; icon_source?: string },
+ input: { dir: string; icon_source?: string; intent?: "install" | "publish" },
): Promise<McpTextResult> {
try {
const result = await deps.forgePack({
dir: input.dir,
+ ...(input.intent !== undefined ? { intent: input.intent } : {}),
...(input.icon_source !== undefined ? { iconSource: input.icon_source } : {}),
});
if (!result.ok) {
@@ -1058,10 +1069,10 @@ export async function handleForgePack(
/** ghost_forge_publish 的 handler 主体(导出供单测)。 */
export async function handleForgePublish(
deps: CindyGhostsMcpDeps,
- input: { file: string },
+ input: { token: string },
): Promise<McpTextResult> {
try {
- const result = await deps.forgePublish({ file: input.file });
+ const result = await deps.forgePublish({ token: input.token });
if (!result.ok) {
deps.logger?.warn("ghost_forge_publish rejected", {
errorCode: result.errorCode,
@@ -1282,15 +1293,19 @@ export function createCindyGhostsMcpServer(
.describe(
"可选;仅当用户明确选择 AI 生成图标时,传图片工具结果的 xdt_image_url,或 xdt_image_urls 数组第一项(cindy-media:// 地址);失败会保留默认图标继续打包",
),
+ intent: z
+ .enum(["install", "publish"])
+ .optional()
+ .describe("缺省 install:弹装入确认;publish:不装入,返回一次性发布票据"),
},
async (input) => handleForgePack(deps, input),
);
- server.tool(
+ server.registerTool(
"ghost_forge_publish",
- D_GHOST_FORGE_PUBLISH,
{
- file: z.string().describe("要发布的 .cindy 包绝对路径"),
+ description: D_GHOST_FORGE_PUBLISH,
+ inputSchema: ghostForgePublishInputSchema,
},
async (input) => handleForgePublish(deps, input),
);
diff --git a/packages/cindy-tools/src/types.ts b/packages/cindy-tools/src/types.ts
index 965f3aab5b..3938dd0979 100644
--- a/packages/cindy-tools/src/types.ts
+++ b/packages/cindy-tools/src/types.ts
@@ -237,19 +237,26 @@ export type CindyForgePackResult =
ok: true;
/**
* 作者副本的文件名提示(如 `demo-1.0.0.cindy`),不可用于访问。
- * 不是绝对路径,也不是 Host staging 路径;装入走确认框,不要拿这个字段去读盘。
+ * 不是绝对路径,也不是 Host staging 路径;不要拿这个字段去读盘或发布。
*/
cindyPath: string;
id: string;
name: string;
version: string;
- /** 已弹出装入/更新确认框,等用户决定;装不装永远由用户点头。 */
+ /** 仅 intent=publish 返回;一次性、不可解析的 Host 发布票据。 */
+ publishToken?: string;
+ /** 下一步说明:install 等用户确认,publish 提示消费一次性票据。 */
note: string;
}
| { ok: false; errorCode: CindyForgePackErrorCode; message: string };
/** ghost_forge_publish 立即返回时的失败分类。传输开始后的失败走 status.errorCode。 */
-export type CindyForgePublishErrorCode = 'NOT_ORG_MEMBER' | 'INTERNAL';
+export type CindyForgePublishErrorCode =
+ | 'NOT_ORG_MEMBER'
+ | 'SESSION_BOUNDARY_PENDING'
+ | 'PUBLISH_TOKEN_INVALID'
+ | 'PUBLISH_TOKEN_OWNER_MISMATCH'
+ | 'INTERNAL';
export type CindyForgePublishResult =
| {
@@ -424,12 +431,12 @@ export interface CindyGhostsMcpDeps {
description?: string;
}): Promise<CindyForgeScaffoldResult>;
/**
- * 把一个源码目录校验 + 打包成 .cindy,并弹出与拖入/双击完全相同的
- * 装入(同 id 已装则更新)确认框——装不装永远由用户决定,agent 只能
- * 递到用户面前。
+ * 把一个源码目录校验 + 打包成 .cindy。缺省弹出与拖入/双击完全相同的
+ * 装入确认框;publish 意图只签发一次性发布票据,不触发装入。
*/
forgePack(request: {
dir: string;
+ intent?: 'install' | 'publish';
/**
* 用户明确选择 AI 图标后,由图片工具返回的 cindy-media 地址。Host
* best-effort 把它嵌入包内;失败保留源码里的默认图标,不阻塞打包。
@@ -437,10 +444,10 @@ export interface CindyGhostsMcpDeps {
iconSource?: string;
}): Promise<CindyForgePackResult>;
/**
- * 把一个本机 .cindy 包提交到当前组织发布。立即返回 transferId / uploadId,
- * 传输在后台跑;用 forgePublishStatus 查进度。
+ * 消费 forgePack(intent=publish) 签发的一次性票据,把该次打包的确切字节
+ * 提交到当前组织发布。立即返回 transferId / uploadId,传输在后台跑。
*/
- forgePublish(request: { file: string }): Promise<CindyForgePublishResult>;
+ forgePublish(request: { token: string }): Promise<CindyForgePublishResult>;
/** 查询一次后台发布传输的当前状态。 */
forgePublishStatus(request: { transferId: string }): Promise<CindyForgePublishStatusResult>;
logger?: {