@xiaohhhh1/canvas-agent 0.4.2 → 0.4.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/agent/codex.d.ts
CHANGED
|
@@ -9,9 +9,15 @@ type CodexRunOptions = {
|
|
|
9
9
|
onTurn?: (turnId: string) => void;
|
|
10
10
|
onFinish?: () => void;
|
|
11
11
|
};
|
|
12
|
+
export type CodexRunResult = {
|
|
13
|
+
ok: true;
|
|
14
|
+
} | {
|
|
15
|
+
ok: false;
|
|
16
|
+
error: string;
|
|
17
|
+
};
|
|
12
18
|
export { summarizeCodexThread } from "./codex-history.js";
|
|
13
19
|
/** 将 Codex turn 加入串行队列并等待执行完成。 */
|
|
14
|
-
export declare function runCodexTurn(prompt: string, emit: AgentEmit, attachments?: AgentAttachment[], options?: CodexRunOptions): Promise<
|
|
20
|
+
export declare function runCodexTurn(prompt: string, emit: AgentEmit, attachments?: AgentAttachment[], options?: CodexRunOptions): Promise<CodexRunResult>;
|
|
15
21
|
/** 中断当前线程正在执行的 Codex turn。 */
|
|
16
22
|
export declare function interruptCodexTurn(threadId?: string): Promise<boolean>;
|
|
17
23
|
/** 回复当前 app-server 的待处理权限请求。 */
|
package/dist/agent/codex.js
CHANGED
|
@@ -14,9 +14,9 @@ export { summarizeCodexThread } from "./codex-history.js";
|
|
|
14
14
|
/** 将 Codex turn 加入串行队列并等待执行完成。 */
|
|
15
15
|
export async function runCodexTurn(prompt, emit, attachments = [], options = {}) {
|
|
16
16
|
if (!prompt.trim())
|
|
17
|
-
return;
|
|
17
|
+
return { ok: false, error: "Codex prompt is empty" };
|
|
18
18
|
codexQueue = codexQueue.catch(() => undefined).then(() => runCodexTurnNow(prompt, emit, attachments, options));
|
|
19
|
-
await codexQueue;
|
|
19
|
+
return await codexQueue;
|
|
20
20
|
}
|
|
21
21
|
/** 中断当前线程正在执行的 Codex turn。 */
|
|
22
22
|
export async function interruptCodexTurn(threadId) {
|
|
@@ -115,10 +115,13 @@ async function runCodexTurnNow(prompt, emit, attachments, options) {
|
|
|
115
115
|
unmaterializedThreadIds.delete(threadId);
|
|
116
116
|
await app.startTurn(threadId, prompt, files, options.permissionMode || "request", options.onTurn);
|
|
117
117
|
}
|
|
118
|
+
return { ok: true };
|
|
118
119
|
}
|
|
119
120
|
catch (error) {
|
|
120
121
|
logger.error("Codex turn failed", error);
|
|
121
|
-
|
|
122
|
+
const message = errorMessage(error);
|
|
123
|
+
emit("agent_error", { message });
|
|
124
|
+
return { ok: false, error: message };
|
|
122
125
|
}
|
|
123
126
|
finally {
|
|
124
127
|
options.onFinish?.();
|
package/dist/server/mcp.js
CHANGED
|
@@ -3,6 +3,7 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
|
|
|
3
3
|
import { z } from "zod";
|
|
4
4
|
import { toolDescriptions, toolInputSchemas, toolNames } from "../canvas/schemas.js";
|
|
5
5
|
import { AGENT_PROMPT, loadConfig, VERSION } from "../config.js";
|
|
6
|
+
import { FLOW_C_SCRIPT_CHUNK_MAX } from "../workflow/constants.js";
|
|
6
7
|
/** 启动通过标准输入输出通信的 MCP 服务。 */
|
|
7
8
|
export async function startMcpServer() {
|
|
8
9
|
const config = loadConfig(true);
|
|
@@ -22,7 +23,7 @@ function registerWorkflowTools(server, config) {
|
|
|
22
23
|
inputSchema: { handoffId: z.string().uuid().describe("网站创建的脚本交接 ID") },
|
|
23
24
|
}, async ({ handoffId }) => workflowTool(config, `/agent/workflow/script-handoffs/${encodeURIComponent(handoffId)}/task`, { method: "GET" }));
|
|
24
25
|
server.registerTool("flow_c_submit_script_chunk", {
|
|
25
|
-
description:
|
|
26
|
+
description: `把本段独立完成的 Flow C 高质量脚本持久化回传给网站。每次 1–${FLOW_C_SCRIPT_CHUNK_MAX} 条;成功后再创作下一段。`,
|
|
26
27
|
inputSchema: {
|
|
27
28
|
handoffId: z.string().uuid().describe("脚本交接 ID"),
|
|
28
29
|
jobs: z.array(z.object({
|
|
@@ -30,7 +31,7 @@ function registerWorkflowTools(server, config) {
|
|
|
30
31
|
productIndex: z.number().int().nonnegative(),
|
|
31
32
|
sellingFormId: z.string().min(1).max(100),
|
|
32
33
|
script: z.string().min(40).max(20_000),
|
|
33
|
-
})).min(1).max(
|
|
34
|
+
})).min(1).max(FLOW_C_SCRIPT_CHUNK_MAX),
|
|
34
35
|
},
|
|
35
36
|
}, async ({ handoffId, jobs }) => workflowTool(config, `/agent/workflow/script-handoffs/${encodeURIComponent(handoffId)}/draft-chunks`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ jobs }) }));
|
|
36
37
|
}
|
|
@@ -9,6 +9,8 @@ type ScriptTask = {
|
|
|
9
9
|
requested_count: number;
|
|
10
10
|
product_quantities: number[];
|
|
11
11
|
instructions: string;
|
|
12
|
+
status: "pending" | "writing" | "ready";
|
|
13
|
+
received_ordinals: number[];
|
|
12
14
|
expires_at: string;
|
|
13
15
|
};
|
|
14
16
|
/** 本机持久化的 Flow C 控制器:脚本交给本机 Codex,视频直接落盘。 */
|
|
@@ -64,6 +66,7 @@ export declare class WorkflowManager {
|
|
|
64
66
|
submitScriptChunk(idValue: unknown, jobsValue: unknown): Promise<{
|
|
65
67
|
accepted: number;
|
|
66
68
|
received: number;
|
|
69
|
+
receivedOrdinals?: number[];
|
|
67
70
|
requestedCount: number;
|
|
68
71
|
status: string;
|
|
69
72
|
} & {
|
package/dist/workflow/manager.js
CHANGED
|
@@ -9,8 +9,8 @@ import { runCodexTurn, startCodexThread } from "../agent/codex.js";
|
|
|
9
9
|
import { CONFIG_DIR, ensureSiteWorkspace } from "../config.js";
|
|
10
10
|
import { logger } from "../utils/logger.js";
|
|
11
11
|
import { windowsPowerShellExecutable } from "../utils/windows.js";
|
|
12
|
+
import { FLOW_C_SCRIPT_CHUNK_MAX, FLOW_C_SCRIPT_CHUNK_SIZES } from "./constants.js";
|
|
12
13
|
const STATE_FILE = path.join(CONFIG_DIR, "workflow-state.json");
|
|
13
|
-
const SCRIPT_CHUNK_SIZE = 30;
|
|
14
14
|
const DOWNLOAD_POLL_MS = 10_000;
|
|
15
15
|
/** 本机持久化的 Flow C 控制器:脚本交给本机 Codex,视频直接落盘。 */
|
|
16
16
|
export class WorkflowManager {
|
|
@@ -76,6 +76,7 @@ export class WorkflowManager {
|
|
|
76
76
|
const data = await commerceJson(`${record.apiBase}/workflow-script-handoffs/${encodeURIComponent(record.id)}/task`, record.accessToken, "x-workflow-handoff-token");
|
|
77
77
|
const task = data.handoff;
|
|
78
78
|
record.requestedCount = Number(task.requested_count || 0);
|
|
79
|
+
record.receivedOrdinals = Array.isArray(task.received_ordinals) ? task.received_ordinals.map(Number).filter(Number.isInteger).sort((left, right) => left - right) : [];
|
|
79
80
|
record.expiresAt = task.expires_at;
|
|
80
81
|
record.updatedAt = now();
|
|
81
82
|
this.save();
|
|
@@ -84,15 +85,19 @@ export class WorkflowManager {
|
|
|
84
85
|
/** MCP 分段回传脚本,中心接口再次执行数量、产品索引和脚本完整性校验。 */
|
|
85
86
|
async submitScriptChunk(idValue, jobsValue) {
|
|
86
87
|
const record = this.scriptRecord(workflowId(idValue, "脚本交接 ID"));
|
|
87
|
-
if (!Array.isArray(jobsValue) || !jobsValue.length || jobsValue.length >
|
|
88
|
-
throw new Error(`每段必须包含 1–${
|
|
88
|
+
if (!Array.isArray(jobsValue) || !jobsValue.length || jobsValue.length > FLOW_C_SCRIPT_CHUNK_MAX)
|
|
89
|
+
throw new Error(`每段必须包含 1–${FLOW_C_SCRIPT_CHUNK_MAX} 条脚本`);
|
|
89
90
|
const jobs = jobsValue;
|
|
90
91
|
const data = await commerceJson(`${record.apiBase}/workflow-script-handoffs/${encodeURIComponent(record.id)}/draft-chunks`, record.accessToken, "x-workflow-handoff-token", { method: "POST", body: JSON.stringify({ jobs }) });
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
92
|
+
if (Array.isArray(data.receivedOrdinals))
|
|
93
|
+
record.receivedOrdinals = data.receivedOrdinals.map(Number).filter(Number.isInteger).sort((left, right) => left - right);
|
|
94
|
+
else {
|
|
95
|
+
const accepted = new Set(record.receivedOrdinals);
|
|
96
|
+
for (const job of jobs)
|
|
97
|
+
if (Number.isInteger(Number(job?.ordinal)))
|
|
98
|
+
accepted.add(Number(job.ordinal));
|
|
99
|
+
record.receivedOrdinals = [...accepted].sort((a, b) => a - b);
|
|
100
|
+
}
|
|
96
101
|
record.requestedCount = Number(data.requestedCount || record.requestedCount);
|
|
97
102
|
record.status = data.status === "ready" ? "complete" : "running";
|
|
98
103
|
record.message = data.status === "ready" ? `全部 ${record.requestedCount} 条高质量脚本已回传` : `已回传 ${data.received}/${data.requestedCount} 条脚本`;
|
|
@@ -212,28 +217,47 @@ export class WorkflowManager {
|
|
|
212
217
|
this.save();
|
|
213
218
|
}
|
|
214
219
|
while (record.receivedOrdinals.length < task.requested_count) {
|
|
215
|
-
const missing = missingOrdinals(task.requested_count, record.receivedOrdinals).slice(0, SCRIPT_CHUNK_SIZE);
|
|
216
|
-
if (!missing.length)
|
|
217
|
-
break;
|
|
218
220
|
let progressed = false;
|
|
219
|
-
|
|
221
|
+
let lastRange = "";
|
|
222
|
+
let lastError = "";
|
|
223
|
+
for (const [attemptIndex, chunkSize] of FLOW_C_SCRIPT_CHUNK_SIZES.entries()) {
|
|
224
|
+
const missing = missingOrdinals(task.requested_count, record.receivedOrdinals).slice(0, chunkSize);
|
|
225
|
+
if (!missing.length) {
|
|
226
|
+
progressed = true;
|
|
227
|
+
break;
|
|
228
|
+
}
|
|
229
|
+
lastRange = `${missing[0]}–${missing.at(-1)}`;
|
|
220
230
|
const before = record.receivedOrdinals.length;
|
|
221
231
|
record.attempts += 1;
|
|
222
232
|
record.message = `本机 Codex 正在写第 ${missing[0]}–${missing.at(-1)} 条(总计 ${task.requested_count} 条)`;
|
|
223
233
|
record.updatedAt = now();
|
|
224
234
|
this.save();
|
|
225
|
-
await runCodexTurn(scriptChunkPrompt(id, task, missing), this.emit, [], { threadId: record.threadId, cwd: workspace.workspacePath, permissionMode: "full", onThread: (threadId) => { record.threadId = threadId; this.save(); } });
|
|
235
|
+
const result = await runCodexTurn(scriptChunkPrompt(id, task, missing), this.emit, [], { threadId: record.threadId, cwd: workspace.workspacePath, permissionMode: "full", onThread: (threadId) => { record.threadId = threadId; this.save(); } });
|
|
236
|
+
await this.scriptTask(id);
|
|
226
237
|
progressed = record.receivedOrdinals.length > before;
|
|
227
|
-
if (
|
|
228
|
-
|
|
238
|
+
if (progressed)
|
|
239
|
+
break;
|
|
240
|
+
// Keep provider/client details out of the browser-facing state. The
|
|
241
|
+
// underlying Codex runner already records the technical error locally.
|
|
242
|
+
lastError = result.ok ? "Codex 未调用回传工具" : "Codex 本轮执行失败";
|
|
243
|
+
if (attemptIndex < FLOW_C_SCRIPT_CHUNK_SIZES.length - 1) {
|
|
244
|
+
const nextSize = FLOW_C_SCRIPT_CHUNK_SIZES[attemptIndex + 1];
|
|
245
|
+
record.message = `第 ${lastRange} 条未成功回传,正在换新会话并缩小为每段 ${nextSize} 条重试`;
|
|
246
|
+
const thread = await startCodexThread(this.emit, workspace.workspacePath, "full");
|
|
247
|
+
record.threadId = String(thread.id || "");
|
|
248
|
+
this.save();
|
|
249
|
+
}
|
|
229
250
|
}
|
|
230
251
|
if (!progressed)
|
|
231
|
-
throw new Error(`本机 Codex
|
|
252
|
+
throw new Error(`本机 Codex 已自动换会话并降级到每段 10 条,仍未回传第 ${lastRange} 条${lastError ? `(${lastError})` : ""},请点击重试`);
|
|
232
253
|
}
|
|
233
|
-
|
|
254
|
+
const finalTask = await this.scriptTask(id);
|
|
255
|
+
if (finalTask.status === "ready" && record.receivedOrdinals.length === task.requested_count) {
|
|
234
256
|
record.status = "complete";
|
|
235
257
|
record.message = `全部 ${task.requested_count} 条高质量脚本已回传`;
|
|
236
258
|
}
|
|
259
|
+
else
|
|
260
|
+
throw new Error(`中心校验尚未通过(${record.receivedOrdinals.length}/${task.requested_count} 条),请点击重试`);
|
|
237
261
|
}
|
|
238
262
|
catch (error) {
|
|
239
263
|
record.status = error instanceof ExpiredCapabilityError ? "expired" : "error";
|
|
@@ -364,9 +388,37 @@ class ExpiredCapabilityError extends Error {
|
|
|
364
388
|
function scriptChunkPrompt(id, task, ordinals) {
|
|
365
389
|
return `你正在后台处理“抖音小辉跨境工具”Flow C 脚本交接 ${id}。
|
|
366
390
|
必须使用 MCP 工具 flow_c_get_script_task 读取完整任务,再只创作 ordinal ${ordinals[0]} 到 ${ordinals.at(-1)}(精确列表:${ordinals.join(", ")})。
|
|
391
|
+
本段 productIndex 必须严格按此映射填写:${scriptProductAssignments(task.product_quantities, ordinals)}。不得凭产品名称猜测或把相邻产品编号混用。
|
|
367
392
|
脚本质量绝不能因批量而降低:每条都必须独立构思、完整、真实合规,严格遵守任务 instructions、产品图片顺序和 productIndex;使用目标市场 ${task.market} 的自然本地语言与偏快但清晰的 10 秒节奏。
|
|
393
|
+
用户没有指定带货方向时,不得随意只用一种泛化形式;必须按任务 instructions 中“已批准的创意方向”逐条做产品适配轮换。轮换必须按每个产品自己的序号连续计算,不能因 30/15/10 条分段、换会话或跨产品边界而从第一个方向重新开始;让同一产品在重复某一方向前优先覆盖其他适配方向。
|
|
368
394
|
写完后必须调用 flow_c_submit_script_chunk 一次回传这 ${ordinals.length} 条,handoffId=${id}。不要创建付费批次,不要调用供应商模型,不要在聊天输出大段 JSON。工具返回成功后仅简短结束。`;
|
|
369
395
|
}
|
|
396
|
+
function scriptProductAssignments(productQuantities, ordinals) {
|
|
397
|
+
const assignments = [];
|
|
398
|
+
let first = ordinals[0];
|
|
399
|
+
let previous = first;
|
|
400
|
+
let productIndex = productIndexForOrdinal(productQuantities, first);
|
|
401
|
+
for (const ordinal of ordinals.slice(1)) {
|
|
402
|
+
const nextProductIndex = productIndexForOrdinal(productQuantities, ordinal);
|
|
403
|
+
if (nextProductIndex !== productIndex || ordinal !== previous + 1) {
|
|
404
|
+
assignments.push(`${first}${first === previous ? "" : `–${previous}`} → productIndex ${productIndex}`);
|
|
405
|
+
first = ordinal;
|
|
406
|
+
productIndex = nextProductIndex;
|
|
407
|
+
}
|
|
408
|
+
previous = ordinal;
|
|
409
|
+
}
|
|
410
|
+
assignments.push(`${first}${first === previous ? "" : `–${previous}`} → productIndex ${productIndex}`);
|
|
411
|
+
return assignments.join(";");
|
|
412
|
+
}
|
|
413
|
+
function productIndexForOrdinal(productQuantities, ordinal) {
|
|
414
|
+
let lastOrdinal = 0;
|
|
415
|
+
for (const [productIndex, quantity] of productQuantities.entries()) {
|
|
416
|
+
lastOrdinal += Number(quantity);
|
|
417
|
+
if (ordinal <= lastOrdinal)
|
|
418
|
+
return productIndex;
|
|
419
|
+
}
|
|
420
|
+
return -1;
|
|
421
|
+
}
|
|
370
422
|
function publicScript(record) {
|
|
371
423
|
return { id: record.id, status: record.status, requestedCount: record.requestedCount, received: record.receivedOrdinals.length, threadId: record.threadId, message: record.message, expiresAt: record.expiresAt, updatedAt: record.updatedAt };
|
|
372
424
|
}
|