@evandu/super-pi 0.1.274 → 0.1.276

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.
Files changed (52) hide show
  1. package/agents/super-pi-documents/index.ts +16 -1
  2. package/agents/super-pi-task/core.ts +1 -1
  3. package/bin/render-presentation.ps1 +35 -0
  4. package/desktop/main.cjs +16 -9
  5. package/desktop/notifications.cjs +2 -1
  6. package/desktop/relaunch.cjs +5 -2
  7. package/desktop/restart-handoff.cjs +35 -0
  8. package/desktop/shell-entries.cjs +14 -2
  9. package/dist/.super-pi-check-inputs.json +4 -0
  10. package/dist/client/.super-pi-client-sources.json +26 -19
  11. package/dist/client/assets/CodeMirrorEditor-WFfkDO6N.js +2 -0
  12. package/dist/client/assets/{GitDiffEditor-CpoDDQrA.css → GitDiffEditor-DOFVNrEW.css} +1 -1
  13. package/dist/client/assets/GitDiffEditor-PPULzRIU.js +29 -0
  14. package/dist/client/assets/index-BjauxoWZ.js +350 -0
  15. package/dist/client/assets/index-CnNljc5p.css +1 -0
  16. package/dist/client/index.html +2 -2
  17. package/dist/server/agents.d.ts +1 -1
  18. package/dist/server/agents.js +10 -3
  19. package/dist/server/application/document-service.d.ts +134 -0
  20. package/dist/server/application/document-service.js +9 -0
  21. package/dist/server/application/run-service.d.ts +1 -0
  22. package/dist/server/application/run-service.js +33 -7
  23. package/dist/server/http-server.js +32 -3
  24. package/dist/server/length-continuation.d.ts +2 -9
  25. package/dist/server/length-continuation.js +10 -10
  26. package/dist/server/pi-session-events.js +3 -1
  27. package/dist/server/presentations/brief.d.ts +49 -0
  28. package/dist/server/presentations/brief.js +132 -0
  29. package/dist/server/presentations/inspect.d.ts +15 -0
  30. package/dist/server/presentations/inspect.js +30 -0
  31. package/dist/server/presentations/native.d.ts +8 -0
  32. package/dist/server/presentations/native.js +33 -0
  33. package/dist/server/presentations/render.d.ts +16 -0
  34. package/dist/server/presentations/render.js +152 -0
  35. package/dist/server/presentations/service.d.ts +176 -0
  36. package/dist/server/presentations/service.js +155 -0
  37. package/dist/server/runtime.js +3 -2
  38. package/dist/server/turn-failure.d.ts +2 -0
  39. package/dist/server/turn-failure.js +15 -1
  40. package/dist/shared/message-source-link.d.ts +1 -0
  41. package/dist/shared/message-source-link.js +4 -0
  42. package/dist/shared/output-recovery.d.ts +4 -0
  43. package/dist/shared/output-recovery.js +6 -0
  44. package/dist/shared/workspace-file-preview.d.ts +1 -1
  45. package/dist/shared/workspace-file-preview.js +2 -0
  46. package/package.json +4 -1
  47. package/skills/presentation/SKILL.md +23 -1
  48. package/skills/presentation/references/spec.md +15 -0
  49. package/dist/client/assets/CodeMirrorEditor-DjMbNm7l.js +0 -2
  50. package/dist/client/assets/GitDiffEditor-Cwim9Ua1.js +0 -29
  51. package/dist/client/assets/index-BL9o4WZN.js +0 -350
  52. package/dist/client/assets/index-D1qJmoVY.css +0 -1
@@ -8,9 +8,9 @@
8
8
  <link rel="alternate icon" href="/favicon.ico" />
9
9
  <link rel="apple-touch-icon" href="/favicon.svg" />
10
10
  <title>Super Pi</title>
11
- <script type="module" crossorigin src="/assets/index-BL9o4WZN.js"></script>
11
+ <script type="module" crossorigin src="/assets/index-BjauxoWZ.js"></script>
12
12
  <link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-XKyaHtl9.js">
13
- <link rel="stylesheet" crossorigin href="/assets/index-D1qJmoVY.css">
13
+ <link rel="stylesheet" crossorigin href="/assets/index-CnNljc5p.css">
14
14
  </head>
15
15
  <body>
16
16
  <div id="root"></div>
@@ -38,7 +38,7 @@ type Frontmatter = Record<string, unknown>;
38
38
  */
39
39
  export declare const PI_TOOL_NAMES: readonly ["read", "bash", "powershell", "edit", "write", "grep", "find", "ls", "codemode", "tool_search", "list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource"];
40
40
  /** Tools shipped by this package. Authors must be able to explicitly deny host extras. */
41
- export declare const SUPER_PI_TOOL_NAMES: readonly ["task", "todowrite", "workflow", "run_async", "worktree", "scheduled_task", "project", "question", "tool_register", "tool_shortcut", "tool_remove", "memory", "skill_manage", "session_search", "session_spawn", "session_status", "session_dispatch", "session_stop", "session_report", "session_stop_subtree", "session_remove", "session_reminder", "knowledge_search", "knowledge_import", "document_read", "document_write", "web_search", "web_fetch", "feishu_doc_read", "feishu_doc_write"];
41
+ export declare const SUPER_PI_TOOL_NAMES: readonly ["task", "todowrite", "workflow", "run_async", "worktree", "scheduled_task", "project", "question", "tool_register", "tool_shortcut", "tool_remove", "memory", "skill_manage", "session_search", "session_spawn", "session_status", "session_dispatch", "session_stop", "session_report", "session_stop_subtree", "session_remove", "session_reminder", "knowledge_search", "knowledge_import", "document_read", "document_write", "presentation_create", "presentation_read", "presentation_edit", "presentation_render", "web_search", "web_fetch", "feishu_doc_read", "feishu_doc_write"];
42
42
  /**
43
43
  * Whether a name can be a real Pi tool. A name is real if it is one of `PI_TOOL_NAMES`, an MCP
44
44
  * server tool, or a PATTERN.
@@ -43,7 +43,7 @@ export const SUPER_PI_TOOL_NAMES = [
43
43
  "memory", "skill_manage", "session_search",
44
44
  "session_spawn", "session_status", "session_dispatch", "session_stop", "session_report", "session_stop_subtree", "session_remove", "session_reminder",
45
45
  "knowledge_search", "knowledge_import",
46
- "document_read", "document_write", "web_search", "web_fetch", "feishu_doc_read", "feishu_doc_write",
46
+ "document_read", "document_write", "presentation_create", "presentation_read", "presentation_edit", "presentation_render", "web_search", "web_fetch", "feishu_doc_read", "feishu_doc_write",
47
47
  ];
48
48
  const KNOWN_TOOL_NAMES = [...PI_TOOL_NAMES, ...SUPER_PI_TOOL_NAMES];
49
49
  const PI_TOOL_NAME_SET = new Set(KNOWN_TOOL_NAMES);
@@ -249,6 +249,13 @@ function unquote(value) {
249
249
  return value.slice(1, -1);
250
250
  return value;
251
251
  }
252
+ /** New artifact writers must not widen an existing read-only or document-write-denied role. */
253
+ function presentationWriteDenials(tools, options) {
254
+ if (!tools || typeof tools !== "object")
255
+ return [];
256
+ const readOnly = tools["*"] === false && !["write", "edit", "bash", "powershell", "document_write"].some(name => tools[name] === true);
257
+ return ["presentation_create", "presentation_edit"].filter(name => options.extraAllowedTools?.includes(name) && tools[name] !== true && (tools.document_write === false || readOnly));
258
+ }
252
259
  /**
253
260
  * The Pi CLI flags an agent's `tools` map becomes. Returned flat so the caller can push them into the
254
261
  * spawn argv in order, and so a test can assert on the exact list.
@@ -268,7 +275,7 @@ function unquote(value) {
268
275
  * see a schema for it. Naming a tool on the allowlist also activates it (agent-session.ts:3569-3574).
269
276
  */
270
277
  export function toolFlags(tools, options = {}) {
271
- const denied = new Set((options.denyTools ?? []).filter((name) => name !== ""));
278
+ const denied = new Set([...(options.denyTools ?? []), ...presentationWriteDenials(tools, options)].filter((name) => name !== ""));
272
279
  // An agent with no `tools:` map runs on Pi's own default set, so there is nothing to translate - but a
273
280
  // DENY inherited from a parent still has to become an explicit exclusion, because there is no allowlist
274
281
  // here to drop the name from.
@@ -330,7 +337,7 @@ export function deniesAllTools(tools) {
330
337
  * do for every shape of `tools:` map.
331
338
  */
332
339
  export function toolSelection(tools, options = {}) {
333
- const denied = new Set((options.denyTools ?? []).filter((name) => name !== ""));
340
+ const denied = new Set([...(options.denyTools ?? []), ...presentationWriteDenials(tools, options)].filter((name) => name !== ""));
334
341
  // No map at all is Pi's own default set. An inherited deny still has to become an exclusion, because
335
342
  // there is no allowlist here to drop the name from.
336
343
  if (!tools || typeof tools !== "object") {
@@ -22,6 +22,140 @@ export declare const MAX_DOCUMENT_REQUEST_BYTES: number;
22
22
  export declare class DocumentService {
23
23
  private readonly store;
24
24
  constructor(store: Store);
25
+ presentation(conversationId: string, body: Record<string, unknown>): Promise<{
26
+ version: 1;
27
+ etag: string;
28
+ operation: string;
29
+ sourceHash: string;
30
+ title: string;
31
+ verification: "layout-only" | "native-office";
32
+ renderer: string;
33
+ nativeReason?: string;
34
+ inspection: Awaited<ReturnType<typeof import("../presentations/inspect.js").inspectPptx>>;
35
+ contactSheets: {
36
+ asset: string;
37
+ hash: string;
38
+ }[];
39
+ warnings: {
40
+ slideId: string;
41
+ elementId: string;
42
+ message: string;
43
+ }[];
44
+ baseline?: {
45
+ path: string;
46
+ etag: string;
47
+ };
48
+ slides: {
49
+ id: string;
50
+ title: string;
51
+ notes: string;
52
+ asset: string;
53
+ hash: string;
54
+ }[];
55
+ source: import("../presentations/brief.js").PresentationSource;
56
+ path: string;
57
+ contactSheetPaths: string[];
58
+ link: string;
59
+ } | {
60
+ version: 1;
61
+ etag: string;
62
+ operation: string;
63
+ sourceHash: string;
64
+ title: string;
65
+ verification: "layout-only" | "native-office";
66
+ renderer: string;
67
+ nativeReason?: string;
68
+ inspection: Awaited<ReturnType<typeof import("../presentations/inspect.js").inspectPptx>>;
69
+ contactSheets: {
70
+ asset: string;
71
+ hash: string;
72
+ }[];
73
+ slides: {
74
+ id: string;
75
+ title: string;
76
+ notes: string;
77
+ asset: string;
78
+ hash: string;
79
+ }[];
80
+ warnings: {
81
+ slideId: string;
82
+ elementId: string;
83
+ message: string;
84
+ }[];
85
+ baseline?: {
86
+ path: string;
87
+ etag: string;
88
+ };
89
+ path: string;
90
+ contactSheetPaths: string[];
91
+ reused: boolean;
92
+ link: string;
93
+ } | {
94
+ version: 1;
95
+ etag: string;
96
+ operation: string;
97
+ sourceHash: string;
98
+ title: string;
99
+ verification: "layout-only" | "native-office";
100
+ renderer: string;
101
+ nativeReason?: string;
102
+ inspection: Awaited<ReturnType<typeof import("../presentations/inspect.js").inspectPptx>>;
103
+ contactSheets: {
104
+ asset: string;
105
+ hash: string;
106
+ }[];
107
+ slides: {
108
+ id: string;
109
+ title: string;
110
+ notes: string;
111
+ asset: string;
112
+ hash: string;
113
+ }[];
114
+ warnings: {
115
+ slideId: string;
116
+ elementId: string;
117
+ message: string;
118
+ }[];
119
+ baseline?: {
120
+ path: string;
121
+ etag: string;
122
+ };
123
+ path: string;
124
+ bytes: number;
125
+ contactSheetPaths: string[];
126
+ link: string;
127
+ } | {
128
+ path: string;
129
+ etag: string;
130
+ verification: "layout-only" | "native-office";
131
+ renderer: string;
132
+ nativeReason: string | undefined;
133
+ inspection: {
134
+ slides: number;
135
+ notes: number;
136
+ nativeCharts: number;
137
+ nativeTables: number;
138
+ editableTextShapes: number;
139
+ embeddedWorkbooks: number;
140
+ canvasInches: {
141
+ width: number;
142
+ height: number;
143
+ } | undefined;
144
+ relationships: string;
145
+ verification: string;
146
+ };
147
+ warnings: {
148
+ slideId: string;
149
+ elementId: string;
150
+ message: string;
151
+ }[];
152
+ sheet: number;
153
+ totalSheets: number;
154
+ images: {
155
+ mimeType: string;
156
+ data: string;
157
+ }[];
158
+ }>;
25
159
  /**
26
160
  * The workspace a conversation works in, taken from the store.
27
161
  *
@@ -2,6 +2,8 @@ import { mkdir, stat, writeFile } from "node:fs/promises";
2
2
  import { dirname, extname } from "node:path";
3
3
  import { buildDocument, documentFormatOf, DocumentError, extractText } from "../documents.js";
4
4
  import { fileEtag, resolveInsideRoot } from "../files.js";
5
+ import { resolveFileCwd } from "../session-cwd.js";
6
+ import { presentationTool } from "../presentations/service.js";
5
7
  /**
6
8
  * The largest request the document endpoint accepts.
7
9
  *
@@ -26,6 +28,13 @@ export class DocumentService {
26
28
  constructor(store) {
27
29
  this.store = store;
28
30
  }
31
+ async presentation(conversationId, body) {
32
+ const conversation = this.store.snapshot().conversations.find(item => item.id === conversationId);
33
+ if (!conversation?.workspaceId)
34
+ throw new Error("会话或工作区不存在");
35
+ const root = await resolveFileCwd(this.workspacePath(conversationId), conversation.cwd ?? "");
36
+ return presentationTool(root, body);
37
+ }
29
38
  /**
30
39
  * The workspace a conversation works in, taken from the store.
31
40
  *
@@ -409,6 +409,7 @@ export declare class RunService {
409
409
  enqueueAndRun(conversationId: string, content: string, images?: MessageImage[], attachments?: Message["attachments"], clientId?: string, mode?: MessageDeliveryMode, onAccepted?: () => void): Promise<void>;
410
410
  enqueueReminder(conversationId: string, note: string): Promise<void>;
411
411
  private enqueueMessage;
412
+ private recoverOutputLimit;
412
413
  /**
413
414
  * Steers a queued message into the in-flight turn.
414
415
  */
@@ -2109,14 +2109,10 @@ export class RunService {
2109
2109
  if (isLengthExceededError(error)) {
2110
2110
  const used = this.lengthContinuations.get(conversation.id) ?? 0;
2111
2111
  if (used < MAX_LENGTH_CONTINUATIONS && !controller.signal.aborted) {
2112
- this.lengthContinuations.set(conversation.id, used + 1);
2113
- console.warn(`Super Pi turn was truncated by output limit (${used + 1}/${MAX_LENGTH_CONTINUATIONS}); auto-continuing silently.`);
2114
- const lastAssistant = conversation.messages.filter((m) => m.role === "assistant").pop();
2115
- const continuationPrompt = buildLengthContinuationPrompt(lastAssistant);
2116
- // Auto continue without exposing warning banner to user
2112
+ // Read the current persisted turn, not the detached snapshot from before streaming.
2117
2113
  queueMicrotask(() => {
2118
- void this.enqueueAndRunAsAgent(conversation.id, continuationPrompt).catch((contErr) => {
2119
- console.warn("Super Pi auto-continuation dispatch error:", describeThrownWithStack(contErr));
2114
+ void this.recoverOutputLimit(conversation.id, controller).catch(recoveryError => {
2115
+ console.warn("Super Pi output recovery failed:", describeThrownWithStack(recoveryError));
2120
2116
  });
2121
2117
  });
2122
2118
  return;
@@ -2145,6 +2141,36 @@ export class RunService {
2145
2141
  this.broadcaster.broadcastState();
2146
2142
  }
2147
2143
  }
2144
+ async recoverOutputLimit(conversationId, controller) {
2145
+ while (!controller.signal.aborted) {
2146
+ const used = this.lengthContinuations.get(conversationId) ?? 0;
2147
+ const current = this.store.conversation(conversationId);
2148
+ if (!current || current.archivedAt)
2149
+ return;
2150
+ const assistant = current.messages.filter(message => message.role === "assistant").at(-1);
2151
+ if (used >= MAX_LENGTH_CONTINUATIONS) {
2152
+ this.lengthContinuations.delete(conversationId);
2153
+ const hasAnswer = typeof assistant?.content === "string" && assistant.content.trim();
2154
+ await this.store.setStatus(conversationId, "idle");
2155
+ await this.store.setWarningReason(conversationId, hasAnswer
2156
+ ? "模型多次达到输出额度上限,自动恢复后仍未完成。可以继续任务,或降低思考等级后重试。"
2157
+ : "模型在产生可见回答前耗尽输出额度,自动恢复未成功。额度可能用于推理或未完成的工具参数;请重试、降低思考等级或更换模型。");
2158
+ this.broadcaster.broadcastState();
2159
+ return;
2160
+ }
2161
+ this.lengthContinuations.set(conversationId, used + 1);
2162
+ try {
2163
+ await this.enqueueAndRunAsAgent(conversationId, buildLengthContinuationPrompt(assistant));
2164
+ return;
2165
+ }
2166
+ catch (error) {
2167
+ if (!isLengthExceededError(error)) {
2168
+ console.warn("Super Pi auto-continuation dispatch error:", describeThrownWithStack(error));
2169
+ return;
2170
+ }
2171
+ }
2172
+ }
2173
+ }
2148
2174
  /**
2149
2175
  * Steers a queued message into the in-flight turn.
2150
2176
  */
@@ -38,6 +38,7 @@ import { updateIsActive } from "../shared/update-status.js";
38
38
  import { FileIndex, refreshWorkspaceIndex } from "./file-index.js";
39
39
  import { ensureNameIndex, QUICK_OPEN_PAGE_SIZE, recordWorkspacePath } from "./file-name-index.js";
40
40
  import { resolveFileCwd, sessionScopeKey, workspacePathFromSession } from "./session-cwd.js";
41
+ import { presentationAsset, readPresentation } from "./presentations/service.js";
41
42
  import { explorerInternalPath, explorerPath, inspectWorkspaceUpload, listWorkspaceTrash, MAX_WORKSPACE_UPLOAD_BYTES, mutateWorkspaceTree, serializeWorkspaceWrite, uploadWorkspaceFile } from "./workspace-file-operations.js";
42
43
  import { readWorkspaceDocumentPreview, respondWithWorkspaceFile } from "./workspace-file-response.js";
43
44
  import { createExplicitFileOpen } from "./explicit-file-open.js";
@@ -1363,9 +1364,11 @@ export function createHttpServer(options) {
1363
1364
  response.writeHead(403, { "content-type": "application/json; charset=utf-8" }).end(JSON.stringify({ error: verdict.message }));
1364
1365
  return;
1365
1366
  }
1366
- const result = body.action === "write"
1367
- ? await context.documentService.write(conversationId, String(body.path ?? ""), String(body.content ?? ""), typeof body.title === "string" ? body.title : undefined, typeof body.baseEtag === "string" ? body.baseEtag : undefined)
1368
- : await context.documentService.read(conversationId, String(body.path ?? ""));
1367
+ const result = typeof body.action === "string" && body.action.startsWith("presentation_")
1368
+ ? await context.documentService.presentation(conversationId, body)
1369
+ : body.action === "write"
1370
+ ? await context.documentService.write(conversationId, String(body.path ?? ""), String(body.content ?? ""), typeof body.title === "string" ? body.title : undefined, typeof body.baseEtag === "string" ? body.baseEtag : undefined)
1371
+ : await context.documentService.read(conversationId, String(body.path ?? ""));
1369
1372
  response.writeHead(200, { "content-type": "application/json; charset=utf-8" }).end(JSON.stringify(result));
1370
1373
  }
1371
1374
  catch (error) {
@@ -1373,6 +1376,32 @@ export function createHttpServer(options) {
1373
1376
  }
1374
1377
  return;
1375
1378
  }
1379
+ if (url.pathname === "/api/presentations" || url.pathname === "/api/presentations/asset") {
1380
+ if (request.method !== "GET") {
1381
+ json(405, { error: "不支持此操作" });
1382
+ return;
1383
+ }
1384
+ try {
1385
+ const workspaceId = url.searchParams.get("workspaceId")?.trim();
1386
+ const workspace = workspaceId ? store.workspace(workspaceId) : undefined;
1387
+ if (!workspace || workspace.closedAt)
1388
+ throw new Error("请先选择有效工作区");
1389
+ const root = await resolveFileCwd(workspace.path, url.searchParams.get("cwd"));
1390
+ const path = url.searchParams.get("path");
1391
+ if (!path)
1392
+ throw new Error("缺少 path");
1393
+ if (url.pathname.endsWith("/asset")) {
1394
+ const asset = await presentationAsset(root, path, url.searchParams.get("asset") ?? "");
1395
+ response.writeHead(200, { "content-type": asset.type, "cache-control": "no-store", "x-content-type-options": "nosniff", "content-security-policy": "default-src 'none'; style-src 'none'; sandbox" }).end(asset.bytes);
1396
+ }
1397
+ else
1398
+ json(200, await readPresentation(root, path));
1399
+ }
1400
+ catch (error) {
1401
+ json(400, { error: error instanceof Error ? error.message : String(error) });
1402
+ }
1403
+ return;
1404
+ }
1376
1405
  if (url.pathname === "/api/tavily/settings") {
1377
1406
  const origin = request.headers.origin;
1378
1407
  const fetchSite = request.headers["sec-fetch-site"];
@@ -15,15 +15,8 @@
15
15
  * WHY IT IS AN ORDER AND NOT A USER MESSAGE. The person never typed it, and a row under their name
16
16
  * saying words they never said is the exact bug this ordering was built to avoid.
17
17
  */
18
- /**
19
- * THE ENVELOPE A CONTINUATION ORDER TRAVELS IN.
20
- *
21
- * The browser renders a `tool` row by looking at the content, and it tells a delivered result
22
- * (`<task ...>`) from an order (no envelope) by the same inspection. A continuation is neither: it
23
- * is the system telling the session to keep writing, and it needs a third label - 「续写」 - because
24
- * calling it a 「智能体下发」 order would say the system sent a task, which is not what happened.
25
- */
26
- export declare const LENGTH_CONTINUATION_ENVELOPE = "continue_output";
18
+ import { LENGTH_CONTINUATION_ENVELOPE } from "../shared/output-recovery.js";
19
+ export { LENGTH_CONTINUATION_ENVELOPE };
27
20
  /**
28
21
  * Maximum number of automatic continuations allowed per task/turn before requiring manual intervention.
29
22
  */
@@ -23,7 +23,9 @@
23
23
  * is the system telling the session to keep writing, and it needs a third label - 「续写」 - because
24
24
  * calling it a 「智能体下发」 order would say the system sent a task, which is not what happened.
25
25
  */
26
- export const LENGTH_CONTINUATION_ENVELOPE = "continue_output";
26
+ import { stripInlineThinking } from "./inline-thinking.js";
27
+ import { LENGTH_CONTINUATION_ENVELOPE } from "../shared/output-recovery.js";
28
+ export { LENGTH_CONTINUATION_ENVELOPE };
27
29
  /**
28
30
  * Maximum number of automatic continuations allowed per task/turn before requiring manual intervention.
29
31
  */
@@ -77,20 +79,18 @@ export function hasUnclosedThinking(text) {
77
79
  * anchor and prevents it from freezing or emitting a single polite word.
78
80
  */
79
81
  export function buildLengthContinuationText(assistant) {
80
- if (!assistant)
81
- return LENGTH_CONTINUATION_TEXT;
82
+ const content = stripInlineThinking(typeof assistant?.content === "string" ? assistant.content : "").replace(/[\u200B-\u200D\uFEFF]/g, "").trim();
82
83
  // Case 1: truncation happened inside tool call arguments
83
- if (Array.isArray(assistant.toolCalls) && assistant.toolCalls.length > 0) {
84
- const rawContent = typeof assistant.content === "string" ? assistant.content.trim() : "";
85
- if (!rawContent || rawContent.length < 20) {
86
- return "上一次工具调用因参数超出单次长度上限未完整执行。请将写入或修改操作拆分为更小的批次(如使用分块写入或局部编辑模式)重新发起调用。";
87
- }
84
+ if (Array.isArray(assistant?.toolCalls) && assistant.toolCalls.some(call => {
85
+ const tool = call;
86
+ return tool && (tool.preparing === true || tool.status === undefined);
87
+ })) {
88
+ return "上一次工具调用因参数超出单次长度上限未完整执行。请检查已有工具结果,仅重新发起未完成的调用,将写入或修改操作拆分为更小的批次(如使用分块写入或局部编辑模式),不要重复执行已成功的写入。";
88
89
  }
89
90
  // Case 2: textual output
90
- const content = typeof assistant.content === "string" ? assistant.content : "";
91
91
  const anchor = extractContinuationAnchor(content);
92
92
  if (!anchor)
93
- return LENGTH_CONTINUATION_TEXT;
93
+ return "上一轮在产生可见回答前耗尽了模型输出额度,没有可续写的正文。请基于原始用户请求和已完成的工具结果继续完成任务,避免重复长篇推理,优先执行必要的小步骤或给出简洁回答;不要虚构已输出的内容或断点,不要重复执行已经成功的写入。";
94
94
  if (hasUnclosedCodeBlock(content)) {
95
95
  return `上一条代码因为达到单次输出上限在以下断点处被截断:\n\`\`\`\n${anchor}\n\`\`\`\n请直接紧接上述断点继续写完后续代码并闭合代码块,严禁寒暄,不要重复断点之前已经写过的代码。`;
96
96
  }
@@ -18,7 +18,7 @@
18
18
  */
19
19
  import { describeToolCall, describeToolCallArgs, extractPartialResultText, readQuestionCall } from "./tool-calls.js";
20
20
  import { toolTargetPath } from "./file-changes.js";
21
- import { LengthExceededError } from "./turn-failure.js";
21
+ import { LengthExceededError, isProviderQuotaError } from "./turn-failure.js";
22
22
  /** Keeps only real strings, so a malformed queue snapshot cannot put objects into a broadcast. */
23
23
  const textList = (value) => Array.isArray(value) ? value.filter((item) => typeof item === "string") : undefined;
24
24
  /**
@@ -78,6 +78,8 @@ export function describeMessageFailure(record) {
78
78
  if (!message || typeof message !== "object" || message.role !== "assistant")
79
79
  return undefined;
80
80
  const text = typeof message.errorMessage === "string" ? message.errorMessage.trim() : "";
81
+ if (text && isProviderQuotaError(text))
82
+ return { message: text, stopReason: "error" };
81
83
  if (message.stopReason === "error") {
82
84
  return { message: text || "Pi 报告模型或服务提供方错误。", stopReason: "error" };
83
85
  }
@@ -0,0 +1,49 @@
1
+ import { type PresentationSpec } from "./schema.js";
2
+ export type SlideBrief = {
3
+ id: string;
4
+ title: string;
5
+ layout?: "cover" | "body" | "comparison" | "chart" | "table" | "timeline" | "metrics";
6
+ subtitle?: string;
7
+ bullets?: string[];
8
+ columns?: {
9
+ title: string;
10
+ bullets: string[];
11
+ }[];
12
+ chart?: {
13
+ type: "bar" | "column" | "line" | "area" | "pie" | "doughnut";
14
+ categories: string[];
15
+ series: {
16
+ name: string;
17
+ values: number[];
18
+ }[];
19
+ };
20
+ table?: (string | number | boolean | null)[][];
21
+ steps?: {
22
+ title: string;
23
+ body: string;
24
+ }[];
25
+ metrics?: {
26
+ label: string;
27
+ value: string;
28
+ detail?: string;
29
+ }[];
30
+ notes?: string;
31
+ source?: string;
32
+ };
33
+ export type PresentationBrief = {
34
+ title: string;
35
+ author?: string;
36
+ data?: Record<string, unknown>;
37
+ slides: SlideBrief[];
38
+ };
39
+ export type PresentationSource = {
40
+ kind: "brief";
41
+ brief: PresentationBrief;
42
+ } | {
43
+ kind: "spec";
44
+ spec: PresentationSpec;
45
+ };
46
+ export declare function safeJson(text: string): any;
47
+ export declare function compile(source: PresentationSource): PresentationSpec;
48
+ /** Stable slide IDs make a local revision independent of pagination. */
49
+ export declare function patchSource(source: PresentationSource, patch: any): PresentationSource;
@@ -0,0 +1,132 @@
1
+ import { validatePresentationSpec } from "./schema.js";
2
+ const object = (v) => !!v && typeof v === "object" && !Array.isArray(v);
3
+ const forbidden = new Set(["__proto__", "prototype", "constructor"]);
4
+ export function safeJson(text) {
5
+ return JSON.parse(text, (key, value) => { if (forbidden.has(key))
6
+ throw new Error("不支持的 JSON 属性"); return value; });
7
+ }
8
+ function bind(value, data, depth = 0) {
9
+ if (depth > 24)
10
+ throw new Error("数据引用或对象嵌套过深");
11
+ const lookup = (key) => {
12
+ let found = data;
13
+ for (const part of key.split(".")) {
14
+ if (forbidden.has(part) || (!object(found) && !Array.isArray(found)) || !Object.hasOwn(found, part))
15
+ throw new Error(`数据引用不存在:${key}`);
16
+ found = found[part];
17
+ }
18
+ return found;
19
+ };
20
+ if (object(value) && Object.keys(value).length === 1 && typeof value.$ref === "string")
21
+ return bind(lookup(value.$ref), data, depth + 1);
22
+ if (typeof value === "string")
23
+ return value.replace(/\{\{([\w.-]+)\}\}/g, (_match, key) => {
24
+ const found = lookup(key);
25
+ if (!["string", "number", "boolean"].includes(typeof found))
26
+ throw new Error(`数据引用必须为标量:${key}`);
27
+ return String(found);
28
+ });
29
+ if (Array.isArray(value))
30
+ return value.map(item => bind(item, data, depth + 1));
31
+ if (object(value))
32
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, bind(item, data, depth + 1)]));
33
+ return value;
34
+ }
35
+ export function compile(source) {
36
+ let spec;
37
+ if (source.kind === "spec")
38
+ spec = source.spec;
39
+ else {
40
+ const brief = source.brief;
41
+ if (!object(brief) || typeof brief.title !== "string" || !Array.isArray(brief.slides) || !brief.slides.length || brief.slides.length > 200)
42
+ throw new Error("brief 需要 title 和 1–200 个 slides");
43
+ spec = { version: 1, canvas: { width: 13.333, height: 7.5 }, metadata: { title: brief.title, author: brief.author, language: "zh-CN" }, slides: [] };
44
+ for (const [index, original] of brief.slides.entries()) {
45
+ const slide = bind(original, brief.data ?? {});
46
+ if (!object(slide) || typeof slide.id !== "string" || typeof slide.title !== "string")
47
+ throw new Error(`第 ${index + 1} 页需要 id/title`);
48
+ const elements = [];
49
+ const text = (key, content, x, y, width, height, size = 22, bold = false, color = "233047") => {
50
+ if (typeof content !== "string")
51
+ throw new Error(`第 ${index + 1} 页 ${key} 必须为文字`);
52
+ elements.push({ id: `${slide.id}-${key}`, type: "text", x, y, width, height, text: content, fontSize: size, fontFamily: "Noto Sans SC", bold, color });
53
+ };
54
+ text("number", `${String(index + 1).padStart(2, "0")} / ${brief.slides.length}`, .6, 7.05, 2, .22, 10, false, "52627A");
55
+ text("title", slide.title, .65, slide.layout === "cover" ? 1.6 : .5, 12, slide.layout === "cover" ? 1.6 : .9, slide.layout === "cover" ? 36 : 28, true);
56
+ if (slide.source)
57
+ text("source", slide.source, 2.7, 7.02, 10, .3, 10, false, "52627A");
58
+ const bullets = (items, x, y, width, height, key) => text(key, items.map(item => `• ${item}`).join("\n\n"), x, y, width, height, 22);
59
+ const layout = slide.layout ?? (slide.chart ? "chart" : slide.table ? "table" : "body");
60
+ if (layout === "cover")
61
+ text("subtitle", slide.subtitle ?? "", .7, 3.7, 11.9, 1.5, 24, false, "52627A");
62
+ else if (layout === "body")
63
+ bullets(slide.bullets ?? [slide.subtitle ?? ""], .75, 1.75, 11.8, 4.85, "body");
64
+ else if (layout === "comparison") {
65
+ if (!slide.columns?.length || slide.columns.length > 3)
66
+ throw new Error("comparison 需要 1–3 个 columns");
67
+ const w = 12 / slide.columns.length;
68
+ slide.columns.forEach((col, i) => { text(`col-${i}`, col.title, .7 + w * i, 1.65, w - .35, .7, 24, true, "245BA8"); bullets(col.bullets, .7 + w * i, 2.6, w - .4, 3.9, `body-${i}`); });
69
+ }
70
+ else if (layout === "chart") {
71
+ if (!slide.chart)
72
+ throw new Error("chart 页面缺少 chart 数据");
73
+ elements.push({ id: `${slide.id}-chart`, type: "chart", x: .8, y: 1.6, width: 11.7, height: slide.subtitle ? 4.5 : 5.1, chart: slide.chart.type, categories: slide.chart.categories, series: slide.chart.series, showLegend: true, showValues: true });
74
+ if (slide.subtitle)
75
+ text("takeaway", slide.subtitle, .8, 6.25, 11.7, .6, 18);
76
+ }
77
+ else if (layout === "table") {
78
+ if (!slide.table?.length)
79
+ throw new Error("table 页面缺少 table");
80
+ elements.push({ id: `${slide.id}-table`, type: "table", x: .75, y: 1.65, width: 11.8, height: 5, rows: slide.table, headerRows: 1 });
81
+ }
82
+ else if (layout === "timeline" || layout === "metrics") {
83
+ const entries = layout === "timeline" ? slide.steps?.map(step => ({ label: step.title, value: step.body })) : slide.metrics;
84
+ if (!entries?.length || entries.length > 5)
85
+ throw new Error(`${layout} 需要 1–5 项`);
86
+ const w = 12 / entries.length;
87
+ entries.forEach((item, i) => {
88
+ text(`label-${i}`, item.label, .7 + w * i, 1.9, w - .35, 1, 20, true, "245BA8");
89
+ text(`value-${i}`, item.value, .7 + w * i, 3.05, w - .35, 2.1, layout === "metrics" ? 30 : 22, layout === "metrics");
90
+ if ("detail" in item && typeof item.detail === "string")
91
+ text(`detail-${i}`, item.detail, .7 + w * i, 5.4, w - .35, 1.1, 16);
92
+ });
93
+ }
94
+ else
95
+ throw new Error(`不支持的 layout:${layout}`);
96
+ spec.slides.push({ id: slide.id, title: slide.title, notes: slide.notes, background: "F8FAFD", elements });
97
+ }
98
+ }
99
+ const result = validatePresentationSpec(spec);
100
+ if (!result.valid)
101
+ throw new Error(JSON.stringify(result.diagnostics));
102
+ if (!spec.slides.length || spec.canvas.width > 56 || spec.canvas.height > 56)
103
+ throw new Error("页面数或画布大小非法");
104
+ return spec;
105
+ }
106
+ /** Stable slide IDs make a local revision independent of pagination. */
107
+ export function patchSource(source, patch) {
108
+ if (!object(patch))
109
+ throw new Error("patch 必须为对象");
110
+ const copy = structuredClone(source);
111
+ const deck = copy.kind === "brief" ? copy.brief : copy.spec;
112
+ if (patch.data !== undefined) {
113
+ if (copy.kind !== "brief" || !object(patch.data))
114
+ throw new Error("data 补丁仅用于 brief");
115
+ copy.brief.data = { ...copy.brief.data, ...patch.data };
116
+ }
117
+ if (patch.slides !== undefined) {
118
+ if (!object(patch.slides))
119
+ throw new Error("slides 补丁格式为 {页面ID: 字段补丁}");
120
+ for (const [id, changes] of Object.entries(patch.slides)) {
121
+ const index = deck.slides.findIndex(slide => slide.id === id);
122
+ if (index < 0 || !object(changes) || (changes.id !== undefined && changes.id !== id))
123
+ throw new Error(`页面补丁非法:${id}`);
124
+ Object.assign(deck.slides[index], changes);
125
+ }
126
+ }
127
+ const unknown = Object.keys(patch).filter(key => key !== "data" && key !== "slides");
128
+ if (unknown.length)
129
+ throw new Error(`不支持的补丁字段:${unknown.join(",")}`);
130
+ compile(copy);
131
+ return copy;
132
+ }
@@ -0,0 +1,15 @@
1
+ /** Inspect generated OOXML rather than making the model write a ZIP/XML checker for every deck. */
2
+ export declare function inspectPptx(bytes: Buffer): Promise<{
3
+ slides: number;
4
+ notes: number;
5
+ nativeCharts: number;
6
+ nativeTables: number;
7
+ editableTextShapes: number;
8
+ embeddedWorkbooks: number;
9
+ canvasInches: {
10
+ width: number;
11
+ height: number;
12
+ } | undefined;
13
+ relationships: string;
14
+ verification: string;
15
+ }>;