nolo-cli 0.8.0 → 0.9.0

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 (183) hide show
  1. package/_executeModel-UD44KGZ4.js +203 -0
  2. package/action-ZJWE3Y5S.js +28 -0
  3. package/addContentAction-TVDBNJM5.js +26 -0
  4. package/addDialogAgentAction-EKH774VT.js +68 -0
  5. package/agentDeleteCommand-TCPEFJTF.js +327 -0
  6. package/agentEmailCommands-CZ3UILZ4.js +626 -0
  7. package/agentListCommands-SJKO2FFB.js +223 -0
  8. package/agentMachineCommands-PSNABISZ.js +425 -0
  9. package/agentPullCommand-O2MTUAFR.js +122 -0
  10. package/agentRecordCommands-MH2JKFHS.js +94 -0
  11. package/agentRunCommand-4KH6MIZR.js +110 -0
  12. package/agentRunControl-K4VKNEHF.js +57 -0
  13. package/agentRuntimeLocal-SKHJUWSS.js +104 -0
  14. package/agentSlice-3WXXN4VK.js +42 -0
  15. package/authCommand-PXFX6JDT.js +581 -0
  16. package/authCommands-356AYWEK.js +35 -0
  17. package/chunk-2EISRLRC.js +238 -0
  18. package/chunk-2FTTDCD4.js +675 -0
  19. package/chunk-2K2ECKSG.js +222 -0
  20. package/chunk-2PUGVR6E.js +19 -0
  21. package/chunk-3ASDTTEI.js +1774 -0
  22. package/chunk-3EUW3WEO.js +8 -0
  23. package/chunk-3LY4F7SV.js +9293 -0
  24. package/chunk-3TZDXYSF.js +71 -0
  25. package/chunk-3WYQEUBI.js +34 -0
  26. package/chunk-4CQLVGRV.js +50 -0
  27. package/chunk-4IJYA27C.js +342 -0
  28. package/chunk-4K2KKCSD.js +577 -0
  29. package/chunk-4SN6J65J.js +38 -0
  30. package/chunk-4VNS5WPM.js +42 -0
  31. package/chunk-4ZDM73SD.js +34 -0
  32. package/chunk-5CS33IBL.js +301 -0
  33. package/chunk-5KLGBAAR.js +386 -0
  34. package/chunk-5MIDPSSK.js +206 -0
  35. package/chunk-5MMAK75Q.js +15 -0
  36. package/chunk-5PJ3VWCS.js +360 -0
  37. package/chunk-63SLEOLK.js +175 -0
  38. package/chunk-63W5N6P3.js +150 -0
  39. package/chunk-6GANEXVO.js +231 -0
  40. package/chunk-6HYVJV7B.js +102 -0
  41. package/chunk-6WD3OOJS.js +20 -0
  42. package/chunk-7OOXPE3N.js +628 -0
  43. package/chunk-7QRKCBOP.js +1078 -0
  44. package/chunk-ATNTHIZI.js +13 -0
  45. package/chunk-AUQ747NZ.js +902 -0
  46. package/chunk-AVMKZHBC.js +85 -0
  47. package/chunk-AZPCASRE.js +36 -0
  48. package/chunk-BBYVOSU2.js +792 -0
  49. package/chunk-C3RUNRHT.js +51 -0
  50. package/chunk-CF2WZF4N.js +134 -0
  51. package/chunk-CF7PE763.js +10 -0
  52. package/chunk-CKOJQDKR.js +198 -0
  53. package/chunk-COMXDWNM.js +807 -0
  54. package/chunk-CPB2YM4D.js +171 -0
  55. package/chunk-CWMSB67P.js +34 -0
  56. package/chunk-DCOA4QSN.js +105 -0
  57. package/chunk-DFFIZ25G.js +30 -0
  58. package/chunk-DWLEOOGR.js +8 -0
  59. package/chunk-DZ3XJVET.js +231 -0
  60. package/chunk-EHLHSX7R.js +1433 -0
  61. package/chunk-ELRRLDWI.js +478 -0
  62. package/chunk-EXTIQUCI.js +482 -0
  63. package/chunk-EYEEHCU4.js +3066 -0
  64. package/chunk-G3SUCT4W.js +8 -0
  65. package/chunk-G43KEVSC.js +1447 -0
  66. package/chunk-GAKEBQD6.js +30 -0
  67. package/chunk-GBRG75BQ.js +86 -0
  68. package/chunk-GG4AJPSR.js +191 -0
  69. package/chunk-H33743XH.js +25 -0
  70. package/chunk-HNMXYYJR.js +12 -0
  71. package/chunk-I42VC5KR.js +15 -0
  72. package/chunk-IDZTNRP2.js +85 -0
  73. package/chunk-ISNCLGUZ.js +146 -0
  74. package/chunk-IWX4UW2E.js +548 -0
  75. package/chunk-JBTJAPUF.js +35 -0
  76. package/chunk-JEXVIMYZ.js +55 -0
  77. package/chunk-JRKKFRAV.js +537 -0
  78. package/chunk-JZPBVBIY.js +94 -0
  79. package/chunk-KKY4B2Q2.js +21 -0
  80. package/chunk-KOCA5FCS.js +4750 -0
  81. package/chunk-KQHGZWSV.js +63 -0
  82. package/chunk-KTVVPRJS.js +138 -0
  83. package/chunk-KUG52IAP.js +8 -0
  84. package/chunk-KX6YBIHG.js +8 -0
  85. package/chunk-LARL2V6G.js +9017 -0
  86. package/chunk-LCBAMY2M.js +60 -0
  87. package/chunk-LM6IYQ3F.js +16 -0
  88. package/chunk-M76ECQRD.js +13658 -0
  89. package/chunk-MGOJ5R6J.js +113 -0
  90. package/chunk-MKMWT7SA.js +27196 -0
  91. package/chunk-MRC4Q34M.js +188 -0
  92. package/chunk-OLZBQWZU.js +6 -0
  93. package/chunk-OPZYGHUC.js +89 -0
  94. package/chunk-OWOHNGCN.js +50 -0
  95. package/chunk-PAKN26FP.js +239 -0
  96. package/chunk-PCWC3JTN.js +91 -0
  97. package/chunk-PG5PNA7Y.js +939 -0
  98. package/chunk-Q2YZULBH.js +104 -0
  99. package/chunk-QSJ3HFEF.js +8 -0
  100. package/chunk-QYXLLLGL.js +4519 -0
  101. package/chunk-ROWQEJRP.js +139 -0
  102. package/chunk-S7Z2HMCN.js +25 -0
  103. package/chunk-SBR32ZZS.js +1901 -0
  104. package/chunk-SH2CFQOH.js +3391 -0
  105. package/chunk-SL35K7AH.js +226 -0
  106. package/chunk-TILFE6LV.js +381 -0
  107. package/chunk-TSS3XJY4.js +2052 -0
  108. package/chunk-U4TRT5V4.js +246 -0
  109. package/chunk-U6VC4MU4.js +8 -0
  110. package/chunk-UAD2WT54.js +64 -0
  111. package/chunk-UUJDGGAK.js +421 -0
  112. package/chunk-VF4K2QE6.js +21 -0
  113. package/chunk-VHBWHNVT.js +59 -0
  114. package/chunk-VIDPVFP3.js +20 -0
  115. package/chunk-VP4WJWKW.js +8882 -0
  116. package/chunk-W4NVOSFF.js +37 -0
  117. package/chunk-WKM6FH35.js +190 -0
  118. package/chunk-WWC7I6TA.js +8 -0
  119. package/chunk-X7W4TNB4.js +1550 -0
  120. package/chunk-XE635NI4.js +1948 -0
  121. package/chunk-XKIMRZO2.js +221 -0
  122. package/chunk-XS466O7S.js +933 -0
  123. package/chunk-Y5GCAMGP.js +9 -0
  124. package/chunk-YBWOP46I.js +3272 -0
  125. package/chunk-YPRZSPF3.js +148 -0
  126. package/chunk-YYUCRDOK.js +69 -0
  127. package/chunk-Z4NR32XR.js +50 -0
  128. package/chunk-ZIG5LJ7X.js +24765 -0
  129. package/chunk-ZNFJWEN4.js +56 -0
  130. package/chunk-ZQ2UM4KG.js +2878 -0
  131. package/cliExecutor-DNE7TCC4.js +36 -0
  132. package/clipboardy-BVE3LVEH.js +12001 -0
  133. package/createAgentAutomationAction-63OIP6X5.js +866 -0
  134. package/createDialogAction-ZLYZDYBB.js +54 -0
  135. package/createPageAction-AL5FSDCK.js +171 -0
  136. package/db-HCJ5PRB5.js +271 -0
  137. package/dbSlice-PR44QPXY.js +60 -0
  138. package/deleteFile-4SKGPHOZ.js +41 -0
  139. package/dialogCommands-F6YI5742.js +63 -0
  140. package/dialogSlice-JSBNZRLR.js +148 -0
  141. package/docCreateCommands-4CTO7ERT.js +219 -0
  142. package/docDeleteCommands-VBWERDRG.js +180 -0
  143. package/docReadCommands-KNP4MFYB.js +133 -0
  144. package/docStore-ADP5VYY4.js +98 -0
  145. package/docUpdateCommands-4BCBJQHA.js +317 -0
  146. package/fetchMessages-U6ZHN56A.js +17 -0
  147. package/getPricing-3E6UNPKL.js +30 -0
  148. package/handleSendMessageAction-IJDQ6ARA.js +185 -0
  149. package/index.js +188 -112943
  150. package/lib-FYYBQIXS.js +19839 -0
  151. package/localDialogRead-Z5UTAJPU.js +26 -0
  152. package/localFirstLog-DHNOY2NA.js +19 -0
  153. package/localRuntimeAuthority-TEGCOWX4.js +471 -0
  154. package/localRuntimeDb-LGDF6FQP.js +12 -0
  155. package/machineCommands-EA3M4XTN.js +779 -0
  156. package/machineInfo-M6KB6HZN.js +10 -0
  157. package/machineWsRunDispatch-NAPKE5ZA.js +110 -0
  158. package/memoryCommands-O4MIPIWQ.js +476 -0
  159. package/models-4OPOOLFS.js +9 -0
  160. package/offlineMarxistsAgentCommand-BCPJITJL.js +242 -0
  161. package/package.json +3 -25
  162. package/read-RIJCIVKX.js +17 -0
  163. package/readDocTool-GZD2N3LO.js +16 -0
  164. package/readlineWorkspace-KMWT4T4S.js +5509 -0
  165. package/removeDialogAgentAction-GJQJNDW6.js +73 -0
  166. package/runAgentClientLoop-U5Q6NDTJ.js +291 -0
  167. package/runtimeDoctorCommands-LRHLPDRC.js +289 -0
  168. package/setDialogExtraReferencesAction-M7OQG54N.js +60 -0
  169. package/setPrimaryDialogAgentAction-46UNFJDL.js +80 -0
  170. package/settingSlice-FVUUH4JA.js +199 -0
  171. package/skillSummaryMarker-42HKSXYY.js +9 -0
  172. package/slateToRenderMarkdown-Y5IYN73U.js +7 -0
  173. package/slateUtils-2M7MUTWX.js +19 -0
  174. package/spaceCommands-E2CFRPZJ.js +454 -0
  175. package/spaceSlice-L3R6IMXE.js +147 -0
  176. package/streamAgentChatTurn-UBDAOQWE.js +4528 -0
  177. package/tableCommands-GOFP7QKA.js +1286 -0
  178. package/toolApiClient-QI3YBNWB.js +26 -0
  179. package/tools-TMJXZTCA.js +85 -0
  180. package/tuiSummaryLlmCaller-RV3THLZF.js +78 -0
  181. package/understanding-GQKNDDWM.js +271 -0
  182. package/updateCommands-VOSPKXFF.js +31 -0
  183. package/updateDialogTitleAction-ZTWRDXI2.js +188 -0
@@ -0,0 +1,1901 @@
1
+ import {
2
+ MEMORY_USE_GUIDANCE,
3
+ wrapHistoricalSummaryWithReplayGuard
4
+ } from "./chunk-KKY4B2Q2.js";
5
+ import {
6
+ ANTIGRAVITY_CLOUD_CODE_BASE_URL,
7
+ isAntigravityOAuthAgent
8
+ } from "./chunk-C3RUNRHT.js";
9
+ import {
10
+ clipMultilineText,
11
+ fetchAndSerializeTable
12
+ } from "./chunk-MKMWT7SA.js";
13
+ import {
14
+ normalizeNonNegativeMs,
15
+ parseRetryAfterHeaderMs
16
+ } from "./chunk-GAKEBQD6.js";
17
+ import {
18
+ slateToSimplifiedMarkdown
19
+ } from "./chunk-XKIMRZO2.js";
20
+ import {
21
+ extractCategorizedMentions
22
+ } from "./chunk-VP4WJWKW.js";
23
+ import {
24
+ resolvePageSkillMetadata
25
+ } from "./chunk-ZQ2UM4KG.js";
26
+ import {
27
+ estimateTokenCount,
28
+ fetchAndCacheMessages,
29
+ shouldUseServerProxy
30
+ } from "./chunk-ZIG5LJ7X.js";
31
+ import {
32
+ fetchServerSyncedCredential
33
+ } from "./chunk-4K2KKCSD.js";
34
+ import {
35
+ createSpaceKey
36
+ } from "./chunk-UAD2WT54.js";
37
+ import {
38
+ buildCurrentTimeBlock,
39
+ buildIdentityBlock,
40
+ buildRuntimeGuidanceBlocks
41
+ } from "./chunk-PAKN26FP.js";
42
+ import {
43
+ OPENAI_RESPONSES_ENDPOINT,
44
+ buildProviderAuthHeaders,
45
+ convertMessagesToResponsesInput,
46
+ isOpenAiResponsesModel,
47
+ resolvePlatformChatCompletionsEndpoint
48
+ } from "./chunk-JRKKFRAV.js";
49
+ import {
50
+ canonicalizeToolNames
51
+ } from "./chunk-AUQ747NZ.js";
52
+ import {
53
+ getModelConfig,
54
+ isModelSupportReasoningEffort
55
+ } from "./chunk-BBYVOSU2.js";
56
+ import {
57
+ createFileCredentialBroker
58
+ } from "./chunk-5CS33IBL.js";
59
+ import {
60
+ isDeepInfraKimiModel,
61
+ isFireworksKimiModel,
62
+ resolveFireworksKimiModel
63
+ } from "./chunk-IWX4UW2E.js";
64
+ import {
65
+ extractCustomId
66
+ } from "./chunk-DFFIZ25G.js";
67
+ import {
68
+ toErrorMessage
69
+ } from "./chunk-HNMXYYJR.js";
70
+ import {
71
+ read
72
+ } from "./chunk-COMXDWNM.js";
73
+ import {
74
+ asNonEmptyStringArray
75
+ } from "./chunk-I42VC5KR.js";
76
+ import {
77
+ asTrimmedLowercaseString
78
+ } from "./chunk-QSJ3HFEF.js";
79
+ import {
80
+ getRuntimeServerContext
81
+ } from "./chunk-EYEEHCU4.js";
82
+ import {
83
+ isAbortError
84
+ } from "./chunk-QYXLLLGL.js";
85
+ import {
86
+ isLoopbackUrl
87
+ } from "./chunk-4SN6J65J.js";
88
+ import {
89
+ API_ENDPOINTS
90
+ } from "./chunk-LCBAMY2M.js";
91
+ import {
92
+ asTrimmedString
93
+ } from "./chunk-3EUW3WEO.js";
94
+ import {
95
+ asOptionalTrimmedString
96
+ } from "./chunk-G3SUCT4W.js";
97
+
98
+ // packages/ai/skills/referenceRuntime.ts
99
+ var joinUniqueStrings = (...groups) => Array.from(new Set(groups.flatMap((items) => asNonEmptyStringArray(items))));
100
+ var extractRuntimePageCapabilities = (content) => {
101
+ const meta = resolvePageSkillMetadata(content);
102
+ const directTools = asNonEmptyStringArray(content?.tools);
103
+ const skillConfig = meta?.skillConfig;
104
+ const skillTools = skillConfig?.toolNames ?? [];
105
+ const softSkillHints = asNonEmptyStringArray([
106
+ skillConfig?.name,
107
+ ...meta?.recommendedSkills ?? []
108
+ ]);
109
+ return {
110
+ directTools,
111
+ hardSkillKeys: meta?.requiredSkills ?? [],
112
+ softSkillKeys: meta?.recommendedSkills ?? [],
113
+ hardSkillTools: meta?.kind === "skill" ? skillTools : [],
114
+ softSkillHints,
115
+ promptPatches: skillConfig?.promptPatch ? [skillConfig.promptPatch] : [],
116
+ shouldUpgradeReference: directTools.length > 0 || meta?.kind === "skill" || !!skillConfig?.promptPatch
117
+ };
118
+ };
119
+ var buildSkillGuidancePromptBlock = (options) => {
120
+ const title = asOptionalTrimmedString(options.title) ?? "--- \u6280\u80FD\u63D0\u793A ---";
121
+ const recommendedSkillHints = joinUniqueStrings(options.recommendedSkillHints);
122
+ const skillPromptPatches = joinUniqueStrings(options.skillPromptPatches);
123
+ if (recommendedSkillHints.length === 0 && skillPromptPatches.length === 0) {
124
+ return "";
125
+ }
126
+ return [
127
+ title,
128
+ recommendedSkillHints.length > 0 ? `\u4EE5\u4E0B\u6280\u80FD\u4E0E\u5F53\u524D\u4EFB\u52A1\u66F4\u76F8\u5173\uFF0C\u53EF\u4F18\u5148\u8003\u8651\uFF1A${recommendedSkillHints.join("\u3001")}` : "",
129
+ ...skillPromptPatches
130
+ ].filter(Boolean).join("\n");
131
+ };
132
+ var buildIdentifierCandidates = (identifier, contentByKey) => {
133
+ const trimmed = identifier.trim();
134
+ if (!trimmed || contentByKey.has(trimmed)) return trimmed;
135
+ const candidateToKey = /* @__PURE__ */ new Map();
136
+ for (const [key, page] of Array.from(contentByKey.entries())) {
137
+ const meta = resolvePageSkillMetadata(page);
138
+ for (const value of [key, page?.dbKey, page?.title, meta?.skillConfig?.id, meta?.skillConfig?.name]) {
139
+ const trimmedValue = asOptionalTrimmedString(value);
140
+ if (trimmedValue) {
141
+ candidateToKey.set(trimmedValue, key);
142
+ }
143
+ }
144
+ }
145
+ return candidateToKey.get(trimmed) ?? trimmed;
146
+ };
147
+ async function resolveSkillGraphFromRoots(options) {
148
+ const contentByKey = new Map(options.contentByKey ?? []);
149
+ const requiredTools = /* @__PURE__ */ new Set();
150
+ const recommendedTools = /* @__PURE__ */ new Set();
151
+ const recommendedSkillHints = /* @__PURE__ */ new Set();
152
+ const skillPromptPatches = /* @__PURE__ */ new Set();
153
+ const visits = [];
154
+ const visited = /* @__PURE__ */ new Set();
155
+ const loadPageCached = async (identifier) => {
156
+ const resolvedIdentifier = buildIdentifierCandidates(identifier, contentByKey);
157
+ if (!resolvedIdentifier) return null;
158
+ if (contentByKey.has(resolvedIdentifier)) {
159
+ return contentByKey.get(resolvedIdentifier) ?? null;
160
+ }
161
+ const page = await options.loadPage(resolvedIdentifier);
162
+ if (page) {
163
+ contentByKey.set(resolvedIdentifier, page);
164
+ if (page.dbKey) {
165
+ contentByKey.set(page.dbKey, page);
166
+ }
167
+ }
168
+ return page ?? null;
169
+ };
170
+ const visit = async (identifier, mode, sourceLabel) => {
171
+ const page = await loadPageCached(identifier);
172
+ if (!page?.dbKey) return;
173
+ const visitKey = `${mode}:${page.dbKey}`;
174
+ if (visited.has(visitKey)) return;
175
+ visited.add(visitKey);
176
+ const meta = resolvePageSkillMetadata(page);
177
+ const directTools = canonicalizeToolNames(page.tools ?? []);
178
+ const skillTools = canonicalizeToolNames(meta?.skillConfig?.toolNames ?? []);
179
+ const mergedTools = joinUniqueStrings(directTools, skillTools);
180
+ visits.push({
181
+ dbKey: page.dbKey,
182
+ title: page.title,
183
+ mode,
184
+ sourceLabel,
185
+ meta
186
+ });
187
+ if (mode === "required") {
188
+ mergedTools.forEach((toolName) => requiredTools.add(toolName));
189
+ if (meta?.skillConfig?.promptPatch) {
190
+ skillPromptPatches.add(meta.skillConfig.promptPatch);
191
+ }
192
+ } else {
193
+ mergedTools.forEach((toolName) => recommendedTools.add(toolName));
194
+ if (meta?.skillConfig?.name) {
195
+ recommendedSkillHints.add(meta.skillConfig.name);
196
+ }
197
+ }
198
+ const nextHard = meta?.requiredSkills ?? meta?.skillConfig?.requiredSkills ?? [];
199
+ const nextSoft = meta?.recommendedSkills ?? meta?.skillConfig?.recommendedSkills ?? [];
200
+ if (mode === "required") {
201
+ await Promise.all(nextHard.map((childKey) => visit(childKey, "required", page.dbKey)));
202
+ await Promise.all(nextSoft.map((childKey) => visit(childKey, "recommended", page.dbKey)));
203
+ return;
204
+ }
205
+ await Promise.all([...nextHard, ...nextSoft].map((childKey) => visit(childKey, "recommended", page.dbKey)));
206
+ };
207
+ await Promise.all(options.roots.map((root) => visit(root.identifier, root.mode, root.sourceLabel)));
208
+ return {
209
+ requiredTools: Array.from(requiredTools),
210
+ recommendedTools: Array.from(recommendedTools),
211
+ recommendedSkillHints: Array.from(recommendedSkillHints),
212
+ skillPromptPatches: Array.from(skillPromptPatches),
213
+ contentByKey,
214
+ visits
215
+ };
216
+ }
217
+
218
+ // packages/ai/agent/referenceUtils.ts
219
+ function mergeReferences(base, extra) {
220
+ const safeBase = Array.isArray(base) ? base : [];
221
+ const safeExtra = Array.isArray(extra) ? extra : [];
222
+ const seen = /* @__PURE__ */ new Set();
223
+ const merged = [];
224
+ for (const item of [...safeBase, ...safeExtra]) {
225
+ const key = item.dbKey;
226
+ if (key && seen.has(key)) continue;
227
+ if (key) seen.add(key);
228
+ merged.push(item);
229
+ }
230
+ return merged;
231
+ }
232
+ var loadContentsByKeys = async (keys, dispatch, preloaded) => {
233
+ const contentByKey = /* @__PURE__ */ new Map();
234
+ const uniqueKeys = Array.from(new Set(keys.filter(Boolean)));
235
+ await Promise.all(
236
+ uniqueKeys.map(async (dbKey) => {
237
+ if (preloaded?.has(dbKey)) {
238
+ const content = preloaded.get(dbKey);
239
+ if (content) contentByKey.set(dbKey, content);
240
+ return;
241
+ }
242
+ try {
243
+ const content = await dispatch(read({ dbKey })).unwrap();
244
+ if (content) contentByKey.set(dbKey, content);
245
+ } catch {
246
+ }
247
+ })
248
+ );
249
+ return contentByKey;
250
+ };
251
+ var resolveReferenceAssets = async (references, dispatch) => {
252
+ if (!Array.isArray(references) || references.length === 0) {
253
+ return {
254
+ references: [],
255
+ referencedTools: [],
256
+ recommendedSkillTools: [],
257
+ recommendedSkillHints: [],
258
+ skillPromptPatches: [],
259
+ contentByKey: /* @__PURE__ */ new Map()
260
+ };
261
+ }
262
+ const entries = await Promise.all(
263
+ references.filter((ref) => ref?.dbKey).map(async (ref) => {
264
+ try {
265
+ const content = await dispatch(read({ dbKey: ref.dbKey })).unwrap();
266
+ return { ref, content };
267
+ } catch {
268
+ return { ref, content: null };
269
+ }
270
+ })
271
+ );
272
+ const contentByKey = /* @__PURE__ */ new Map();
273
+ const toolSet = /* @__PURE__ */ new Set();
274
+ const recommendedToolSet = /* @__PURE__ */ new Set();
275
+ const recommendedSkillHints = /* @__PURE__ */ new Set();
276
+ const skillPromptPatches = /* @__PURE__ */ new Set();
277
+ const normalizedReferences = [];
278
+ const hardSkillKeys = /* @__PURE__ */ new Set();
279
+ const softSkillKeys = /* @__PURE__ */ new Set();
280
+ for (const { ref, content } of entries) {
281
+ if (content) {
282
+ contentByKey.set(ref.dbKey, content);
283
+ }
284
+ const capabilities = extractRuntimePageCapabilities(content);
285
+ for (const tool of capabilities.directTools) {
286
+ toolSet.add(tool);
287
+ }
288
+ for (const tool of capabilities.hardSkillTools) {
289
+ toolSet.add(tool);
290
+ }
291
+ for (const hint of capabilities.softSkillHints) {
292
+ recommendedSkillHints.add(hint);
293
+ }
294
+ for (const patch of capabilities.promptPatches) {
295
+ skillPromptPatches.add(patch);
296
+ }
297
+ for (const skillKey of capabilities.hardSkillKeys) {
298
+ hardSkillKeys.add(skillKey);
299
+ }
300
+ for (const skillKey of capabilities.softSkillKeys) {
301
+ softSkillKeys.add(skillKey);
302
+ }
303
+ normalizedReferences.push({
304
+ ...ref,
305
+ type: capabilities.shouldUpgradeReference ? "instruction" : ref.type
306
+ });
307
+ }
308
+ const resolvedSkillLinks = await resolveSkillGraphFromRoots({
309
+ roots: [
310
+ ...Array.from(hardSkillKeys).map((identifier) => ({ identifier, mode: "required" })),
311
+ ...Array.from(softSkillKeys).map((identifier) => ({ identifier, mode: "recommended" }))
312
+ ],
313
+ loadPage: async (identifier) => {
314
+ const loaded = await loadContentsByKeys([identifier], dispatch, contentByKey);
315
+ return loaded.get(identifier) ?? null;
316
+ },
317
+ contentByKey
318
+ });
319
+ resolvedSkillLinks.contentByKey.forEach((value, key) => contentByKey.set(key, value));
320
+ for (const tool of resolvedSkillLinks.requiredTools) {
321
+ toolSet.add(tool);
322
+ }
323
+ for (const tool of resolvedSkillLinks.recommendedTools) {
324
+ recommendedToolSet.add(tool);
325
+ }
326
+ for (const hint of resolvedSkillLinks.recommendedSkillHints) {
327
+ recommendedSkillHints.add(hint);
328
+ }
329
+ for (const patch of resolvedSkillLinks.skillPromptPatches) {
330
+ skillPromptPatches.add(patch);
331
+ }
332
+ return {
333
+ references: normalizedReferences,
334
+ referencedTools: Array.from(toolSet),
335
+ recommendedSkillTools: Array.from(recommendedToolSet),
336
+ recommendedSkillHints: Array.from(recommendedSkillHints),
337
+ skillPromptPatches: Array.from(skillPromptPatches),
338
+ contentByKey
339
+ };
340
+ };
341
+ var resolveToolsFromKeys = async (keys, dispatch, preloaded) => {
342
+ if (!Array.isArray(keys) || keys.length === 0) {
343
+ return {
344
+ tools: [],
345
+ recommendedSkillTools: [],
346
+ recommendedSkillHints: [],
347
+ skillPromptPatches: [],
348
+ contentByKey: /* @__PURE__ */ new Map()
349
+ };
350
+ }
351
+ const contentByKey = await loadContentsByKeys(keys, dispatch, preloaded);
352
+ const toolSet = /* @__PURE__ */ new Set();
353
+ const recommendedToolSet = /* @__PURE__ */ new Set();
354
+ const recommendedSkillHints = /* @__PURE__ */ new Set();
355
+ const skillPromptPatches = /* @__PURE__ */ new Set();
356
+ const hardSkillKeys = /* @__PURE__ */ new Set();
357
+ const softSkillKeys = /* @__PURE__ */ new Set();
358
+ for (const content of contentByKey.values()) {
359
+ const capabilities = extractRuntimePageCapabilities(content);
360
+ for (const tool of [...capabilities.directTools, ...capabilities.hardSkillTools]) {
361
+ toolSet.add(tool);
362
+ }
363
+ for (const hint of capabilities.softSkillHints) {
364
+ recommendedSkillHints.add(hint);
365
+ }
366
+ for (const patch of capabilities.promptPatches) {
367
+ skillPromptPatches.add(patch);
368
+ }
369
+ for (const skillKey of capabilities.hardSkillKeys) {
370
+ hardSkillKeys.add(skillKey);
371
+ }
372
+ for (const skillKey of capabilities.softSkillKeys) {
373
+ softSkillKeys.add(skillKey);
374
+ }
375
+ }
376
+ const resolvedSkillLinks = await resolveSkillGraphFromRoots({
377
+ roots: [
378
+ ...Array.from(hardSkillKeys).map((identifier) => ({ identifier, mode: "required" })),
379
+ ...Array.from(softSkillKeys).map((identifier) => ({ identifier, mode: "recommended" }))
380
+ ],
381
+ loadPage: async (identifier) => {
382
+ const loaded = await loadContentsByKeys([identifier], dispatch, contentByKey);
383
+ return loaded.get(identifier) ?? null;
384
+ },
385
+ contentByKey
386
+ });
387
+ resolvedSkillLinks.contentByKey.forEach((value, key) => contentByKey.set(key, value));
388
+ for (const tool of resolvedSkillLinks.requiredTools) {
389
+ toolSet.add(tool);
390
+ }
391
+ for (const tool of resolvedSkillLinks.recommendedTools) {
392
+ recommendedToolSet.add(tool);
393
+ }
394
+ for (const hint of resolvedSkillLinks.recommendedSkillHints) {
395
+ recommendedSkillHints.add(hint);
396
+ }
397
+ for (const patch of resolvedSkillLinks.skillPromptPatches) {
398
+ skillPromptPatches.add(patch);
399
+ }
400
+ return {
401
+ tools: Array.from(toolSet),
402
+ recommendedSkillTools: Array.from(recommendedToolSet),
403
+ recommendedSkillHints: Array.from(recommendedSkillHints),
404
+ skillPromptPatches: Array.from(skillPromptPatches),
405
+ contentByKey
406
+ };
407
+ };
408
+
409
+ // packages/agent-runtime/agentCallPlan.ts
410
+ var CODEX_RESPONSES_URL = "https://chatgpt.com/backend-api/codex/responses";
411
+ var CURSOR_AGENT_URL = "https://api2.cursor.sh/agent.v1.AgentService/Run";
412
+ function resolveClientWire(plan) {
413
+ if (plan.upstreamWire === "gemini-cca") return "chat.completions";
414
+ if (plan.upstreamWire === "anthropic-messages") return "chat.completions";
415
+ if (plan.upstreamWire === "cursor-connect") return "chat.completions";
416
+ if (plan.upstreamWire === "responses" && plan.authMethod.kind === "oauth" && plan.authMethod.ref === "chatgpt") {
417
+ return "chat.completions";
418
+ }
419
+ return plan.upstreamWire;
420
+ }
421
+ var XAI_CHAT_COMPLETIONS_URL = "https://api.x.ai/v1/chat/completions";
422
+ var ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages";
423
+ var CODEX_REQUIRED_HEADERS = [
424
+ "chatgpt-account-id",
425
+ "OpenAI-Beta",
426
+ "originator"
427
+ ];
428
+ var ANTIGRAVITY_REQUIRED_HEADERS = [
429
+ "User-Agent"
430
+ // antigravity-specific UA (matches getAntigravityUserAgent)
431
+ ];
432
+ function agentShouldUseServerProxy(agentConfig) {
433
+ return shouldUseServerProxy(agentConfig);
434
+ }
435
+ function resolveAgentCallPlan(agentConfig, _env) {
436
+ const apiKeyRef = asTrimmedLowercaseString(agentConfig.apiKeyRef);
437
+ const provider = asTrimmedLowercaseString(
438
+ agentConfig.provider ?? agentConfig.apiSource
439
+ );
440
+ if (isAntigravityOAuthAgent(agentConfig)) {
441
+ return {
442
+ authMethod: { kind: "oauth", ref: "antigravity" },
443
+ transport: "server-proxy",
444
+ upstreamWire: "gemini-cca",
445
+ endpoint: ANTIGRAVITY_CLOUD_CODE_BASE_URL,
446
+ requiredHeaders: [...ANTIGRAVITY_REQUIRED_HEADERS],
447
+ vendor: provider || "google-antigravity"
448
+ };
449
+ }
450
+ if (apiKeyRef === "chatgpt") {
451
+ return {
452
+ authMethod: { kind: "oauth", ref: "chatgpt" },
453
+ transport: "server-proxy",
454
+ upstreamWire: "responses",
455
+ endpoint: CODEX_RESPONSES_URL,
456
+ requiredHeaders: [...CODEX_REQUIRED_HEADERS],
457
+ vendor: provider || "openai"
458
+ };
459
+ }
460
+ if (apiKeyRef === "claude") {
461
+ return {
462
+ authMethod: { kind: "oauth", ref: "claude" },
463
+ transport: "server-proxy",
464
+ upstreamWire: "anthropic-messages",
465
+ endpoint: ANTHROPIC_MESSAGES_URL,
466
+ requiredHeaders: ["anthropic-version", "anthropic-beta"],
467
+ vendor: provider || "anthropic"
468
+ };
469
+ }
470
+ if (apiKeyRef === "xai") {
471
+ return {
472
+ authMethod: { kind: "oauth", ref: "xai" },
473
+ transport: "server-proxy",
474
+ upstreamWire: "chat.completions",
475
+ endpoint: XAI_CHAT_COMPLETIONS_URL,
476
+ requiredHeaders: [],
477
+ vendor: provider || "xai"
478
+ };
479
+ }
480
+ if (apiKeyRef === "cursor") {
481
+ return {
482
+ authMethod: { kind: "oauth", ref: "cursor" },
483
+ transport: "direct",
484
+ upstreamWire: "cursor-connect",
485
+ endpoint: CURSOR_AGENT_URL,
486
+ requiredHeaders: [
487
+ "x-cursor-client-version",
488
+ "x-cursor-client-type",
489
+ "x-ghost-mode"
490
+ ],
491
+ vendor: provider || "cursor"
492
+ };
493
+ }
494
+ if (agentConfig.cliProvider || agentConfig.apiSource === "cli" || provider === "cli") {
495
+ return {
496
+ authMethod: { kind: "cli", provider: agentConfig.cliProvider || provider || "codex" },
497
+ transport: "direct",
498
+ upstreamWire: "cli",
499
+ endpoint: "",
500
+ requiredHeaders: [],
501
+ vendor: provider || "cli"
502
+ };
503
+ }
504
+ if (agentConfig.customProviderUrl || agentConfig.apiSource === "custom") {
505
+ const transport2 = agentShouldUseServerProxy(agentConfig) ? "server-proxy" : "direct";
506
+ const endpoint2 = asOptionalTrimmedString(agentConfig.customProviderUrl) ?? "";
507
+ const upstreamWire2 = endpoint2.includes("/responses") ? "responses" : "chat.completions";
508
+ return {
509
+ authMethod: { kind: "custom-key" },
510
+ transport: transport2,
511
+ upstreamWire: upstreamWire2,
512
+ endpoint: endpoint2,
513
+ requiredHeaders: [],
514
+ vendor: provider || "custom"
515
+ };
516
+ }
517
+ const transport = agentShouldUseServerProxy(agentConfig) ? "server-proxy" : "direct";
518
+ const useResponses = isOpenAiResponsesModel({
519
+ provider,
520
+ model: agentConfig.model,
521
+ endpointKey: agentConfig.endpointKey
522
+ });
523
+ const upstreamWire = useResponses ? "responses" : "chat.completions";
524
+ const endpoint = useResponses ? OPENAI_RESPONSES_ENDPOINT : resolvePlatformChatCompletionsEndpoint(provider) ?? "";
525
+ return {
526
+ authMethod: { kind: "platform-key" },
527
+ transport,
528
+ upstreamWire,
529
+ endpoint,
530
+ requiredHeaders: [],
531
+ vendor: provider || "openai"
532
+ };
533
+ }
534
+
535
+ // packages/ai/llm/usageRequestOptions.ts
536
+ var STREAM_USAGE_PROVIDERS = /* @__PURE__ */ new Set([
537
+ "google",
538
+ "openrouter",
539
+ "xai",
540
+ "openai",
541
+ "fireworks",
542
+ "mistral",
543
+ "cloudflare",
544
+ "gmi"
545
+ ]);
546
+ var EXTRA_USAGE_FIELD_PROVIDERS = /* @__PURE__ */ new Set(["openrouter"]);
547
+ var normalizeProviderName = (providerName) => asTrimmedLowercaseString(providerName);
548
+ var getUsageRequestOptions = (providerName, options) => {
549
+ const normalizedProvider = normalizeProviderName(providerName);
550
+ const api = options?.api ?? "chat-completions";
551
+ if (api === "responses") {
552
+ return EXTRA_USAGE_FIELD_PROVIDERS.has(normalizedProvider) ? {
553
+ usage: {
554
+ include: true
555
+ }
556
+ } : {};
557
+ }
558
+ return {
559
+ ...STREAM_USAGE_PROVIDERS.has(normalizedProvider) ? {
560
+ stream_options: {
561
+ include_usage: true
562
+ }
563
+ } : {},
564
+ ...EXTRA_USAGE_FIELD_PROVIDERS.has(normalizedProvider) ? {
565
+ usage: {
566
+ include: true
567
+ }
568
+ } : {}
569
+ };
570
+ };
571
+
572
+ // packages/app/i18n/mapLanguage.ts
573
+ var languageMap = {
574
+ "en-US": "English",
575
+ "zh-CN": "Simplified Chinese",
576
+ "zh-TW": "Traditional Chinese",
577
+ "ja-JP": "Japanese"
578
+ // Add more mappings as needed
579
+ };
580
+ var mapLanguage = (responseLanguage) => {
581
+ return languageMap[responseLanguage] || responseLanguage;
582
+ };
583
+
584
+ // packages/ai/agent/pageBuilderHandoffRules.ts
585
+ var PAGE_BUILDER_AGENT_PUBLIC_KEY = "agent-pub-01PAGEBUILDR00000000FT7R9G";
586
+ var PAGE_BUILDER_SCENARIOS = [
587
+ {
588
+ id: "information-display",
589
+ label: "\u4FE1\u606F\u5C55\u793A",
590
+ userIntent: "\u4E3B\u9875\u3001\u4EA7\u54C1\u4ECB\u7ECD\u3001\u670D\u52A1\u4ECB\u7ECD\u3001\u4F5C\u54C1\u96C6\u3001\u6D3B\u52A8\u9875\u3001\u62A5\u4EF7\u9875",
591
+ prompt: "\u5E2E\u6211\u505A\u4E00\u4E2A\u72EC\u7ACB AI \u4EA7\u54C1\u987E\u95EE\u7684\u4E2A\u4EBA\u4E3B\u9875\u3002\u8981\u770B\u8D77\u6765\u4E13\u4E1A\uFF0C\u5305\u542B\u4E2A\u4EBA\u5B9A\u4F4D\u3001\u80FD\u63D0\u4F9B\u7684\u670D\u52A1\u5361\u7247\u3001\u4EE3\u8868\u6210\u679C\u5361\u7247\u3001\u53EF\u4FE1\u80CC\u4E66\u548C\u8054\u7CFB\u5408\u4F5C\u6309\u94AE\u3002"
592
+ },
593
+ {
594
+ id: "data-analysis",
595
+ label: "\u6570\u636E\u5206\u6790",
596
+ userIntent: "\u65E5\u62A5\u3001\u5468\u62A5\u3001\u7ECF\u8425\u770B\u677F\u3001\u8D28\u68C0\u62A5\u544A\u3001\u9500\u552E\u6F0F\u6597\u3001\u53CD\u9988\u5206\u6790",
597
+ prompt: "\u5E2E\u6211\u505A\u4E00\u4E2A AI \u5BA2\u670D\u8D28\u68C0\u65E5\u62A5\uFF0C\u5305\u542B\u6838\u5FC3\u6307\u6807\u3001\u8FD1 7 \u5929\u98CE\u9669\u8D8B\u52BF\u3001\u5F02\u5E38\u4F1A\u8BDD\u660E\u7EC6\u8868\uFF0C\u4EE5\u53CA\u660E\u5929\u9700\u8981\u8DDF\u8FDB\u7684\u5EFA\u8BAE\u3002"
598
+ },
599
+ {
600
+ id: "process-guide",
601
+ label: "\u6D41\u7A0B\u8BF4\u660E",
602
+ userIntent: "\u6559\u7A0B\u3001SOP\u3001onboarding\u3001\u64CD\u4F5C\u6307\u5357\u3001\u8BFE\u7A0B\u6B65\u9AA4\u3001\u7533\u8BF7\u6D41\u7A0B",
603
+ prompt: "\u5E2E\u6211\u505A\u4E00\u4E2A\u65B0\u5458\u5DE5\u4F7F\u7528 CRM \u7684\u4EA4\u4E92\u6559\u7A0B\u9875\u9762\uFF0C\u5305\u542B\u5B66\u4E60\u76EE\u6807\u3001\u64CD\u4F5C\u6B65\u9AA4\u3001\u793A\u4F8B\u7EC3\u4E60\u3001\u68C0\u67E5\u6E05\u5355\u548C\u4E0B\u4E00\u6B65\u6309\u94AE\u3002"
604
+ },
605
+ {
606
+ id: "decision-comparison",
607
+ label: "\u51B3\u7B56\u6BD4\u8F83",
608
+ userIntent: "\u65B9\u6848\u5BF9\u6BD4\u3001\u4EA7\u54C1\u9009\u578B\u3001\u5019\u9009\u4EBA\u5BF9\u6BD4\u3001\u7ADE\u54C1\u5206\u6790\u3001\u91C7\u8D2D\u5EFA\u8BAE",
609
+ prompt: "\u5E2E\u6211\u505A\u4E00\u4E2A\u4E09\u6B3E CRM \u65B9\u6848\u5BF9\u6BD4\u9875\uFF0C\u5305\u542B\u5BF9\u6BD4\u7EF4\u5EA6\u8868\u683C\u3001\u6BCF\u4E2A\u65B9\u6848\u7684\u4F18\u7F3A\u70B9\u5361\u7247\u3001\u8BC4\u5206\u3001\u9002\u5408\u56E2\u961F\u7C7B\u578B\u548C\u6700\u7EC8\u63A8\u8350\u3002"
610
+ },
611
+ {
612
+ id: "plan-roadmap",
613
+ label: "\u8BA1\u5212\u6392\u5E03",
614
+ userIntent: "\u9879\u76EE\u8BA1\u5212\u3001\u5B66\u4E60\u8BA1\u5212\u3001\u5065\u8EAB\u8BA1\u5212\u3001\u5185\u5BB9\u65E5\u5386\u3001\u53D1\u5E03\u8282\u594F",
615
+ prompt: "\u5E2E\u6211\u505A\u4E00\u4E2A 30 \u5929\u5185\u5BB9\u53D1\u5E03\u8BA1\u5212\u9875\u9762\uFF0C\u5305\u542B\u9636\u6BB5\u76EE\u6807\u3001\u6BCF\u5468\u4EFB\u52A1\u3001\u4F18\u5148\u7EA7\u3001\u91CC\u7A0B\u7891\u5361\u7247\u548C\u98CE\u9669\u63D0\u9192\u3002"
616
+ },
617
+ {
618
+ id: "mixed-pitch",
619
+ label: "\u6DF7\u5408\u957F\u5C3E",
620
+ userIntent: "\u6C47\u62A5\u9875\u3001\u878D\u8D44\u6750\u6599\u3001\u590D\u6742\u9879\u76EE\u6982\u89C8\uFF0C\u6DF7\u5408\u5C55\u793A\u3001\u6570\u636E\u3001\u8BA1\u5212\u3001\u5BF9\u6BD4",
621
+ prompt: "\u7ED9\u4E00\u4E2A\u65E9\u671F AI \u5BA2\u670D\u521B\u4E1A\u9879\u76EE\u505A\u4E00\u9875\u878D\u8D44\u6C47\u62A5\u9875\uFF0C\u5305\u542B\u5E02\u573A\u673A\u4F1A\u3001\u5173\u952E\u6570\u636E\u6307\u6807\u5361\u3001\u589E\u957F\u8D8B\u52BF\u56FE\u3001\u4EA7\u54C1\u8DEF\u7EBF\u3001\u7ADE\u54C1\u5BF9\u6BD4\u8868\u3001\u56E2\u961F\u4ECB\u7ECD\u548C\u4E0B\u4E00\u6B65\u8BA1\u5212\u3002"
622
+ }
623
+ ];
624
+ var scenarioLines = PAGE_BUILDER_SCENARIOS.map(
625
+ (scenario) => `- ${scenario.label}\uFF1A${scenario.userIntent}`
626
+ ).join("\n");
627
+ var PAGE_BUILDER_HANDOFF_INSTRUCTIONS = `--- \u9875\u9762\u751F\u6210\u52A9\u624B handoff ---
628
+ \u5F53\u7528\u6237\u9700\u8981\u628A\u5185\u5BB9\u53D8\u6210\u201C\u53EF\u770B\u7684\u9875\u9762/\u62A5\u544A/\u770B\u677F/\u6559\u7A0B/\u5BF9\u6BD4\u9875/\u8BA1\u5212\u9875\u201D\u65F6\uFF0C\u53EF\u4EE5\u628A\u672C\u8F6E\u4EA4\u7ED9\u9875\u9762\u751F\u6210\u52A9\u624B\u3002
629
+
630
+ \u76EE\u6807 Agent:
631
+ - agentKey: ${PAGE_BUILDER_AGENT_PUBLIC_KEY}
632
+ - \u63A8\u8350\u5DE5\u5177: runStreamingAgent
633
+
634
+ \u9002\u5408 handoff \u7684\u89C6\u89C9\u610F\u56FE\u5927\u7C7B\uFF1A
635
+ ${scenarioLines}
636
+
637
+ \u8C03\u7528\u8FB9\u754C\uFF1A
638
+ - \u7528\u6237\u660E\u786E\u8981\u6C42\u201C\u505A\u6210\u9875\u9762 / \u770B\u677F / \u62A5\u544A / \u6559\u7A0B / \u4E3B\u9875 / \u5BF9\u6BD4\u9875 / \u8BA1\u5212\u8868 / \u53EF\u89C6\u5316\u201D\u65F6\uFF0C\u53EF\u4EE5\u76F4\u63A5 runStreamingAgent\u3002
639
+ - \u5982\u679C\u7528\u6237\u53EA\u662F\u8BA8\u8BBA\u5185\u5BB9\uFF0C\u4F46\u4F60\u5224\u65AD\u201C\u6587\u5B57\u56DE\u7B54\u4E0D\u5982\u53EF\u89C6\u5316\u9875\u9762\u201D\uFF0C\u5148\u8BE2\u95EE\u7528\u6237\uFF1A\u201C\u8FD9\u4E2A\u66F4\u9002\u5408\u505A\u6210\u4E00\u9875\u53EF\u89C6\u5316\u9875\u9762\uFF0C\u8981\u6211\u751F\u6210\u4E00\u4E2A\u53EF\u4EA4\u4E92\u7248\u672C\u5417\uFF1F\u201D
640
+ - \u4E0D\u8981\u628A\u666E\u901A\u95EE\u7B54\u3001\u95F2\u804A\u3001\u4EE3\u7801\u89E3\u91CA\u3001\u7EAF\u6587\u672C\u603B\u7ED3\u5F3A\u884C\u4EA4\u7ED9\u9875\u9762\u751F\u6210\u52A9\u624B\u3002
641
+ - handoff \u65F6\uFF0C\u628A\u7528\u6237\u539F\u59CB\u9700\u6C42\u548C\u4F60\u5DF2\u786E\u8BA4\u7684\u4E1A\u52A1\u4E0A\u4E0B\u6587\u4E00\u8D77\u653E\u8FDB userInput\uFF0C\u4E0D\u8981\u8981\u6C42\u7528\u6237\u7406\u89E3 React\u3001HTML\u3001\u4EE3\u7801\u5757\u6216\u8FD0\u884C\u65F6\u3002
642
+ - \u9875\u9762\u751F\u6210\u52A9\u624B\u53EA\u8D1F\u8D23\u751F\u6210\u548C\u4FEE\u6539\u53EF\u4EA4\u4E92\u9875\u9762\uFF1B\u4F60\u4ECD\u8D1F\u8D23\u5224\u65AD\u3001\u89E3\u91CA\u3001\u6F84\u6E05\u548C\u540E\u7EED\u534F\u8C03\u3002`;
643
+
644
+ // packages/ai/agent/contextCompiler.ts
645
+ function createHash(_algo) {
646
+ let buf = "";
647
+ return {
648
+ update(s) {
649
+ buf += s;
650
+ return this;
651
+ },
652
+ digest(_enc) {
653
+ let h = 2166136261;
654
+ for (let i = 0; i < buf.length; i++) {
655
+ h ^= buf.charCodeAt(i);
656
+ h = h * 16777619 >>> 0;
657
+ }
658
+ return h.toString(16).padStart(8, "0");
659
+ }
660
+ };
661
+ }
662
+ var hasLayerContent = (layer) => Boolean(layer.content);
663
+ var estimateContextTokens = (content) => Math.ceil(content.length / 4);
664
+ var compileContextLayers = (layers) => {
665
+ const compiledLayers = [];
666
+ for (const layer of layers) {
667
+ if (!hasLayerContent(layer)) continue;
668
+ const estimatedTokens = estimateContextTokens(layer.content);
669
+ compiledLayers.push({
670
+ id: layer.id,
671
+ owner: layer.owner,
672
+ content: layer.content,
673
+ cacheScope: layer.cacheScope ?? "turn",
674
+ charCount: layer.content.length,
675
+ estimatedTokens,
676
+ tokenBudget: layer.tokenBudget,
677
+ budgetStatus: typeof layer.tokenBudget === "number" ? estimatedTokens <= layer.tokenBudget ? "within-budget" : "over-budget" : void 0
678
+ });
679
+ }
680
+ const stablePrefixLayers = [];
681
+ for (const layer of compiledLayers) {
682
+ if (layer.cacheScope === "turn") break;
683
+ stablePrefixLayers.push(layer);
684
+ }
685
+ const stablePrefixContent = stablePrefixLayers.map((layer) => layer.content).join("\n\n");
686
+ const dynamicLayers = compiledLayers.slice(stablePrefixLayers.length);
687
+ const dynamicContent = dynamicLayers.map((layer) => layer.content).join("\n\n");
688
+ return {
689
+ content: compiledLayers.map((layer) => layer.content).join("\n\n"),
690
+ stablePrefixContent,
691
+ dynamicContent,
692
+ layers: compiledLayers,
693
+ cacheProfile: {
694
+ stablePrefixHash: createHash("sha256").update(stablePrefixContent).digest("hex"),
695
+ stablePrefixLayerIds: stablePrefixLayers.map((layer) => layer.id),
696
+ stablePrefixCharCount: stablePrefixContent.length,
697
+ stablePrefixEstimatedTokens: estimateContextTokens(stablePrefixContent)
698
+ }
699
+ };
700
+ };
701
+
702
+ // packages/ai/agent/buildSystemPrompt.ts
703
+ var CONTEXT_USAGE_INSTRUCTIONS = `\u53C2\u8003\u8D44\u6599\u4F7F\u7528\u8BF4\u660E\uFF1A
704
+ - \u4E0B\u65B9\u63D0\u4F9B\u7684\u8D44\u6599\u662F\u4F60\u7684\u4E3B\u8981\u6743\u5A01\u4FE1\u606F\u6765\u6E90\u3002
705
+ - \u56DE\u7B54\u95EE\u9898\u65F6\uFF0C\u5E94\u4F18\u5148\u4F9D\u8D56\u8FD9\u4E9B\u8D44\u6599\u3002\u5B83\u4EEC\u6309\u4F18\u5148\u7EA7\u4ECE\u9AD8\u5230\u4F4E\u6392\u5217\u3002
706
+ - \u4F7F\u7528\u5176\u4E2D\u7684\u4E8B\u5B9E\u3001\u6570\u636E\u548C\u540D\u79F0\u65F6\uFF0C\u8981\u4FDD\u6301\u7CBE\u51C6\u3002
707
+ - \u5982\u679C\u8D44\u6599\u4E2D\u6CA1\u6709\u5305\u542B\u7B54\u6848\uFF0C\u5E94\u8BF4\u660E\u8FD9\u4E00\u70B9\uFF0C\u7136\u540E\u518D\u4F7F\u7528\u4F60\u7684\u901A\u7528\u77E5\u8BC6\u8FDB\u884C\u56DE\u7B54\u3002
708
+ - \u5982\u679C\u4F60\u5728\u8D44\u6599\u4E2D\u53D1\u73B0\u76F8\u4E92\u77DB\u76FE\u7684\u4FE1\u606F\uFF0C\u4E5F\u8981\u5728\u56DE\u7B54\u4E2D\u6307\u51FA\u8FD9\u4E00\u70B9\u3002
709
+ - \u5F53\u901A\u7528\u6307\u4EE4\u4E0E\u66F4\u5177\u4F53\u7684"\u6309 Agent / \u6309\u6587\u6863"\u7684\u89C4\u5219\u53D1\u751F\u51B2\u7A81\u65F6\uFF0C\u5FC5\u987B\u4F18\u5148\u9075\u5B88\u66F4\u5177\u4F53\u3001\u4F18\u5148\u7EA7\u66F4\u9AD8\u7684\u89C4\u5219\u3002`;
710
+ var MENU_USAGE_INSTRUCTIONS = `--- \u4EA4\u4E92\u8BF4\u660E ---
711
+ \u6240\u6709\u7528\u6237\u8F93\u5165\u5747\u4E3A\u7EAF\u6587\u672C\u6D88\u606F\uFF0C\u76F4\u63A5\u7406\u89E3\u5373\u53EF\uFF0C\u4E0D\u8981\u5728\u56DE\u590D\u4E2D\u63D0\u53CA\u6309\u94AE\u3001\u83DC\u5355\u3001\u754C\u9762\u7B49 UI \u5143\u7D20\u3002
712
+
713
+ ## \u4F55\u65F6\u8C03\u7528 ui_ask_choice
714
+ \u9ED8\u8BA4\u503E\u5411"\u76F4\u63A5\u884C\u52A8"\uFF1A\u5F53\u4F60\u80FD\u57FA\u4E8E\u73B0\u6709\u4E0A\u4E0B\u6587\u7ED9\u51FA\u9AD8\u8D28\u91CF\u7B54\u6848\u6216\u6267\u884C\u65F6\uFF0C\u4F18\u5148\u76F4\u63A5\u505A\uFF0C\u4E0D\u8981\u4E3A\u4E86\u95EE\u800C\u95EE\u3002\u4EC5\u5728\u4EE5\u4E0B\u60C5\u51B5\u8C03\u7528 ui_ask_choice\uFF1A
715
+ 1\uFF09\u7528\u6237\u9700\u6C42\u5BBD\u6CDB\u6216\u6A21\u7CCA\uFF0C\u4E14\u4F60\u80FD\u7ED9\u51FA 2\uFF5E5 \u4E2A\u4E92\u65A5\u3001\u90FD\u5408\u7406\u7684\u65B9\u5411\u5019\u9009\u2014\u2014\u8BA9\u7528\u6237\u5148\u9009\u4E00\u4E2A\u65B9\u5411\u518D\u6DF1\u5165\uFF1B
716
+ 2\uFF09\u8BA1\u5212/\u6D41\u7A0B\u5230\u4E86\u771F\u6B63\u7684\u5206\u652F\u8282\u70B9\uFF0C\u4E0D\u540C\u9009\u62E9\u4F1A\u5BFC\u81F4\u663E\u8457\u4E0D\u540C\u7684\u6210\u672C\u3001\u9690\u79C1\u6216\u7ED3\u679C\u8D70\u5411\uFF0C\u4E14\u4F60\u65E0\u6CD5\u4ECE\u4E0A\u4E0B\u6587\u63A8\u65AD\u7528\u6237\u504F\u597D\uFF1B
717
+ 3\uFF09\u65B0\u4F1A\u8BDD\u5F00\u5934\uFF0C\u6839\u636E\u7528\u6237\u753B\u50CF\u7ED9\u51FA\u82E5\u5E72"\u63A5\u4E0B\u6765\u53EF\u4EE5\u5C1D\u8BD5\u7684\u4E8B\u60C5"\u4F5C\u4E3A\u529F\u80FD\u5BFC\u822A\u6216\u4F7F\u7528\u5F15\u5BFC\u3002
718
+
719
+ ## \u8C03\u7528 ui_ask_choice \u7684\u89C4\u8303
720
+ - \u63D0\u4F9B 2\uFF5E5 \u4E2A\u4E92\u65A5\u9009\u9879\uFF1B\u5982\u679C\u4F60\u6709\u63A8\u8350\u65B9\u5411\uFF0C\u628A\u5B83\u653E\u5728 choices \u7684\u7B2C\u4E00\u4F4D\uFF1B
721
+ - \u6BCF\u4E2A\u9009\u9879\u7684 label \u5199\u7B80\u77ED\u6309\u94AE\u6587\u6848\uFF0CuserMessage \u5199\u6210\u5B8C\u6574\u7684\u4E0B\u4E00\u53E5\u8BDD\uFF0C\u65B9\u4FBF\u7528\u6237\u70B9\u51FB\u540E\u4E0A\u4E0B\u6587\u8FDE\u8D2F\uFF1B
722
+ - \u4E0D\u8981\u5728\u9009\u9879\u5217\u8868\u91CC\u653E"\u5176\u4ED6/Other"\u2014\u2014\u5BA2\u6237\u7AEF\u4F1A\u81EA\u52A8\u4E3A\u7528\u6237\u8FFD\u52A0\u81EA\u7531\u8F93\u5165\u7684\u9000\u8DEF\uFF1B
723
+ - \u628A\u8981\u95EE\u7528\u6237\u7684\u95EE\u9898\u5199\u5728 question \u5B57\u6BB5\u91CC\uFF0C\u4E0D\u8981\u5728\u540C\u4E00\u8F6E assistant \u666E\u901A\u6587\u672C\u91CC\u91CD\u590D\u8FD9\u53E5\u8BDD\uFF1B
724
+ - \u5982\u679C\u7528\u6237\u7684\u76EE\u6807\u5DF2\u7ECF\u975E\u5E38\u5177\u4F53\u6E05\u6670\uFF0C\u5373\u4FBF\u4E0A\u8FF0\u6761\u4EF6\u770B\u4F3C\u6EE1\u8DB3\uFF0C\u4E5F\u4F18\u5148\u76F4\u63A5\u56DE\u7B54\uFF0C\u4E0D\u8981\u5F3A\u884C\u5F39\u9009\u62E9\u83DC\u5355\u3002`;
725
+ var WEBPAGE_ACCESS_INSTRUCTIONS = `--- \u7F51\u9875\u8BBF\u95EE\u80FD\u529B (Web Access) ---
726
+ \u83B7\u53D6\u5916\u90E8\u4FE1\u606F\u65F6\u7531\u7B80\u5165\u7E41\uFF1A
727
+ 0. \u7528\u6237\u5DF2\u7ED9\u660E\u786E URL \u2192 \u5148\u76F4\u63A5 fetch \u8FD9\u4E9B URL\uFF0C\u4E0D\u8981\u5148\u641C\u7D22\u6216\u731C\u5907\u7528\u7F51\u5740\u3002\u5B83\u4EEC\u662F\u672C\u6B21\u4EFB\u52A1\u6700\u9AD8\u4F18\u5148\u7EA7\u7684\u7F51\u9875\u771F\u503C\u3002\u4EC5\u5F53\u6293\u53D6\u5931\u8D25\u3001\u7F3A\u5B57\u6BB5\u6216\u5185\u5BB9\u4E0D\u5339\u914D\u65F6\u624D\u989D\u5916\u641C\u7D22\uFF0C\u5E76\u5728\u56DE\u590D\u4E2D\u8BF4\u660E\u964D\u7EA7\u539F\u56E0\u3002
728
+ 1. \u65E0\u660E\u786E URL \u2192 \u5148\u7528 exa_search \u53D1\u73B0\u6743\u5A01\u5165\u53E3\uFF08\u5C24\u5176\u964C\u751F docs \u7AD9\uFF0C\u4E0D\u8981\u76F4\u63A5\u731C\u5B50\u8DEF\u5F84\uFF09\u3002
729
+ 2. \u5DF2\u6709\u660E\u786E URL \u4E14\u9700\u5B8C\u6574\u6E32\u67D3\u5185\u5BB9 \u2192 fetchWebpage\uFF08\u652F\u6301 JS/SPA\uFF1Bdocs.* \u4F1A\u81EA\u52A8\u68C0\u67E5 /llms.txt \u5E76\u89C4\u8303\u5316 URL\uFF09\u3002
730
+ 3. \u9700\u767B\u5F55/\u586B\u8868/\u591A\u6B65\u4EA4\u4E92 \u2192 browser_openSession\uFF08openSession \u62FF ID \u2192 typeText/click/readContent\uFF09\u3002
731
+ 4. YouTube/\u4E9A\u9A6C\u900A/Google \u7B49\u7ED3\u6784\u5316\u6570\u636E \u2192 \u7528\u5BF9\u5E94\u4E13\u7528 Scraper \u5DE5\u5177\uFF08youtubeScraper\u3001amazonProductScraper \u7B49\uFF09\u3002`;
732
+ var AGENT_ORCHESTRATION_INSTRUCTIONS = `--- Agent \u7F16\u6392\u4E0E\u534F\u4F5C ---
733
+ \u4F60\u6240\u5728\u7684\u7CFB\u7EDF\u652F\u6301\u591A\u4E2A\u5B50 Agent \u548C\u5DE5\u4F5C\u6D41\u5DE5\u5177\uFF0C\u8BF7\u628A\u81EA\u5DF1\u89C6\u4E3A"\u603B\u534F\u8C03\u8005"\uFF1A
734
+
735
+ 1\uFF09\u5B50 Agent \u534F\u4F5C
736
+ - \u5982\u679C\u76EE\u6807 Agent \u8BB0\u5F55\u5DF2\u7ECF\u58F0\u660E delegation.serverBase / runtimeServerBase\uFF0C\u5DE5\u5177\u4F1A\u81EA\u52A8\u8DEF\u7531\u5230\u5BF9\u5E94 nolo server\uFF1B\u4F60\u4E0D\u9700\u8981\u91CD\u590D\u586B\u5199 serverBase\u3002
737
+ - \u5982\u679C\u7528\u6237\u660E\u786E\u7ED9\u4E86\u53E6\u4E00\u4E2A\u53EF\u8BBF\u95EE\u7684 server origin\uFF08\u4F8B\u5982 Windows \u673A\u5668\u7684 Cloudflare \u57DF\u540D\uFF09\uFF0C\u53EF\u4EE5\u5728\u5DE5\u5177\u53C2\u6570\u91CC\u4F20 serverBase \u8986\u76D6\u81EA\u52A8\u8DEF\u7531\uFF1B\u4E0D\u8981\u81C6\u9020\u5730\u5740\uFF0C\u4E5F\u4E0D\u8981\u628A\u666E\u901A localhost \u5F53\u6210\u8FDC\u7AEF\u673A\u5668\u3002
738
+ - \u9700\u8981\u5F02\u6B65\u542F\u52A8\u4E00\u4E2A\u5B50\u5BF9\u8BDD\u3001\u8BA9\u5F53\u524D\u5BF9\u8BDD\u7A0D\u540E\u6839\u636E\u5B50 Agent \u7684\u5B8C\u6210/\u5931\u8D25\u7EE7\u7EED\u5224\u65AD\u65F6\uFF0C\u4F7F\u7528 callAgent({ background: true })\u3002\u5B83\u53EA\u8868\u793A child dialog \u5DF2\u542F\u52A8\u6216\u6392\u961F\uFF0C\u4E0D\u8868\u793A\u4EFB\u52A1\u5DF2\u7ECF\u5B8C\u6210\uFF1Bchild \u8FDB\u5165 done/failed \u540E\uFF0C\u7CFB\u7EDF\u4F1A\u7528 terminal wake \u7EE7\u7EED\u7236\u5BF9\u8BDD\uFF0C\u4F60\u518D\u8BFB\u53D6 child evidence \u51B3\u5B9A\u4E0B\u4E00\u6B65\u3002
739
+ - callAgent({ background: true }) \u662F\u901A\u7528\u591A Agent \u534F\u4F5C\u80FD\u529B\uFF0C\u4E0D\u9650\u4E8E\u4EE3\u7801\u4EFB\u52A1\uFF1B\u6E38\u620F\u8BBE\u8BA1\u3001\u7535\u5F71\u7B56\u5212\u3001\u5199\u4F5C\u3001\u8FD0\u8425\u3001\u7814\u7A76\u7B49\u9700\u8981\u5F02\u6B65\u5206\u5DE5\u7684\u573A\u666F\u4E5F\u53EF\u4EE5\u4F7F\u7528\u3002
740
+ - \u9700\u8981\u7B49\u5F85\u4E00\u4E2A\u77ED\u7ED3\u679C\u5E76\u76F4\u63A5\u7EFC\u5408\u65F6\uFF0C\u4F7F\u7528 callAgent\uFF08\u9ED8\u8BA4\u540C\u6B65\u7B49\u5F85\uFF09\uFF1B\u9700\u8981\u7528\u6237\u524D\u53F0\u5B9E\u65F6\u770B\u5230\u53E6\u4E00\u4E2A Agent \u53D1\u8A00\u65F6\uFF0C\u4F7F\u7528 runStreamingAgent\u3002
741
+ - \u5F53\u7528\u6237\u9700\u8981\u591A\u89C6\u89D2\u5206\u6790\u6216\u8FA9\u8BBA\u65F6\uFF0C\u4F60\u53EF\u4EE5\uFF1A
742
+ - \u5148\u7528 callAgent \u4F9D\u6B21\u8BE2\u95EE\u591A\u4E2A Agent \u5BF9\u540C\u4E00\u95EE\u9898\u7684\u770B\u6CD5\uFF1B
743
+ - \u5728\u6700\u540E\u4E00\u6761\u56DE\u590D\u4E2D\uFF0C\u7528\u4F60\u81EA\u5DF1\u7684\u8BDD\u5E2E\u7528\u6237\u603B\u7ED3\u8FD9\u4E9B\u89C2\u70B9\u7684\u5F02\u540C\uFF0C\u5E76\u7ED9\u51FA\u7EFC\u5408\u7ED3\u8BBA\u3002
744
+
745
+ 2\uFF09\u5DE5\u4F5C\u6D41 / Workflow \u5DE5\u5177
746
+ - \u5BF9\u4E8E\u9700\u8981\u591A\u6B65\u9AA4\u3001\u987A\u5E8F\u4F9D\u8D56\u6216\u6279\u91CF\u5DE5\u5177\u8C03\u7528\u7684\u590D\u6742\u4EFB\u52A1\uFF0C\u5E94\u4F18\u5148\u8003\u8651\u4F7F\u7528 createWorkflow \u8FD9\u7C7B\u5DE5\u4F5C\u6D41\u5DE5\u5177\u3002
747
+ - \u8C03\u7528\u5DE5\u4F5C\u6D41\u5DE5\u5177\u65F6\uFF0C\u4F60\u8D1F\u8D23\uFF1A
748
+ - \u6E05\u695A\u63CF\u8FF0\u76EE\u6807\u548C\u7EA6\u675F\uFF1B
749
+ - \u5728\u5DE5\u4F5C\u6D41\u6267\u884C\u8FC7\u7A0B\u4E2D\u5173\u6CE8\u5176\u8F93\u51FA\u7684\u4E2D\u95F4\u7ED3\u679C\u548C\u6700\u7EC8\u7ED3\u679C\uFF1B
750
+ - \u5F53\u4F60\u8BA4\u4E3A\u4EFB\u52A1\u8DB3\u591F\u5B8C\u6210\uFF0C\u6216\u7528\u6237\u8981\u6C42\u603B\u7ED3\u65F6\uFF0C\u5BF9\u6574\u4E2A\u8FC7\u7A0B\u548C\u7ED3\u679C\u8FDB\u884C\u603B\u7ED3\uFF0C\u6307\u51FA\u53EF\u80FD\u7684\u9519\u8BEF\u6216\u98CE\u9669\u3002
751
+
752
+ 3\uFF09\u5371\u9669 / \u4E0D\u53EF\u9006\u64CD\u4F5C
753
+ - \u6D89\u53CA\u4E0D\u53EF\u9006\u64CD\u4F5C\u65F6\uFF08\u4FEE\u6539\u6587\u4EF6\u3001\u5220\u9664\u6570\u636E\u3001\u53D1\u9001\u6D88\u606F\u3001\u751F\u6210\u6B63\u5F0F\u6587\u4EF6\u3001\u6267\u884C\u4EA4\u6613\u7B49\uFF09\uFF0C\u8BF7\u4F18\u5148\u9884\u89C8\u6216\u5411\u7528\u6237\u786E\u8BA4\u3002
754
+ - \u5F53\u5DE5\u5177\u8FD4\u56DE"\u9884\u89C8"\u6216"\u5F85\u786E\u8BA4"\u72B6\u6001\u65F6\uFF0C\u8BF7\u6682\u505C\u8FDB\u4E00\u6B65\u81EA\u52A8\u4FEE\u6539\uFF0C\u7B49\u5F85\u7528\u6237\u660E\u786E\u786E\u8BA4\u6216\u53CD\u9988\u540E\u518D\u7EE7\u7EED\u3002\u4E0D\u8981\u5728\u7528\u6237\u672A\u786E\u8BA4\u524D\u8FDE\u7EED\u53D1\u51FA\u591A\u6B21\u7834\u574F\u6027\u4FEE\u6539\u3002`;
755
+ var KNOWLEDGE_MANAGEMENT_INSTRUCTIONS = `--- \u77E5\u8BC6\u7BA1\u7406 ---
756
+ \u4E09\u5C42\u77E5\u8BC6\uFF1A
757
+ 1. references\uFF08Agent \u914D\u7F6E\uFF0C\u6BCF\u6B21\u5BF9\u8BDD\u81EA\u52A8\u6CE8\u5165\uFF09\uFF1Atype=instruction \u8FDB prompt \u9876\u90E8\uFF08\u884C\u4E3A\u89C4\u5219\uFF09\uFF1Btype=knowledge \u4F5C\u53C2\u8003\u8D44\u6599\u3002\u652F\u6301 page/dialog/table \u5B8C\u6574\u5C55\u5F00\uFF1Bpage \u91CC\u7684 @mention \u53EA\u5C55\u5F00\u5143\u4FE1\u606F\uFF08\u6807\u9898+dbKey\uFF09\uFF0C\u4E0D\u9012\u5F52\u5C55\u5F00\u5185\u5BB9\u3002
758
+ 2. createDoc \u6587\u6863\uFF08\u6309\u9700 read\uFF09\uFF1A\u603B\u7D22\u5F15\u9875\u7528 @[page:PAGE-xxx|\u6807\u9898] \u6307\u5411\u7EC6\u5206\u9875\uFF1Bmention \u662F\u6307\u9488\uFF0C\u53D6\u5185\u5BB9\u5FC5\u987B read({ dbKey })\u3002
759
+ \u8BFB\u53D6\u8DEF\u5F84\uFF1Aprompt/references \u6709 \u2192 \u76F4\u63A5\u7528\uFF1B\u6CA1\u6709 \u2192 read \u7D22\u5F15\u9875\u627E\u7EC6\u5206\u9875 dbKey \u2192 read \u7EC6\u5206\u9875\u53D6\u5B8C\u6574\u5185\u5BB9\u3002
760
+ \u4F55\u65F6\u6C89\u6DC0\uFF1A\u7528\u6237\u7ED9\u4E86\u53EF\u590D\u7528\u4FE1\u606F / \u5B8C\u6210\u6709\u4EF7\u503C\u8C03\u7814 \u2192 createDoc\uFF08\u5E76 updateAgent \u52A0\u5165 references\uFF09\uFF1B\u7D22\u5F15\u7F3A\u5165\u53E3 \u2192 updateDoc \u8865 @mention\u3002\u4E0D\u8981\u628A\u4E00\u6B21\u6027\u5185\u5BB9\u5199\u6210\u77E5\u8BC6\u9875\u3002`;
761
+ var MEMORY_CAPTURE_INSTRUCTIONS = `--- \u957F\u671F\u8BB0\u5FC6 ---
762
+ \u4F60\u53EF\u7528 rememberMemory \u628A\u503C\u5F97\u957F\u671F\u4FDD\u7559\u7684\u4FE1\u606F\u5199\u6210\u4E00\u6761 episodic memory\u3002
763
+ - \u8BB0\u5F55\uFF1A\u7A33\u5B9A\u4E14\u5BF9\u672A\u6765\u534F\u4F5C\u6709\u5E2E\u52A9\u7684\u7528\u6237\u504F\u597D/\u5224\u65AD\u6807\u51C6/\u4FE1\u606F\u7EC4\u7EC7\u4E60\u60EF/\u573A\u666F\u5316\u6289\u62E9\uFF1B\u540E\u7EED\u53CD\u590D\u7528\u5230\u7684\u7A7A\u95F4\u5171\u8BC6\u3001\u534F\u4F5C\u7EA6\u5B9A\u3001\u56E2\u961F\u89C4\u5219\uFF1B\u4E0E\u5F53\u524D Agent \u6302\u94A9\u7684\u6709\u6548\u505A\u6CD5\u3002
764
+ - \u4E0D\u8BB0\u5F55\uFF1A\u4E00\u6B21\u6027\u4EFB\u52A1\u7EC6\u8282\u3001\u5F88\u5FEB\u8FC7\u671F\u7684\u4E8B\u5B9E\u3001\u4E3A\u51D1\u6570\u52C9\u5F3A\u62BD\u51FA\u7684\u5185\u5BB9\u3002
765
+ - scope \u6309\u5185\u5BB9\u6027\u8D28\u9009\uFF0C\u4E0D\u56FA\u5B9A\u4F18\u5148\u67D0\u4E00\u5C42\uFF1A
766
+ - Space \u534F\u4F5C\u7EA6\u5B9A/\u56E2\u961F\u89C4\u5219 \u2192 scope=space\uFF08\u4EC5\u5F53\u5F53\u524D dialog \u5DF2\u7ED1\u5B9A space\uFF09
767
+ - \u7528\u6237\u4E2A\u4EBA\u8EAB\u4EFD\u6216\u7EAF\u4E2A\u4EBA\u504F\u597D \u2192 scope=auto\uFF08\u9ED8\u8BA4\u8BB0\u5230\u7528\u6237\uFF0C\u6240\u6709 Agent \u90FD\u80FD\u53EC\u56DE\uFF09
768
+ - \u4E0E\u5F53\u524D Agent \u6302\u94A9\u7684\u6709\u6548\u505A\u6CD5 \u2192 scope=auto\uFF08runtime \u81EA\u52A8\u628A subject \u6807\u8BB0\u4E3A\u5F53\u524D Agent\uFF0C\u53EA\u6709\u8FD9\u4E2A Agent \u53EC\u56DE\uFF09
769
+ - \u5F53\u524D\u4EFB\u52A1\u7684\u4E34\u65F6\u8FDB\u5EA6 \u2192 \u4E0D\u8C03\u7528\uFF0C\u8D70\u5BF9\u8BDD\u4E0A\u4E0B\u6587
770
+ - \u65B9\u5F0F\uFF1A\u5199\u6210\u7B80\u77ED\u53EF\u590D\u7528\u7684\u62BD\u8C61\uFF08\u201C\u8BE5\u7528\u6237\u5728\u67D0\u573A\u666F\u901A\u5E38\u600E\u4E48\u9009/\u600E\u4E48\u534F\u4F5C\u201D\uFF09\uFF0C\u4E0D\u8981\u590D\u5236\u6574\u6BB5\u5BF9\u8BDD\u3002\u9ED8\u8BA4\u9759\u9ED8\u6267\u884C\uFF0C\u9664\u975E\u7528\u6237\u5728\u8BA8\u8BBA\u8BB0\u5FC6\u672C\u8EAB\u3002\u62FF\u4E0D\u51C6\u662F\u5426\u503C\u5F97\u8BB0\u65F6\uFF0C\u4F18\u5148\u8BB0\u4E0B\u53EF\u590D\u7528\u7684\u504F\u597D\u6216\u534F\u4F5C\u7EA6\u5B9A\u2014\u2014\u4E8B\u540E\u8FC7\u6EE4\u6BD4\u6F0F\u8BB0\u66F4\u6613\u8865\u6551\uFF1B\u4F46\u7EAF\u4E00\u6B21\u6027\u4EFB\u52A1\u7EC6\u8282\u3001\u5F88\u5FEB\u8FC7\u671F\u7684\u4E8B\u5B9E\u4ECD\u4E0D\u8981\u8BB0\u3002`;
771
+ var SELF_UPDATE_INSTRUCTIONS = `--- Agent \u81EA\u6211\u66F4\u65B0\u80FD\u529B ---
772
+
773
+ ## \u4F55\u65F6\u66F4\u65B0\u81EA\u5DF1
774
+ - \u91CD\u8981\u51B3\u7B56/\u8FDB\u5EA6\u53D8\u5316 \u2192 updateDoc \u5199\u56DE\u72B6\u6001\u9875
775
+ - \u503C\u5F97\u590D\u7528\u7684\u77E5\u8BC6 \u2192 createDoc \u5EFA\u7EC6\u5206\u9875\uFF0C\u518D\u6309\u9700\u8981\u66F4\u65B0\u81EA\u5DF1\u7684 references / greeting / introduction
776
+ - \u5C0F\u5E45\u4F53\u9A8C\u4F18\u5316 \u2192 updateSelf \u8C03\u6574 greeting / introduction / tags
777
+
778
+ ## \u66F4\u65B0\u539F\u5219
779
+ - \u4F18\u5148\u5F62\u6210\u6700\u5C0F\u3001\u53EF\u89E3\u91CA\u7684\u53D8\u66F4\uFF0C\u4E0D\u8981\u4E3A\u4E86\u201C\u663E\u5F97\u5728\u8FDB\u5316\u201D\u800C\u9891\u7E41\u6539\u81EA\u5DF1
780
+ - \u4F4E\u98CE\u9669\u6C89\u6DC0\u4F18\u5148\u5199\u5165 memory / doc\uFF1B\u53EA\u6709\u5F53\u8FD9\u4E9B\u77E5\u8BC6\u9700\u8981\u957F\u671F\u6539\u53D8\u4F60\u7684\u884C\u4E3A\u65B9\u5F0F\u65F6\uFF0C\u518D\u8003\u8651 updateSelf
781
+ - prompt / references / tools / model \u8FD9\u7C7B\u9AD8\u5F71\u54CD\u5B57\u6BB5\uFF0C\u9ED8\u8BA4\u6309\u9700\u8981\u786E\u8BA4\u6765\u5904\u7406\uFF0C\u4E0D\u8981\u9759\u9ED8\u5927\u6539
782
+ - \u5982\u679C\u5DE5\u5177\u8FD4\u56DE policy limit / ask / reject\uFF0C\u4E0D\u8981\u91CD\u590D\u5C1D\u8BD5\uFF0C\u5E94\u5148\u5411\u7528\u6237\u89E3\u91CA\u6216\u7B49\u5F85\u66F4\u9AD8\u6743\u9650\u786E\u8BA4
783
+ - \u6CA1\u6709\u53D1\u751F\u5B9E\u9645\u66F4\u65B0\u65F6\uFF0C\u4E0D\u8981\u5728\u56DE\u590D\u672B\u5C3E\u989D\u5916\u6C47\u62A5\u201C\u672A\u66F4\u65B0\u201D\u72B6\u6001`;
784
+ var GENERIC_AGENT_UPDATE_INSTRUCTIONS = `--- Agent \u7EF4\u62A4\u80FD\u529B ---
785
+ \u4F60\u62E5\u6709 updateAgent \u6743\u9650\uFF0C\u53EF\u4EE5\u66F4\u65B0\u6307\u5B9A\u7684 Agent\u3002
786
+
787
+ ## \u4F55\u65F6\u66F4\u65B0\u522B\u7684 Agent
788
+ - \u7528\u6237\u660E\u786E\u8981\u6C42\u4F60\u7EF4\u62A4\u3001\u4FEE\u590D\u6216\u6279\u91CF\u8C03\u6574\u53E6\u4E00\u4E2A Agent
789
+ - \u4F60\u9700\u8981\u4FEE\u6539\u7684\u76EE\u6807\u4E0D\u662F\u5F53\u524D\u6B63\u5728\u8FD0\u884C\u7684\u81EA\u5DF1
790
+
791
+ ## \u66F4\u65B0\u539F\u5219
792
+ - \u9ED8\u8BA4\u628A updateAgent \u5F53\u6210\u9AD8\u98CE\u9669\u7EF4\u62A4\u64CD\u4F5C\uFF0C\u4F18\u5148\u6700\u5C0F\u6539\u52A8
793
+ - \u4FEE\u6539\u524D\u5148\u786E\u8BA4\u76EE\u6807 Agent \u662F\u5426\u6B63\u786E\uFF0C\u907F\u514D\u8BEF\u6539
794
+ - \u5982\u679C\u5DE5\u5177\u8FD4\u56DE\u9700\u8981\u786E\u8BA4\uFF0C\u4E0D\u8981\u7ED5\u8FC7\u786E\u8BA4\u6D41\u7A0B`;
795
+ var CLARIFICATION_MODE_INSTRUCTIONS = `\u5728\u4F60\u8FD8\u4E0D\u4E86\u89E3\u7528\u6237\u610F\u56FE\u65F6\uFF0C\u901A\u8FC7\u63D0\u95EE\u6765\u6F84\u6E05\u9700\u6C42\uFF0C\u800C\u4E0D\u662F\u4ED3\u4FC3\u7ED9\u51FA\u7B54\u6848\u3002`;
796
+ var isBrowser = typeof window !== "undefined";
797
+ var TOOL_GUIDED_SECTIONS = [
798
+ {
799
+ id: "agentOrchestration",
800
+ triggerTools: ["callAgent", "runStreamingAgent"],
801
+ build: (tools) => [
802
+ AGENT_ORCHESTRATION_INSTRUCTIONS,
803
+ tools.includes("runStreamingAgent") ? PAGE_BUILDER_HANDOFF_INSTRUCTIONS : ""
804
+ ].filter(Boolean).join("\n\n")
805
+ },
806
+ { id: "menuUsage", triggerTools: ["ui_ask_choice"], build: () => MENU_USAGE_INSTRUCTIONS },
807
+ {
808
+ id: "webAccess",
809
+ triggerTools: ["exa_search", "fetchWebpage", "browser_openSession", "read_x_post"],
810
+ build: () => WEBPAGE_ACCESS_INSTRUCTIONS
811
+ },
812
+ {
813
+ id: "knowledgeManagement",
814
+ triggerTools: ["createDoc", "updateDoc", "read", "readDoc", "readPage"],
815
+ build: () => KNOWLEDGE_MANAGEMENT_INSTRUCTIONS
816
+ },
817
+ { id: "memoryCapture", triggerTools: ["rememberMemory"], build: () => MEMORY_CAPTURE_INSTRUCTIONS },
818
+ { id: "selfUpdate", triggerTools: ["updateSelf"], build: () => SELF_UPDATE_INSTRUCTIONS },
819
+ { id: "genericAgentUpdate", triggerTools: ["updateAgent"], build: () => GENERIC_AGENT_UPDATE_INSTRUCTIONS }
820
+ ];
821
+ function resolveToolGuidedSections(agentTools) {
822
+ const out = {};
823
+ for (const section of TOOL_GUIDED_SECTIONS) {
824
+ if (section.triggerTools.some((t) => agentTools.includes(t))) {
825
+ out[section.id] = section.build(agentTools);
826
+ } else {
827
+ out[section.id] = "";
828
+ }
829
+ }
830
+ return out;
831
+ }
832
+ var createContextSection = (title, description, content) => content ? `### ${title}
833
+ ${description}
834
+
835
+ ${content} ` : "";
836
+ var buildResponseGuidelines = (isMobile) => {
837
+ if (isMobile) {
838
+ return `-- - \u54CD\u5E94\u5C55\u793A\u6307\u5357-- -
839
+ \u8BF7\u4E3A\u79FB\u52A8\u7AEF\u8FDB\u884C\u4F18\u5316\uFF1A
840
+ - \u4F7F\u7528\u66F4\u77ED\u7684\u6BB5\u843D\u548C\u7B80\u6D01\u7684\u9879\u76EE\u7B26\u53F7\u5217\u8868\u3002
841
+ - \u907F\u514D\u8FC7\u5BBD\u7684\u8868\u683C\u6216\u4EE3\u7801\u5757\uFF0C\u4EE5\u514D\u4EA7\u751F\u6A2A\u5411\u6EDA\u52A8\u3002
842
+ - \u4F18\u5148\u91C7\u7528\u5782\u76F4\u6392\u5E03\uFF0C\u800C\u4E0D\u662F\u5DE6\u53F3\u5E76\u6392\u7684\u5E03\u5C40\u3002`;
843
+ }
844
+ return `-- - \u54CD\u5E94\u5C55\u793A\u6307\u5357-- -
845
+ \u4F60\u7684\u56DE\u590D\u5C06\u663E\u793A\u5728\u5927\u5C4F\u5E55\u4E0A\u3002\u4F60\u53EF\u4EE5\uFF1A
846
+ - \u63D0\u4F9B\u66F4\u4E30\u5BCC\u7684\u63A8\u7406\u8FC7\u7A0B\u8BF4\u660E\u548C\u66F4\u6709\u5C42\u6B21\u7684\u7ED3\u6784\u3002
847
+ - \u5728\u5408\u9002\u7684\u573A\u666F\u4E0B\u4F7F\u7528\u5BBD\u5C4F\u4F18\u52BF\uFF0C\u4F8B\u5982\u66F4\u5BBD\u7684\u8868\u683C\u3001\u5E76\u6392\u5BF9\u6BD4\u5C55\u793A\u3001\u66F4\u957F\u7684\u4EE3\u7801\u5757\u7B49\u3002`;
848
+ };
849
+ var buildReferenceMaterialsBlock = (contexts) => {
850
+ const sections = [
851
+ createContextSection(
852
+ "\u8BF4\u660E\u6027\u6587\u6863\uFF08Instructional Documents\uFF09",
853
+ "\uFF08\u6700\u9AD8\u4F18\u5148\u7EA7\uFF1A\u5177\u4F53\u89C4\u5219\u4E0E\u6D41\u7A0B\uFF09",
854
+ contexts.botInstructionsContext
855
+ ),
856
+ createContextSection(
857
+ "\u5F53\u524D\u8F93\u5165\u4E0A\u4E0B\u6587\uFF08Current Input Context\uFF09",
858
+ "\uFF08\u9AD8\u4F18\u5148\u7EA7\uFF1A\u6765\u81EA\u7528\u6237\u672C\u6B21\u8F93\u5165\uFF09",
859
+ contexts.currentInputContext
860
+ ),
861
+ createContextSection(
862
+ "\u4F1A\u8BDD\u5386\u53F2\u5F15\u7528\uFF08Conversation History References\uFF09",
863
+ "\uFF08\u4E2D\u7B49\u4F18\u5148\u7EA7\uFF1A\u6765\u81EA\u8FC7\u5F80\u6D88\u606F\uFF09",
864
+ contexts.historyContext
865
+ ),
866
+ createContextSection(
867
+ "\u77E5\u8BC6\u5E93\u6587\u6863\uFF08Knowledge Base Documents\uFF09",
868
+ "\uFF08\u53C2\u8003\u4F18\u5148\u7EA7\uFF1A\u7528\u4E8E\u901A\u7528\u67E5\u9605\uFF09",
869
+ contexts.botKnowledgeContext
870
+ )
871
+ ].filter(Boolean);
872
+ if (sections.length === 0) {
873
+ return "";
874
+ }
875
+ return [
876
+ "--- \u53C2\u8003\u8D44\u6599 ---",
877
+ CONTEXT_USAGE_INSTRUCTIONS,
878
+ "",
879
+ sections.join("\n\n")
880
+ ].join("\n");
881
+ };
882
+ var buildEditingContextBlock = (contexts) => {
883
+ if (!contexts.editingContext) return "";
884
+ return [
885
+ "--- \u5F53\u524D\u7F16\u8F91\u4E0A\u4E0B\u6587 ---",
886
+ "\u4E0B\u9762\u662F\u7528\u6237\u5F53\u524D\u6B63\u5728\u67E5\u770B\u6216\u7F16\u8F91\u7684\u5BF9\u8C61\u63CF\u8FF0\uFF0C\u8BF7\u5728\u6D89\u53CA\u4FEE\u6539\u3001\u5EFA\u8BAE\u6216\u7ED3\u6784\u6027\u64CD\u4F5C\u65F6\u4F18\u5148\u53C2\u8003\u8FD9\u91CC\uFF1A",
887
+ "",
888
+ contexts.editingContext
889
+ ].join("\n");
890
+ };
891
+ var buildAppWorkingMemoryBlock = (contexts) => {
892
+ if (!contexts.appWorkingMemory) return "";
893
+ return [
894
+ "--- \u6700\u8FD1\u5E94\u7528\u5DE5\u4F5C\u8BB0\u5FC6 ---",
895
+ "\u4E0B\u9762\u662F\u4ECE\u5F53\u524D\u5BF9\u8BDD\u6700\u8FD1\u7684\u5E94\u7528\u76F8\u5173\u5DE5\u5177\u8C03\u7528\u4E2D\u63D0\u70BC\u51FA\u7684\u771F\u503C\u3002\u5373\u4F7F\u7528\u6237\u6CA1\u6709\u6253\u5F00\u53F3\u4FA7\u5E94\u7528\u4FA7\u680F\uFF0C\u53EA\u8981\u4ED6\u8BF4\u201C\u521A\u624D\u90A3\u4E2A app / \u90A3\u4E2A\u7F51\u7AD9 / \u90A3\u4E2A\u9879\u76EE\u201D\uFF0C\u4E5F\u4F18\u5148\u53C2\u8003\u8FD9\u91CC\uFF1A",
896
+ "",
897
+ contexts.appWorkingMemory
898
+ ].join("\n");
899
+ };
900
+ var buildSpaceContextBlock = (contexts) => {
901
+ if (!contexts.spaceContext) return "";
902
+ return [
903
+ contexts.spaceContext,
904
+ "",
905
+ "\u91CD\u8981\u6307\u4EE4 (Space Awareness)\uFF1A",
906
+ "- \u4F60\u6B63\u5904\u4E8E\u4E0A\u8FF0\u5DE5\u4F5C\u7A7A\u95F4\u4E2D\u3002\u5982\u679C\u7528\u6237\u7684\u95EE\u9898\u6D89\u53CA\u5230\u8BE5\u7A7A\u95F4\u7684\u5185\u5BB9\u3001\u6587\u4EF6\u6216\u77E5\u8BC6\uFF1A",
907
+ " - \u4F7F\u7528 `read` \u5DE5\u5177\u67E5\u9605\u666E\u901A\u6570\u636E\u8BB0\u5F55\u6216\u6570\u636E\u8868\u9879\u3002",
908
+ "- \u5982\u679C\u4F60\u5728\u5BF9\u8BDD\u4E2D\u4EA7\u51FA\u4E86\u503C\u5F97\u4FDD\u5B58\u7684\u91CD\u8981\u4FE1\u606F\uFF08\u5982\u603B\u7ED3\u3001\u65B9\u6848\u3001\u4EE3\u7801\u7247\u6BB5\u7B49\uFF09\uFF0C\u8BF7\u4E3B\u52A8\u8BE2\u95EE\u7528\u6237\u6216\u4F7F\u7528 `createDoc` \u5DE5\u5177\u5C06\u5176\u4FDD\u5B58\u4E3A\u65B0\u9875\u9762\uFF0C\u4EE5\u4FBF\u4F5C\u4E3A\u957F\u671F\u8BB0\u5FC6\u7559\u5B58\u3002",
909
+ "",
910
+ "\u8DE8\u7A7A\u95F4\u5BFC\u822A (Cross-Space Navigation)\uFF1A",
911
+ "- \u4F7F\u7528 `listUserSpaces` \u5DE5\u5177\u53EF\u83B7\u53D6\u7528\u6237\u6240\u6709\u53EF\u8BBF\u95EE\u7684 Space \u5217\u8868\uFF08ID \u548C\u540D\u79F0\uFF09\u3002",
912
+ '- \u4F7F\u7528 `read({ dbKey: "space-{spaceId}" })` \u53EF\u83B7\u53D6\u6307\u5B9A Space \u7684\u5B8C\u6574\u6570\u636E\uFF0C\u5305\u62EC\uFF1A',
913
+ " - categories: \u5206\u7C7B\u5B57\u5178\uFF0Ckey \u662F\u5206\u7C7B ID\uFF0Cvalue \u5305\u542B name \u548C order",
914
+ " - contents: \u5185\u5BB9\u5B57\u5178\uFF0C\u6BCF\u9879\u5305\u542B contentKey\uFF08dbKey\uFF09\u3001title\u3001type\u3001categoryId"
915
+ ].join("\n");
916
+ };
917
+ var buildSkillGuidanceBlock = (agentConfig) => {
918
+ const recommendedSkillHints = Array.isArray(agentConfig.recommendedSkillHints) ? agentConfig.recommendedSkillHints.filter(Boolean) : [];
919
+ const skillPromptPatches = Array.isArray(agentConfig.skillPromptPatches) ? agentConfig.skillPromptPatches.filter(Boolean) : [];
920
+ if (recommendedSkillHints.length === 0 && skillPromptPatches.length === 0) {
921
+ return "";
922
+ }
923
+ return buildSkillGuidancePromptBlock({
924
+ title: "--- \u6280\u80FD\u63D0\u793A ---",
925
+ recommendedSkillHints,
926
+ skillPromptPatches
927
+ });
928
+ };
929
+ var buildSystemPrompt = (options) => buildSystemPromptContext(options).content;
930
+ var buildSystemPromptContext = (options) => {
931
+ const {
932
+ agentConfig,
933
+ contexts = {},
934
+ viewport,
935
+ mobileBreakpoint = 768,
936
+ now = /* @__PURE__ */ new Date(),
937
+ timeZone
938
+ } = options;
939
+ const safeLanguage = options.language ?? (typeof navigator !== "undefined" ? navigator.language : "en");
940
+ const { name, prompt: mainPrompt, dbKey, model } = agentConfig;
941
+ const mappedLanguage = mapLanguage(safeLanguage);
942
+ const identitySection = buildIdentityBlock({
943
+ agentName: name,
944
+ agentId: dbKey,
945
+ model,
946
+ responseLanguage: mappedLanguage
947
+ });
948
+ const corePersonaSection = mainPrompt ? `-- - \u6838\u5FC3\u89D2\u8272\u4E0E\u4EFB\u52A1-- -
949
+ ${mainPrompt}` : "";
950
+ const agentTools = canonicalizeToolNames(agentConfig.tools ?? []);
951
+ const toolSections = resolveToolGuidedSections(agentTools);
952
+ const {
953
+ startupProtocol,
954
+ contextLayerContract,
955
+ emailRegistrationWorkflow,
956
+ webResearchToolPolicy
957
+ } = buildRuntimeGuidanceBlocks(agentTools);
958
+ const clarifyingSection = !mainPrompt ? CLARIFICATION_MODE_INSTRUCTIONS : "";
959
+ const userGlobalPromptSection = contexts.userGlobalPrompt?.trim() ? `-- - \u7528\u6237\u5168\u5C40\u504F\u597D-- -
960
+ ${contexts.userGlobalPrompt.trim()} ` : "";
961
+ const fallbackViewportWidth = isBrowser && typeof window !== "undefined" ? window.innerWidth : 1440;
962
+ const isMobile = (viewport?.width ?? fallbackViewportWidth) < mobileBreakpoint;
963
+ const responseGuidelinesSection = buildResponseGuidelines(isMobile);
964
+ const editingContextSection = buildEditingContextBlock(contexts);
965
+ const appWorkingMemorySection = buildAppWorkingMemoryBlock(contexts);
966
+ const spaceContextSection = buildSpaceContextBlock(contexts);
967
+ const rawMemoryOverlay = asOptionalTrimmedString(contexts.memoryOverlay) ?? "";
968
+ const memoryOverlaySection = rawMemoryOverlay;
969
+ const hasMemoryTools = Array.isArray(agentConfig.tools) && agentConfig.tools.some(
970
+ (t) => /memory/i.test(t)
971
+ );
972
+ const memoryUseGuidanceSection = hasMemoryTools ? MEMORY_USE_GUIDANCE : "";
973
+ const skillGuidanceSection = buildSkillGuidanceBlock(agentConfig);
974
+ const referenceMaterialsSection = buildReferenceMaterialsBlock(contexts);
975
+ const dialogSummarySection = contexts.dialogSummary?.trim() ? `--- \u5386\u53F2\u5BF9\u8BDD\u6458\u8981 ---
976
+ ${wrapHistoricalSummaryWithReplayGuard(contexts.dialogSummary)}` : "";
977
+ return compileContextLayers([
978
+ { id: "identity", owner: "platform", cacheScope: "session", content: identitySection },
979
+ { id: "startup-protocol", owner: "platform", cacheScope: "static", content: startupProtocol },
980
+ { id: "core-persona", owner: "agent", cacheScope: "session", content: corePersonaSection },
981
+ { id: "agent-orchestration", owner: "platform", cacheScope: "session", content: toolSections.agentOrchestration },
982
+ { id: "web-access", owner: "platform", cacheScope: "session", content: toolSections.webAccess },
983
+ { id: "menu-usage", owner: "platform", cacheScope: "session", content: toolSections.menuUsage },
984
+ { id: "clarification-mode", owner: "platform", cacheScope: "session", content: clarifyingSection },
985
+ { id: "knowledge-management", owner: "platform", cacheScope: "session", content: toolSections.knowledgeManagement },
986
+ { id: "memory-capture", owner: "platform", cacheScope: "session", content: toolSections.memoryCapture },
987
+ { id: "self-update", owner: "platform", cacheScope: "session", content: toolSections.selfUpdate },
988
+ { id: "generic-agent-update", owner: "platform", cacheScope: "session", content: toolSections.genericAgentUpdate },
989
+ { id: "context-layer-contract", owner: "platform", cacheScope: "static", content: contextLayerContract },
990
+ {
991
+ id: "email-registration-workflow",
992
+ owner: "platform",
993
+ cacheScope: "static",
994
+ content: emailRegistrationWorkflow
995
+ },
996
+ {
997
+ id: "web-research-tool-policy",
998
+ owner: "platform",
999
+ cacheScope: "static",
1000
+ content: webResearchToolPolicy
1001
+ },
1002
+ { id: "user-global-prompt", owner: "user", cacheScope: "session", content: userGlobalPromptSection },
1003
+ { id: "response-guidelines", owner: "platform", cacheScope: "session", content: responseGuidelinesSection },
1004
+ { id: "skill-guidance", owner: "runtime", cacheScope: "session", content: skillGuidanceSection },
1005
+ { id: "space-context", owner: "runtime", cacheScope: "session", content: spaceContextSection },
1006
+ { id: "memory-use-guidance", owner: "platform", cacheScope: "session", content: memoryUseGuidanceSection },
1007
+ { id: "reference-materials", owner: "agent", cacheScope: "turn", content: referenceMaterialsSection },
1008
+ { id: "memory-overlay", owner: "runtime", cacheScope: "turn", content: memoryOverlaySection },
1009
+ { id: "app-working-memory", owner: "runtime", cacheScope: "turn", content: appWorkingMemorySection },
1010
+ { id: "dialog-summary", owner: "runtime", cacheScope: "turn", content: dialogSummarySection },
1011
+ { id: "editing-context", owner: "runtime", cacheScope: "turn", content: editingContextSection },
1012
+ {
1013
+ id: "current-time",
1014
+ owner: "platform",
1015
+ cacheScope: "turn",
1016
+ content: buildCurrentTimeBlock(now, timeZone)
1017
+ }
1018
+ ]);
1019
+ };
1020
+
1021
+ // packages/integrations/openai/providerBodyCompatibility.ts
1022
+ var normalizeChatCompletionsBodyForProvider = ({
1023
+ body,
1024
+ provider,
1025
+ model
1026
+ }) => {
1027
+ const nextBody = { ...body, model };
1028
+ const normalizedProvider = asTrimmedLowercaseString(provider);
1029
+ if (normalizedProvider === "fireworks" && isFireworksKimiModel(model)) {
1030
+ delete nextBody.reasoning;
1031
+ delete nextBody.reasoning_effort;
1032
+ }
1033
+ return nextBody;
1034
+ };
1035
+
1036
+ // packages/integrations/openai/generateOpenAIRequestBody.ts
1037
+ var isClaudeModel = (model) => !!model && (model.includes("claude") || model.includes("anthropic"));
1038
+ var applyClaudeCache = (stableContent, dynamicContent) => {
1039
+ const parts = [];
1040
+ if (stableContent.trim()) {
1041
+ parts.push({
1042
+ type: "text",
1043
+ text: stableContent,
1044
+ cache_control: { type: "ephemeral" }
1045
+ });
1046
+ }
1047
+ if (dynamicContent.trim()) {
1048
+ parts.push({ type: "text", text: dynamicContent });
1049
+ }
1050
+ return parts.length > 0 ? parts : stableContent;
1051
+ };
1052
+ var prependPromptMessage = (messages, agentConfig, resolvedModel, language, contexts, prependSystemPrompt = true) => {
1053
+ if (!prependSystemPrompt) return messages;
1054
+ if (!contexts && !agentConfig.prompt) return messages;
1055
+ if (isClaudeModel(resolvedModel)) {
1056
+ const compiled = buildSystemPromptContext({ agentConfig, language, contexts });
1057
+ if (!compiled.content.trim()) return messages;
1058
+ const content = applyClaudeCache(
1059
+ compiled.stablePrefixContent,
1060
+ compiled.dynamicContent
1061
+ );
1062
+ const systemMessage2 = { role: "system", content };
1063
+ return [systemMessage2, ...messages];
1064
+ }
1065
+ const promptContent = buildSystemPrompt({ agentConfig, language, contexts });
1066
+ if (!promptContent.trim()) return messages;
1067
+ const systemMessage = { role: "system", content: promptContent };
1068
+ return [systemMessage, ...messages];
1069
+ };
1070
+ var shouldInjectLlamaCppThinkingToggle = (agentConfig) => {
1071
+ if (typeof agentConfig.enableThinking !== "boolean") return false;
1072
+ if (!isLoopbackUrl(agentConfig.customProviderUrl)) return false;
1073
+ return /qwen/i.test(agentConfig.model ?? "");
1074
+ };
1075
+ var shouldDisableMiMoThinking = (agentConfig) => {
1076
+ if (agentConfig.enableThinking === true) return false;
1077
+ return /xiaomimimo\.com/i.test(agentConfig.customProviderUrl ?? "") || (agentConfig.provider ?? "").toLowerCase() === "mimo";
1078
+ };
1079
+ var shouldDisableKimiThinking = (agentConfig, providerName, resolvedModel) => {
1080
+ if (agentConfig.enableThinking !== false) return false;
1081
+ if (providerName === "deepinfra") return isDeepInfraKimiModel(resolvedModel);
1082
+ if (providerName === "fireworks") return isFireworksKimiModel(resolvedModel);
1083
+ return false;
1084
+ };
1085
+ var normalizeChatCompletionsContent = (content) => {
1086
+ if (typeof content === "string" || Array.isArray(content)) return content;
1087
+ if (content == null) return null;
1088
+ return JSON.stringify(content);
1089
+ };
1090
+ var sanitizeChatCompletionsMessage = (message) => {
1091
+ const sanitized = {
1092
+ role: message.role,
1093
+ content: normalizeChatCompletionsContent(message.content)
1094
+ };
1095
+ const name = asOptionalTrimmedString(message.name);
1096
+ if (name) sanitized.name = name;
1097
+ const toolCallId = asOptionalTrimmedString(message.tool_call_id);
1098
+ if (toolCallId) sanitized.tool_call_id = toolCallId;
1099
+ if (Array.isArray(message.tool_calls)) {
1100
+ sanitized.tool_calls = message.tool_calls;
1101
+ }
1102
+ if (message.role === "assistant" && typeof message.reasoning_content === "string" && message.reasoning_content) {
1103
+ sanitized.reasoning_content = message.reasoning_content;
1104
+ }
1105
+ return sanitized;
1106
+ };
1107
+ var buildRequestBody = (options) => {
1108
+ const {
1109
+ model,
1110
+ messages,
1111
+ providerName,
1112
+ temperature,
1113
+ top_p,
1114
+ frequency_penalty,
1115
+ presence_penalty,
1116
+ max_tokens,
1117
+ reasoning_effort
1118
+ } = options;
1119
+ const cleanedMessages = messages.map(
1120
+ (message) => sanitizeChatCompletionsMessage(message)
1121
+ );
1122
+ const bodyData = {
1123
+ model,
1124
+ messages: cleanedMessages,
1125
+ stream: true
1126
+ };
1127
+ const usageRequestOptions = getUsageRequestOptions(providerName, {
1128
+ api: "chat-completions"
1129
+ });
1130
+ Object.assign(bodyData, usageRequestOptions);
1131
+ if (reasoning_effort && isModelSupportReasoningEffort(model)) {
1132
+ bodyData.reasoning_effort = reasoning_effort;
1133
+ }
1134
+ if (typeof temperature === "number") bodyData.temperature = temperature;
1135
+ if (typeof top_p === "number") bodyData.top_p = top_p;
1136
+ if (typeof frequency_penalty === "number")
1137
+ bodyData.frequency_penalty = frequency_penalty;
1138
+ if (typeof presence_penalty === "number")
1139
+ bodyData.presence_penalty = presence_penalty;
1140
+ if (typeof max_tokens === "number") bodyData.max_tokens = max_tokens;
1141
+ return bodyData;
1142
+ };
1143
+ var generateOpenAIRequestBody = (agentConfig, providerName, messages, contexts, stableMessages = [], prependSystemPrompt = true) => {
1144
+ const resolvedModel = providerName === "fireworks" ? resolveFireworksKimiModel(agentConfig.model) : agentConfig.model ?? "";
1145
+ let processedStable = [...stableMessages];
1146
+ if (isClaudeModel(resolvedModel) && processedStable.length > 0) {
1147
+ const lastStableIdx = processedStable.length - 1;
1148
+ const lastContent = processedStable[lastStableIdx].content;
1149
+ if (typeof lastContent === "string") {
1150
+ processedStable[lastStableIdx] = {
1151
+ ...processedStable[lastStableIdx],
1152
+ content: [
1153
+ { type: "text", text: lastContent, cache_control: { type: "ephemeral" } }
1154
+ ]
1155
+ };
1156
+ } else if (Array.isArray(lastContent)) {
1157
+ const lastPartIdx = lastContent.length - 1;
1158
+ processedStable[lastStableIdx] = {
1159
+ ...processedStable[lastStableIdx],
1160
+ content: lastContent.map(
1161
+ (part, idx) => idx === lastPartIdx && typeof part === "object" ? { ...part, cache_control: { type: "ephemeral" } } : part
1162
+ )
1163
+ };
1164
+ }
1165
+ }
1166
+ const fullMessages = [...processedStable, ...messages];
1167
+ const messagesWithPrompt = prependPromptMessage(
1168
+ fullMessages,
1169
+ agentConfig,
1170
+ resolvedModel,
1171
+ typeof navigator !== "undefined" ? navigator.language : "en",
1172
+ contexts,
1173
+ prependSystemPrompt
1174
+ );
1175
+ const requestBody = buildRequestBody({
1176
+ model: resolvedModel,
1177
+ messages: messagesWithPrompt,
1178
+ providerName,
1179
+ temperature: agentConfig.temperature,
1180
+ top_p: agentConfig.top_p,
1181
+ frequency_penalty: agentConfig.frequency_penalty,
1182
+ presence_penalty: agentConfig.presence_penalty,
1183
+ max_tokens: agentConfig.max_tokens,
1184
+ reasoning_effort: agentConfig.reasoning_effort
1185
+ });
1186
+ if (shouldInjectLlamaCppThinkingToggle(agentConfig)) {
1187
+ requestBody.chat_template_kwargs = {
1188
+ ...requestBody.chat_template_kwargs ?? {},
1189
+ enable_thinking: agentConfig.enableThinking
1190
+ };
1191
+ }
1192
+ if (shouldDisableMiMoThinking(agentConfig)) {
1193
+ requestBody.thinking = { type: "disabled" };
1194
+ }
1195
+ if (shouldDisableKimiThinking(agentConfig, providerName, resolvedModel)) {
1196
+ requestBody.thinking = { type: "disabled" };
1197
+ requestBody.reasoning_effort = "none";
1198
+ requestBody.reasoning = { enabled: false };
1199
+ }
1200
+ return normalizeChatCompletionsBodyForProvider({
1201
+ body: requestBody,
1202
+ provider: providerName,
1203
+ model: requestBody.model
1204
+ });
1205
+ };
1206
+
1207
+ // packages/integrations/openai/generateResponseRequestBody.ts
1208
+ function generateResponseRequestBody(agentConfig, msgs, contexts, prependSystemPrompt = true) {
1209
+ const language = typeof navigator !== "undefined" && navigator.language ? navigator.language : "zh-CN";
1210
+ const input = convertMessagesToResponsesInput(msgs);
1211
+ const body = {
1212
+ model: agentConfig.model,
1213
+ input,
1214
+ stream: true,
1215
+ ...getUsageRequestOptions(agentConfig.provider, { api: "responses" })
1216
+ };
1217
+ if (prependSystemPrompt) {
1218
+ const promptContent = buildSystemPrompt({
1219
+ agentConfig,
1220
+ language,
1221
+ contexts
1222
+ });
1223
+ body.instructions = promptContent;
1224
+ }
1225
+ if (agentConfig.temperature !== void 0) {
1226
+ body.temperature = agentConfig.temperature;
1227
+ }
1228
+ if (agentConfig.top_p !== void 0) {
1229
+ body.top_p = agentConfig.top_p;
1230
+ }
1231
+ if (agentConfig.max_tokens !== void 0) {
1232
+ body.max_output_tokens = agentConfig.max_tokens;
1233
+ }
1234
+ if (agentConfig.max_tool_calls !== void 0) {
1235
+ body.max_tool_calls = agentConfig.max_tool_calls;
1236
+ }
1237
+ if (agentConfig.user !== void 0) {
1238
+ body.user = agentConfig.user;
1239
+ }
1240
+ if (agentConfig.include !== void 0) {
1241
+ body.include = agentConfig.include;
1242
+ }
1243
+ if (agentConfig.metadata !== void 0) {
1244
+ body.metadata = agentConfig.metadata;
1245
+ }
1246
+ return body;
1247
+ }
1248
+
1249
+ // packages/ai/llm/generateRequestBody.ts
1250
+ var IMAGE_OUTPUT_EXECUTION_PROMPT = [
1251
+ "When the conversation already includes an input image and the user asks to change any visual attribute such as hairstyle, glasses, outfit, makeup, background, composition, or style, default to returning the edited image in this turn.",
1252
+ "When the user asks you to generate, edit, redraw, or return an image, you must return the image in this turn.",
1253
+ "Do not answer with only a textual description.",
1254
+ "Do not claim that you uploaded, attached, or sent an image unless the response actually includes image output.",
1255
+ "Only return text without an image when the user explicitly asks for analysis, recommendations, or explanation without generating an image."
1256
+ ].join(" ");
1257
+ var getImageOutputSettings = (agentConfig, provider) => {
1258
+ const modelName = agentConfig.model;
1259
+ if (!modelName) {
1260
+ return { shouldEnableImage: false, modelConfig: null };
1261
+ }
1262
+ try {
1263
+ const modelConfig = getModelConfig(provider, modelName);
1264
+ const hasImageOutput = !!modelConfig.hasImageOutput;
1265
+ const isExplicitlyDisabled = agentConfig.imageConfig?.enabled === false;
1266
+ return {
1267
+ shouldEnableImage: hasImageOutput && !isExplicitlyDisabled,
1268
+ modelConfig
1269
+ };
1270
+ } catch {
1271
+ return { shouldEnableImage: false, modelConfig: null };
1272
+ }
1273
+ };
1274
+ var withImageOutputPromptGuard = (agentConfig, shouldEnableImage) => {
1275
+ if (!shouldEnableImage) return agentConfig;
1276
+ const basePrompt = asTrimmedString(agentConfig.prompt);
1277
+ if (basePrompt.includes(IMAGE_OUTPUT_EXECUTION_PROMPT)) {
1278
+ return agentConfig;
1279
+ }
1280
+ return {
1281
+ ...agentConfig,
1282
+ prompt: basePrompt ? `${basePrompt}
1283
+
1284
+ ${IMAGE_OUTPUT_EXECUTION_PROMPT}` : IMAGE_OUTPUT_EXECUTION_PROMPT
1285
+ };
1286
+ };
1287
+ var applyImageConfigIfNeeded = (body, agentConfig, provider) => {
1288
+ const { shouldEnableImage, modelConfig } = getImageOutputSettings(
1289
+ agentConfig,
1290
+ provider
1291
+ );
1292
+ const agentImageCfg = agentConfig.imageConfig;
1293
+ if (!shouldEnableImage || !modelConfig) {
1294
+ return body;
1295
+ }
1296
+ const modalities = agentImageCfg?.forceModalities ?? modelConfig.defaultModalities ?? (modelConfig.requiresImageModalities ? ["image", "text"] : void 0);
1297
+ if (modalities && !body.modalities) {
1298
+ body.modalities = modalities;
1299
+ }
1300
+ if (!modelConfig.supportsImageConfig) {
1301
+ return body;
1302
+ }
1303
+ const aspectRatio = agentImageCfg?.aspectRatio;
1304
+ const imageSize = agentImageCfg?.imageSize;
1305
+ if (!aspectRatio && !imageSize) {
1306
+ return body;
1307
+ }
1308
+ body.image_config = {
1309
+ ...body.image_config ?? {},
1310
+ ...aspectRatio ? { aspect_ratio: aspectRatio } : {},
1311
+ ...imageSize ? { image_size: imageSize } : {}
1312
+ };
1313
+ return body;
1314
+ };
1315
+ var generateRequestBody = ({
1316
+ agentConfig,
1317
+ messages,
1318
+ contexts,
1319
+ stableMessages,
1320
+ prependSystemPrompt = true
1321
+ }) => {
1322
+ const provider = (agentConfig.provider || "").toLowerCase();
1323
+ const imageSettings = getImageOutputSettings(agentConfig, provider);
1324
+ const agentConfigForRequest = withImageOutputPromptGuard(
1325
+ agentConfig,
1326
+ imageSettings.shouldEnableImage
1327
+ );
1328
+ const clientWire = resolveClientWire(
1329
+ resolveAgentCallPlan(agentConfigForRequest, {})
1330
+ );
1331
+ if (clientWire === "responses") {
1332
+ return generateResponseRequestBody(
1333
+ agentConfigForRequest,
1334
+ [...stableMessages ?? [], ...messages],
1335
+ contexts,
1336
+ prependSystemPrompt
1337
+ );
1338
+ }
1339
+ const baseBody = generateOpenAIRequestBody(
1340
+ agentConfigForRequest,
1341
+ provider,
1342
+ messages,
1343
+ contexts,
1344
+ stableMessages,
1345
+ prependSystemPrompt
1346
+ );
1347
+ return applyImageConfigIfNeeded(baseBody, agentConfigForRequest, provider);
1348
+ };
1349
+
1350
+ // packages/ai/chat/serverProxyRetry.ts
1351
+ var RETRYABLE_SERVER_PROXY_STATUSES = /* @__PURE__ */ new Set([502, 503, 504]);
1352
+ var DEFAULT_SERVER_PROXY_RETRY_AFTER_MS = 1500;
1353
+ var MAX_SERVER_PROXY_RETRIES = 2;
1354
+ var MAX_STATUS_RETRIES = 1;
1355
+ var resolveServerProxyRetryAfterMs = (response) => parseRetryAfterHeaderMs(response.headers.get("Retry-After")) ?? DEFAULT_SERVER_PROXY_RETRY_AFTER_MS;
1356
+ var isRetryableServerProxyFetchError = (error) => {
1357
+ if (!error || isAbortError(error)) return false;
1358
+ const message = typeof error?.message === "string" ? error.message : String(error);
1359
+ return /ECONNREFUSED|ECONNRESET|EPIPE|socket hang up|network error|failed to fetch|fetch failed|connection closed|load failed|502|503|504/i.test(
1360
+ message
1361
+ );
1362
+ };
1363
+ var waitForServerProxyRetry = async (retryAfterMs, signal) => {
1364
+ if (retryAfterMs <= 0) return;
1365
+ if (signal?.aborted) {
1366
+ const abortError = new Error("Aborted");
1367
+ abortError.name = "AbortError";
1368
+ throw abortError;
1369
+ }
1370
+ await new Promise((resolve, reject) => {
1371
+ const onAbort = () => {
1372
+ clearTimeout(timeoutId);
1373
+ signal?.removeEventListener("abort", onAbort);
1374
+ const abortError = new Error("Aborted");
1375
+ abortError.name = "AbortError";
1376
+ reject(abortError);
1377
+ };
1378
+ const timeoutId = setTimeout(() => {
1379
+ signal?.removeEventListener("abort", onAbort);
1380
+ resolve();
1381
+ }, normalizeNonNegativeMs(retryAfterMs, DEFAULT_SERVER_PROXY_RETRY_AFTER_MS));
1382
+ signal?.addEventListener("abort", onAbort, { once: true });
1383
+ });
1384
+ };
1385
+ var performServerProxyFetchWithRetry = async ({
1386
+ execute,
1387
+ signal,
1388
+ logPrefix = "[fetchWithServerProxy]"
1389
+ }) => {
1390
+ for (let attempt = 0; attempt <= MAX_SERVER_PROXY_RETRIES; attempt += 1) {
1391
+ try {
1392
+ const response = await execute();
1393
+ if (attempt < MAX_STATUS_RETRIES && RETRYABLE_SERVER_PROXY_STATUSES.has(response.status)) {
1394
+ const retryAfterMs = resolveServerProxyRetryAfterMs(response);
1395
+ console.warn(
1396
+ `${logPrefix} \u68C0\u6D4B\u5230${response.status}\u72B6\u6001\uFF0C${retryAfterMs}ms\u540E\u91CD\u8BD5\u4E00\u6B21...`
1397
+ );
1398
+ await waitForServerProxyRetry(retryAfterMs, signal);
1399
+ continue;
1400
+ }
1401
+ return response;
1402
+ } catch (error) {
1403
+ if (attempt < MAX_SERVER_PROXY_RETRIES && isRetryableServerProxyFetchError(error)) {
1404
+ const retryDelay = (attempt + 1) * 1e3;
1405
+ console.warn(
1406
+ `${logPrefix} \u68C0\u6D4B\u5230\u7F51\u7EDC\u77AC\u65AD\uFF0C${retryDelay}ms\u540E\u91CD\u8BD5(\u7B2C${attempt + 1}\u6B21)...`,
1407
+ error
1408
+ );
1409
+ await waitForServerProxyRetry(retryDelay, signal);
1410
+ continue;
1411
+ }
1412
+ throw error;
1413
+ }
1414
+ }
1415
+ throw new Error("server proxy retry exhausted unexpectedly");
1416
+ };
1417
+
1418
+ // packages/ai/chat/resolveDirectRequestApiKey.ts
1419
+ var DIRECT_API_KEY_UNAVAILABLE_MESSAGE = "\u65E0\u6CD5\u52A0\u8F7D\u672C\u5730 API \u5BC6\u94A5\u3002\u8BF7\u5728 Agent \u8BBE\u7F6E\u4E2D\u91CD\u65B0\u586B\u5199\u5BC6\u94A5\uFF0C\u6216\u786E\u8BA4\u672C\u673A\u51ED\u636E\u53EF\u7528\u3002";
1420
+ var DirectApiKeyResolutionError = class extends Error {
1421
+ constructor(message = DIRECT_API_KEY_UNAVAILABLE_MESSAGE) {
1422
+ super(message);
1423
+ this.name = "DirectApiKeyResolutionError";
1424
+ }
1425
+ };
1426
+ var createDirectCredentialBroker = createFileCredentialBroker;
1427
+ function readNonEmpty(value) {
1428
+ return asTrimmedString(value);
1429
+ }
1430
+ async function resolveDirectRequestApiKey(agentConfig, options) {
1431
+ const rawKey = readNonEmpty(agentConfig.apiKey);
1432
+ if (rawKey) return rawKey;
1433
+ const credentialRef = readNonEmpty(agentConfig.credentialRef);
1434
+ if (!credentialRef) return void 0;
1435
+ const factory = options?.brokerFactory ?? createDirectCredentialBroker;
1436
+ const broker = factory();
1437
+ const local = await safeBrokerGet(broker, credentialRef);
1438
+ if (local) return local;
1439
+ if (agentConfig.credentialSynced && options?.syncFetcher) {
1440
+ const synced = await options.syncFetcher(credentialRef);
1441
+ const trimmed = asTrimmedString(synced);
1442
+ if (trimmed) {
1443
+ try {
1444
+ await broker.put(credentialRef, trimmed);
1445
+ } catch {
1446
+ }
1447
+ return trimmed;
1448
+ }
1449
+ }
1450
+ throw new DirectApiKeyResolutionError();
1451
+ }
1452
+ async function safeBrokerGet(broker, ref) {
1453
+ try {
1454
+ return asTrimmedString(await broker.get(ref)) || null;
1455
+ } catch {
1456
+ return null;
1457
+ }
1458
+ }
1459
+
1460
+ // packages/ai/chat/fetchUtils.ts
1461
+ var buildProxyPayload = (bodyData, api, agentConfig, dialogId) => {
1462
+ const apiSource = agentConfig.apiSource === "custom" || agentConfig.apiSource === "cli" ? agentConfig.apiSource : void 0;
1463
+ const provider = bodyData.provider || agentConfig.provider || (apiSource === "custom" ? "custom" : void 0);
1464
+ const apiKey = asOptionalTrimmedString(agentConfig.apiKey);
1465
+ return {
1466
+ ...bodyData,
1467
+ url: api,
1468
+ provider,
1469
+ agentKey: agentConfig.dbKey,
1470
+ ...asOptionalTrimmedString(dialogId) ? { dialogId: asOptionalTrimmedString(dialogId) } : {},
1471
+ ...apiSource ? { apiSource } : {},
1472
+ ...agentConfig.apiKeyHeader ? { apiKeyHeader: agentConfig.apiKeyHeader } : {},
1473
+ KEY: apiKey
1474
+ };
1475
+ };
1476
+ var fetchDirectly = async (params) => {
1477
+ const { api, agentConfig, bodyData, signal, currentServer, token } = params;
1478
+ try {
1479
+ const apiKey = await resolveDirectRequestApiKey(agentConfig, {
1480
+ syncFetcher: currentServer && token ? (ref) => fetchServerSyncedCredential({ currentServer, authToken: token }, ref) : void 0
1481
+ });
1482
+ const authHeaders = buildProviderAuthHeaders({
1483
+ endpoint: api,
1484
+ apiKey: apiKey ?? "",
1485
+ apiKeyHeader: agentConfig.apiKeyHeader
1486
+ });
1487
+ return await fetch(api, {
1488
+ method: "POST",
1489
+ headers: {
1490
+ "Content-Type": "application/json",
1491
+ ...authHeaders,
1492
+ ...api.includes("openrouter.ai") ? {
1493
+ "HTTP-Referer": "https://nolo.chat",
1494
+ "X-Title": "nolo"
1495
+ } : {}
1496
+ },
1497
+ body: JSON.stringify(bodyData),
1498
+ signal
1499
+ // 可选参数,直接传递
1500
+ });
1501
+ } catch (error) {
1502
+ console.error("[fetchDirectly] \u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25:", error);
1503
+ throw error;
1504
+ }
1505
+ };
1506
+ var fetchWithServerProxy = async ({
1507
+ currentServer,
1508
+ api,
1509
+ bodyData,
1510
+ agentConfig,
1511
+ token,
1512
+ signal,
1513
+ dialogId
1514
+ }) => {
1515
+ try {
1516
+ const payload = buildProxyPayload(bodyData, api, agentConfig, dialogId);
1517
+ return await performServerProxyFetchWithRetry({
1518
+ signal,
1519
+ execute: () => fetch(`${currentServer}${API_ENDPOINTS.CHAT}`, {
1520
+ method: "POST",
1521
+ headers: {
1522
+ "Content-Type": "application/json",
1523
+ Authorization: `Bearer ${token}`
1524
+ // 使用 Authorization 头传递 token
1525
+ },
1526
+ body: JSON.stringify(payload),
1527
+ signal
1528
+ })
1529
+ });
1530
+ } catch (error) {
1531
+ console.error("[fetchWithServerProxy] \u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25:", error);
1532
+ throw error;
1533
+ }
1534
+ };
1535
+ var formatFriendlyNetworkErrorMessage = (error) => {
1536
+ if (typeof window !== "undefined" && typeof navigator !== "undefined" && navigator.onLine === false) {
1537
+ return "\u7F51\u7EDC\u8FDE\u63A5\u5DF2\u65AD\u5F00\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5\u540E\u91CD\u8BD5";
1538
+ }
1539
+ const rawMessage = toErrorMessage(error);
1540
+ if (/failed to fetch|networkerror|network error|econnrefused|econnreset|socket hang up/i.test(
1541
+ rawMessage
1542
+ )) {
1543
+ return "\u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5\u6216\u4EE3\u7406/VPN\u8BBE\u7F6E";
1544
+ }
1545
+ return rawMessage;
1546
+ };
1547
+ var performFetchRequest = async (params) => {
1548
+ try {
1549
+ const planConfig = {
1550
+ ...params.agentConfig,
1551
+ provider: params.bodyData.provider || params.agentConfig.provider
1552
+ };
1553
+ return resolveAgentCallPlan(planConfig, {}).transport === "server-proxy" ? await fetchWithServerProxy(params) : await fetchDirectly(params);
1554
+ } catch (error) {
1555
+ console.error("[performFetchRequest] \u8BF7\u6C42\u8FC7\u7A0B\u4E2D\u53D1\u751F\u9519\u8BEF:", error);
1556
+ const friendlyMsg = formatFriendlyNetworkErrorMessage(error);
1557
+ throw new Error(
1558
+ friendlyMsg.startsWith("\u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25") ? friendlyMsg : `\u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25: ${friendlyMsg}`
1559
+ );
1560
+ }
1561
+ };
1562
+
1563
+ // packages/create/editor/transforms/slateToText.ts
1564
+ function getNodeText(node) {
1565
+ if (node.text) {
1566
+ return node.text;
1567
+ }
1568
+ if (node.children && Array.isArray(node.children)) {
1569
+ return node.children.map(getNodeText).join("\n");
1570
+ }
1571
+ return "";
1572
+ }
1573
+ function slateToText(nodes) {
1574
+ if (!nodes || nodes.length === 0) {
1575
+ return "";
1576
+ }
1577
+ return nodes.map(getNodeText).join("\n\n");
1578
+ }
1579
+
1580
+ // packages/ai/context/buildReferenceContext.ts
1581
+ var MAX_META_TEXT_LENGTH = 80;
1582
+ var DIALOG_REFERENCE_MESSAGE_LIMIT = 20;
1583
+ var DIALOG_REFERENCE_SNIPPET_CHARS = 1200;
1584
+ var DIALOG_HANDOFF_SNIPPET_CHARS = 360;
1585
+ var truncateMetaText = (value, max = MAX_META_TEXT_LENGTH) => {
1586
+ if (!value) return "";
1587
+ if (value.length <= max) return value;
1588
+ return `${value.slice(0, max - 3)}...`;
1589
+ };
1590
+ var readSafe = async (dispatch, dbKey) => {
1591
+ try {
1592
+ return await dispatch(read({
1593
+ dbKey
1594
+ })).unwrap();
1595
+ } catch {
1596
+ return null;
1597
+ }
1598
+ };
1599
+ var buildMentionMetaMap = async (slateData, dispatch) => {
1600
+ const metaMap = /* @__PURE__ */ new Map();
1601
+ const mentions = extractCategorizedMentions(slateData);
1602
+ if (!mentions) return metaMap;
1603
+ const pageEntries = await Promise.all(
1604
+ (mentions.pages || []).map(async (pageId) => {
1605
+ const pageData = await readSafe(dispatch, pageId);
1606
+ if (!pageData) {
1607
+ return [`page:${pageId}`, { displayType: "page", metaParts: [] }];
1608
+ }
1609
+ if (pageData.type === "dialog" /* DIALOG */) {
1610
+ const agentCount = Array.isArray(pageData.cybots) ? pageData.cybots.length : 0;
1611
+ return [
1612
+ `page:${pageId}`,
1613
+ {
1614
+ displayType: "dialog",
1615
+ title: pageData.title,
1616
+ metaParts: [
1617
+ `agents=${agentCount}`,
1618
+ `updated=${pageData.updatedAt || pageData.updated_at || pageData.updated || "Unknown"}`
1619
+ ]
1620
+ }
1621
+ ];
1622
+ }
1623
+ const tags = pageData.tags && pageData.tags.length > 0 ? pageData.tags.slice(0, 5).join(", ") : "";
1624
+ return [
1625
+ `page:${pageId}`,
1626
+ {
1627
+ displayType: "page",
1628
+ title: pageData.title,
1629
+ metaParts: [
1630
+ pageData.spaceId ? `space=${pageData.spaceId}` : "",
1631
+ tags ? `tags=${tags}` : "",
1632
+ `updated=${pageData.updatedAt || pageData.updated_at || pageData.updated || "Unknown"}`
1633
+ ].filter(Boolean)
1634
+ }
1635
+ ];
1636
+ })
1637
+ );
1638
+ pageEntries.forEach((entry) => metaMap.set(entry[0], entry[1]));
1639
+ const agentEntries = await Promise.all(
1640
+ (mentions.agents || []).map(async (agentId) => {
1641
+ const agentData = await readSafe(dispatch, agentId);
1642
+ if (!agentData) {
1643
+ return [`agent:${agentId}`, { displayType: "agent", metaParts: [] }];
1644
+ }
1645
+ const desc = truncateMetaText(
1646
+ agentData.description || agentData.introduction || ""
1647
+ );
1648
+ return [
1649
+ `agent:${agentId}`,
1650
+ {
1651
+ displayType: "agent",
1652
+ title: agentData.name,
1653
+ metaParts: [
1654
+ `public=${agentData.isPublic ? "yes" : "no"}`,
1655
+ desc ? `desc=${desc}` : ""
1656
+ ].filter(Boolean)
1657
+ }
1658
+ ];
1659
+ })
1660
+ );
1661
+ agentEntries.forEach((entry) => metaMap.set(entry[0], entry[1]));
1662
+ const spaceEntries = await Promise.all(
1663
+ (mentions.spaces || []).map(async (spaceId) => {
1664
+ const spaceKey = createSpaceKey.space(spaceId);
1665
+ const spaceData = await readSafe(dispatch, spaceKey);
1666
+ if (!spaceData) {
1667
+ return [`space:${spaceId}`, { displayType: "space", metaParts: [] }];
1668
+ }
1669
+ const desc = truncateMetaText(spaceData.description || "");
1670
+ const categoriesCount = Object.keys(spaceData.categories || {}).length;
1671
+ const contentsCount = Object.keys(spaceData.contents || {}).length;
1672
+ return [
1673
+ `space:${spaceId}`,
1674
+ {
1675
+ displayType: "space",
1676
+ title: spaceData.name,
1677
+ metaParts: [
1678
+ desc ? `desc=${desc}` : "",
1679
+ `categories=${categoriesCount}`,
1680
+ `contents=${contentsCount}`
1681
+ ].filter(Boolean)
1682
+ }
1683
+ ];
1684
+ })
1685
+ );
1686
+ spaceEntries.forEach((entry) => metaMap.set(entry[0], entry[1]));
1687
+ return metaMap;
1688
+ };
1689
+ var buildInlineMention = (node, metaMap) => {
1690
+ const resourceType = node.resourceType || "unknown";
1691
+ const resourceId = node.resourceId || "unknown";
1692
+ const key = `${resourceType}:${resourceId}`;
1693
+ const meta = metaMap.get(key);
1694
+ const label = meta?.title || node.label || resourceId || "mention";
1695
+ const displayType = meta?.displayType || resourceType;
1696
+ const metaParts = meta?.metaParts ?? [];
1697
+ const idPart = resourceType === "tool" ? `tool=${resourceId}` : `dbkey=${resourceId}`;
1698
+ const metaSuffix = metaParts.length ? ` | ${metaParts.join(" | ")}` : "";
1699
+ return `@${label}(${displayType} | ${idPart}${metaSuffix})`;
1700
+ };
1701
+ var clipReferenceText = (value, max) => {
1702
+ const raw = typeof value === "string" ? value : value == null ? "" : JSON.stringify(value);
1703
+ return clipMultilineText(raw, max);
1704
+ };
1705
+ var fetchDialogReference = async (dbKey, refContent, dispatch) => {
1706
+ const dialogConfig = refContent;
1707
+ const dialogTitle = dialogConfig.title || `Untitled Dialog (${dbKey})`;
1708
+ const dialogId = extractCustomId(dbKey) || dbKey.replace(/^dialog-/, "");
1709
+ const checkpoint = dialogConfig.runtimeCheckpoint || null;
1710
+ const summary = asTrimmedString(dialogConfig.summary);
1711
+ const messages = await dispatch(
1712
+ async (_dispatch, getState, { db }) => {
1713
+ const state = getState();
1714
+ const { currentToken: token, remoteServers } = getRuntimeServerContext(state);
1715
+ return await fetchAndCacheMessages({
1716
+ db,
1717
+ dialogId,
1718
+ limit: DIALOG_REFERENCE_MESSAGE_LIMIT,
1719
+ token,
1720
+ remoteServers: remoteServers.length > 0 ? remoteServers : void 0
1721
+ });
1722
+ }
1723
+ );
1724
+ const sortedMessages = [...messages].reverse();
1725
+ const formatContent = (content) => clipReferenceText(content, DIALOG_REFERENCE_SNIPPET_CHARS);
1726
+ const transcript = sortedMessages.map((msg, index) => {
1727
+ const toolLine = msg.toolName ? ` tool=${msg.toolName}` : "";
1728
+ const agentLine = msg.cybotKey ? ` agent=${msg.cybotKey}` : "";
1729
+ const createdLine = msg.createdAt ? ` at=${msg.createdAt}` : "";
1730
+ return [
1731
+ `### Message ${index + 1}: ${msg.role || "unknown"} id=${msg.id || "unknown"}${toolLine}${agentLine}${createdLine}`,
1732
+ formatContent(msg.content) || "[empty]"
1733
+ ].join("\n");
1734
+ }).join("\n\n");
1735
+ const checkpointLines = [];
1736
+ if (checkpoint && typeof checkpoint === "object") {
1737
+ if (checkpoint.status) checkpointLines.push(`- status: ${checkpoint.status}`);
1738
+ if (checkpoint.lastUserInput) checkpointLines.push(`- lastUserInput: ${formatContent(checkpoint.lastUserInput)}`);
1739
+ if (checkpoint.lastAssistantText) checkpointLines.push(`- lastAssistantText: ${formatContent(checkpoint.lastAssistantText)}`);
1740
+ if (Array.isArray(checkpoint.lastToolNames) && checkpoint.lastToolNames.length) {
1741
+ checkpointLines.push(`- lastToolNames: ${checkpoint.lastToolNames.join(", ")}`);
1742
+ }
1743
+ if (Array.isArray(checkpoint.availableToolNames) && checkpoint.availableToolNames.length) {
1744
+ checkpointLines.push(`- availableToolNames: ${checkpoint.availableToolNames.join(", ")}`);
1745
+ }
1746
+ }
1747
+ const recentToolEvidence = sortedMessages.filter((msg) => msg.role === "tool" || msg.toolName).slice(-3).map((msg) => {
1748
+ const label = msg.toolName ? `${msg.toolName}` : "tool";
1749
+ return `- ${label} id=${msg.id || "unknown"}: ${clipReferenceText(msg.content, DIALOG_HANDOFF_SNIPPET_CHARS) || "[empty]"}`;
1750
+ });
1751
+ const handoffLines = [
1752
+ `- Use this when continuing work, transferring to another Agent, comparing with the current task, or preparing a document/plan from the prior discussion.`,
1753
+ `- Current state source: ${checkpointLines.length ? "Runtime Checkpoint" : "summaries and recent transcript"}.`,
1754
+ summary ? `- Compressed background: passive summary is available below; treat it as lossy, not original wording.` : "",
1755
+ recentToolEvidence.length ? `- Recent tool evidence:
1756
+ ${recentToolEvidence.join("\n")}` : `- Recent tool evidence: none loaded in the latest ${DIALOG_REFERENCE_MESSAGE_LIMIT} messages.`,
1757
+ `- For exact claims, old decisions, original wording, files/tools mentioned earlier, or anything not visible in the recent transcript, call searchDialogMessages with DB Key ${dbKey}.`
1758
+ ].filter(Boolean);
1759
+ const referenceBody = [
1760
+ `Conversation Reference:`,
1761
+ `DB Key: ${dbKey}`,
1762
+ `Title: ${dialogTitle}`,
1763
+ `Status: ${dialogConfig.status || "unknown"}`,
1764
+ `Loaded Recent Messages: ${sortedMessages.length}`,
1765
+ `Conversation Handoff:
1766
+ ${handoffLines.join("\n")}`,
1767
+ checkpointLines.length ? `Runtime Checkpoint:
1768
+ ${checkpointLines.join("\n")}` : "",
1769
+ summary ? `Passive Summary (compressed history, not original wording):
1770
+ ${wrapHistoricalSummaryWithReplayGuard(summary)}` : "",
1771
+ `Recent Transcript (original message excerpts, oldest to newest):
1772
+ ${transcript || "[no recent messages loaded]"}`,
1773
+ [
1774
+ `Coverage Note: This reference intentionally loads only the latest ${DIALOG_REFERENCE_MESSAGE_LIMIT} messages plus summaries/checkpoint to control token load.`,
1775
+ `Original Message Lookup Policy: If the user asks for an exact old message, original wording, who said what, why a decision was made, early-history detail, file/tool evidence, failed attempts, or a comparison with prior work, use searchDialogMessages({ dialogKey: "${dbKey}", query: "..." }) before making a factual claim from this referenced conversation.`
1776
+ ].join("\n")
1777
+ ].filter(Boolean).join("\n\n");
1778
+ const tokenEstimate = estimateTokenCount(referenceBody);
1779
+ return `${referenceBody}
1780
+
1781
+ Token Load Estimate: ${tokenEstimate} tokens for this conversation reference.
1782
+ ---
1783
+
1784
+ `;
1785
+ };
1786
+ var fetchTableReference = async (dbKey, refContent, dispatch) => {
1787
+ const tableMeta = refContent;
1788
+ const title = tableMeta.displayName || tableMeta.description || `Untitled Table (${dbKey})`;
1789
+ const { markdown: tableMd } = await dispatch(
1790
+ async (_dispatch, getState, { db }) => {
1791
+ const state = getState();
1792
+ const { currentToken: token, remoteServers } = getRuntimeServerContext(state);
1793
+ return await fetchAndSerializeTable(tableMeta, db, {
1794
+ token,
1795
+ remoteServers
1796
+ });
1797
+ }
1798
+ );
1799
+ const tags = tableMeta.tags?.length ? tableMeta.tags.join(", ") : "None";
1800
+ const description = tableMeta.description || "No description provided.";
1801
+ return `Reference Item (Table):
1802
+ DB Key: ${dbKey}
1803
+ Title: ${title}
1804
+ Description: ${description}
1805
+ Tags: ${tags}
1806
+ Content (Markdown Table):
1807
+
1808
+ ${tableMd}
1809
+ ---
1810
+
1811
+ `;
1812
+ };
1813
+ var fetchSlateReference = async (dbKey, refContent, dispatch, options) => {
1814
+ if (!refContent?.slateData) return null;
1815
+ const title = refContent.title || `Untitled (${dbKey})`;
1816
+ let contentString;
1817
+ let contentType;
1818
+ const inlineMentionMeta = options.inlineMentionMeta ?? options.format === "simplified_markdown";
1819
+ switch (options.format) {
1820
+ case "text":
1821
+ contentType = "Plain Text";
1822
+ contentString = slateToText(refContent.slateData);
1823
+ break;
1824
+ case "simplified_markdown":
1825
+ contentType = "Simplified Markdown";
1826
+ if (inlineMentionMeta) {
1827
+ const metaMap = await buildMentionMetaMap(refContent.slateData, dispatch);
1828
+ contentString = slateToSimplifiedMarkdown(refContent.slateData, {
1829
+ mentionResolver: (node) => buildInlineMention(node, metaMap)
1830
+ });
1831
+ } else {
1832
+ contentString = slateToSimplifiedMarkdown(refContent.slateData);
1833
+ }
1834
+ break;
1835
+ case "json":
1836
+ default:
1837
+ contentType = "Slate JSON";
1838
+ contentString = JSON.stringify(refContent.slateData, null, 2);
1839
+ break;
1840
+ }
1841
+ if (!contentString || typeof contentString === "string" && !contentString.trim() || contentString === "[]") {
1842
+ return null;
1843
+ }
1844
+ const tags = (refContent.tags || []).length > 0 ? refContent.tags.join(", ") : "None";
1845
+ const createdAt = refContent.created || "Unknown Creation Date";
1846
+ const updatedAt = refContent.updated || "Unknown Update Date";
1847
+ return `Reference Item:
1848
+ DB Key: ${dbKey}
1849
+ Title: ${title}
1850
+ Content (${contentType}):
1851
+ ${contentString}
1852
+ Tags: ${tags}
1853
+ Created At: ${createdAt}
1854
+ Updated At: ${updatedAt}
1855
+ ---
1856
+
1857
+ `;
1858
+ };
1859
+ var fetchReferenceContents = async (references, dispatch, options = { format: "simplified_markdown" }) => {
1860
+ const result = /* @__PURE__ */ new Map();
1861
+ if (!references || references.length === 0) return result;
1862
+ const referencePromises = references.map(async (dbKey) => {
1863
+ try {
1864
+ const hasPreloaded = options.preloaded?.has(dbKey);
1865
+ const refContent = hasPreloaded ? options.preloaded?.get(dbKey) : await dispatch(read({
1866
+ dbKey
1867
+ })).unwrap();
1868
+ if (!refContent) return null;
1869
+ let formatted = null;
1870
+ if (refContent.type === "dialog" /* DIALOG */) {
1871
+ formatted = await fetchDialogReference(dbKey, refContent, dispatch);
1872
+ } else if (refContent.type === "table" /* TABLE */) {
1873
+ formatted = await fetchTableReference(dbKey, refContent, dispatch);
1874
+ } else {
1875
+ formatted = await fetchSlateReference(dbKey, refContent, dispatch, options);
1876
+ }
1877
+ if (formatted) return [dbKey, formatted];
1878
+ return null;
1879
+ } catch (error) {
1880
+ console.error(`Error fetching reference ${dbKey}:`, error);
1881
+ return null;
1882
+ }
1883
+ });
1884
+ const resolved = await Promise.all(referencePromises);
1885
+ resolved.forEach((item) => {
1886
+ if (item) result.set(item[0], item[1]);
1887
+ });
1888
+ return result;
1889
+ };
1890
+
1891
+ export {
1892
+ fetchReferenceContents,
1893
+ mergeReferences,
1894
+ resolveReferenceAssets,
1895
+ resolveToolsFromKeys,
1896
+ resolveClientWire,
1897
+ resolveAgentCallPlan,
1898
+ generateRequestBody,
1899
+ performServerProxyFetchWithRetry,
1900
+ performFetchRequest
1901
+ };