nolo-cli 0.8.0-alpha.6 → 0.8.0-alpha.7

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 (174) hide show
  1. package/_executeModel-XIGO7HW5.js +198 -0
  2. package/action-PAXRPJJF.js +27 -0
  3. package/addContentAction-CZVWF3QZ.js +25 -0
  4. package/addDialogAgentAction-CCIDTPHC.js +67 -0
  5. package/agentDeleteCommand-47B24JYG.js +323 -0
  6. package/agentEmailCommands-D4FC6OZJ.js +621 -0
  7. package/agentListCommands-UFET7CC4.js +219 -0
  8. package/agentMachineCommands-LH7QDQPP.js +421 -0
  9. package/agentPullCommand-O2MTUAFR.js +122 -0
  10. package/agentRecordCommands-CWS2B5IA.js +89 -0
  11. package/agentRunCommand-3FRPISLG.js +102 -0
  12. package/agentRunControl-K4VKNEHF.js +57 -0
  13. package/agentRuntimeLocal-JNQQC2WG.js +99 -0
  14. package/agentSlice-XDFSELFJ.js +41 -0
  15. package/authCommand-WXMD3IPR.js +574 -0
  16. package/authCommands-X74AFDTC.js +26 -0
  17. package/chunk-2EISRLRC.js +238 -0
  18. package/chunk-2FTTDCD4.js +675 -0
  19. package/chunk-2JHWPW5B.js +2127 -0
  20. package/chunk-2LMT6K6N.js +171 -0
  21. package/chunk-2MALU52L.js +51 -0
  22. package/chunk-364VYAX2.js +19 -0
  23. package/chunk-3ASDTTEI.js +1774 -0
  24. package/chunk-3EUW3WEO.js +8 -0
  25. package/chunk-3LY4F7SV.js +9293 -0
  26. package/chunk-4CQLVGRV.js +50 -0
  27. package/chunk-4IJYA27C.js +342 -0
  28. package/chunk-4SN6J65J.js +38 -0
  29. package/chunk-4VNS5WPM.js +42 -0
  30. package/chunk-543C7RDK.js +562 -0
  31. package/chunk-572EKYLF.js +792 -0
  32. package/chunk-5MIDPSSK.js +206 -0
  33. package/chunk-5MMAK75Q.js +15 -0
  34. package/chunk-5XH3NZ4T.js +3631 -0
  35. package/chunk-63W5N6P3.js +150 -0
  36. package/chunk-6HYVJV7B.js +102 -0
  37. package/chunk-6PWWWMI7.js +628 -0
  38. package/chunk-6WD3OOJS.js +20 -0
  39. package/chunk-A3X4Y7MO.js +4294 -0
  40. package/chunk-AR7ZSGDI.js +929 -0
  41. package/chunk-ATNTHIZI.js +13 -0
  42. package/chunk-AUGHVUFE.js +69 -0
  43. package/chunk-AVMKZHBC.js +85 -0
  44. package/chunk-AZPCASRE.js +36 -0
  45. package/chunk-B76D3JJK.js +1447 -0
  46. package/chunk-BR2WP3DF.js +548 -0
  47. package/chunk-BSTNFPHD.js +231 -0
  48. package/chunk-CF2WZF4N.js +134 -0
  49. package/chunk-CF7PE763.js +10 -0
  50. package/chunk-CKOJQDKR.js +198 -0
  51. package/chunk-CM54RSSA.js +206 -0
  52. package/chunk-CWMSB67P.js +34 -0
  53. package/chunk-DA2OEKS6.js +27 -0
  54. package/chunk-DFFIZ25G.js +30 -0
  55. package/chunk-DWLEOOGR.js +8 -0
  56. package/chunk-DZ3XJVET.js +231 -0
  57. package/chunk-E5HMHIKL.js +222 -0
  58. package/chunk-EHLHSX7R.js +1433 -0
  59. package/chunk-ELRRLDWI.js +478 -0
  60. package/chunk-EYEEHCU4.js +3066 -0
  61. package/chunk-G3SUCT4W.js +8 -0
  62. package/chunk-G5H7RNFL.js +807 -0
  63. package/chunk-GAKEBQD6.js +30 -0
  64. package/chunk-GBRG75BQ.js +86 -0
  65. package/chunk-GEKCOPTN.js +190 -0
  66. package/chunk-H2RMRZJE.js +113 -0
  67. package/chunk-H33743XH.js +25 -0
  68. package/chunk-HEIIIZBX.js +104 -0
  69. package/chunk-HNMXYYJR.js +12 -0
  70. package/chunk-IAXBCTTE.js +175 -0
  71. package/chunk-IDZTNRP2.js +85 -0
  72. package/chunk-IECI4YHR.js +421 -0
  73. package/chunk-ISNCLGUZ.js +146 -0
  74. package/chunk-IYQV26RA.js +138 -0
  75. package/chunk-JBTJAPUF.js +35 -0
  76. package/chunk-JZPBVBIY.js +94 -0
  77. package/chunk-KK6SWS5B.js +1078 -0
  78. package/chunk-KQHGZWSV.js +63 -0
  79. package/chunk-KTI2WDDG.js +24674 -0
  80. package/chunk-KUG52IAP.js +8 -0
  81. package/chunk-KX6YBIHG.js +8 -0
  82. package/chunk-LCBAMY2M.js +60 -0
  83. package/chunk-LM25IZBJ.js +902 -0
  84. package/chunk-LM6IYQ3F.js +16 -0
  85. package/chunk-M76ECQRD.js +13658 -0
  86. package/chunk-MRC4Q34M.js +188 -0
  87. package/chunk-NE3E3XJ2.js +936 -0
  88. package/chunk-NXZGF7F7.js +2878 -0
  89. package/chunk-OF5H3QWS.js +300 -0
  90. package/chunk-OLZBQWZU.js +6 -0
  91. package/chunk-OVGXXUVI.js +91 -0
  92. package/chunk-OWOHNGCN.js +50 -0
  93. package/chunk-PN7AFLOK.js +3401 -0
  94. package/chunk-QSJ3HFEF.js +8 -0
  95. package/chunk-QYXLLLGL.js +4519 -0
  96. package/chunk-ROWQEJRP.js +139 -0
  97. package/chunk-S7Z2HMCN.js +25 -0
  98. package/chunk-SL3EPWB4.js +1949 -0
  99. package/chunk-TDIQFT2F.js +301 -0
  100. package/chunk-TILFE6LV.js +381 -0
  101. package/chunk-U4TRT5V4.js +246 -0
  102. package/chunk-U6VC4MU4.js +8 -0
  103. package/chunk-UAD2WT54.js +64 -0
  104. package/chunk-USZDUWOV.js +191 -0
  105. package/chunk-USZMK5UT.js +105 -0
  106. package/chunk-UVPF33PW.js +46995 -0
  107. package/chunk-V2F4OGYM.js +9013 -0
  108. package/chunk-VEJLAVTC.js +2052 -0
  109. package/chunk-VF4K2QE6.js +21 -0
  110. package/chunk-VHBWHNVT.js +59 -0
  111. package/chunk-VIDPVFP3.js +20 -0
  112. package/chunk-VP4WJWKW.js +8882 -0
  113. package/chunk-VQ2AJRGD.js +148 -0
  114. package/chunk-W4NVOSFF.js +37 -0
  115. package/chunk-WWC7I6TA.js +8 -0
  116. package/chunk-X7W4TNB4.js +1550 -0
  117. package/chunk-XDVAYP26.js +537 -0
  118. package/chunk-XKIMRZO2.js +221 -0
  119. package/chunk-Y5GCAMGP.js +9 -0
  120. package/chunk-YD43KPCK.js +360 -0
  121. package/chunk-YIJFUVKA.js +34 -0
  122. package/chunk-Z4NR32XR.js +50 -0
  123. package/chunk-ZNFJWEN4.js +56 -0
  124. package/cliExecutor-DNE7TCC4.js +36 -0
  125. package/clipboardy-BVE3LVEH.js +12001 -0
  126. package/createAgentAutomationAction-3QTGNYJC.js +864 -0
  127. package/createDialogAction-5YX3ARBK.js +52 -0
  128. package/createPageAction-EQNQQRCW.js +169 -0
  129. package/db-HCJ5PRB5.js +271 -0
  130. package/dbSlice-C4UJLRZP.js +59 -0
  131. package/deleteFile-4SKGPHOZ.js +41 -0
  132. package/dialogCommands-AOQS23FV.js +59 -0
  133. package/dialogSlice-GZE3NCMC.js +146 -0
  134. package/docCreateCommands-GVOQVJON.js +215 -0
  135. package/docDeleteCommands-GEB7YAUZ.js +176 -0
  136. package/docReadCommands-XYKI2DF2.js +129 -0
  137. package/docStore-MLM5AME5.js +96 -0
  138. package/docUpdateCommands-4L3RAMHZ.js +313 -0
  139. package/fetchMessages-JOCYIFKL.js +16 -0
  140. package/getPricing-PWPJ6MNV.js +30 -0
  141. package/handleSendMessageAction-WG2GKTGZ.js +183 -0
  142. package/index.js +188 -113035
  143. package/localDialogRead-D3BELSTF.js +26 -0
  144. package/localFirstLog-DHNOY2NA.js +19 -0
  145. package/localRuntimeAuthority-TEGCOWX4.js +471 -0
  146. package/localRuntimeDb-LGDF6FQP.js +12 -0
  147. package/machineCommands-ZNXKLH6Q.js +774 -0
  148. package/machineInfo-M6KB6HZN.js +10 -0
  149. package/machineWsRunDispatch-7WRG6HNV.js +105 -0
  150. package/memoryCommands-O4MIPIWQ.js +476 -0
  151. package/models-XLEOET3E.js +9 -0
  152. package/offlineMarxistsAgentCommand-BCPJITJL.js +242 -0
  153. package/package.json +3 -25
  154. package/read-RIJCIVKX.js +17 -0
  155. package/readDocTool-GZD2N3LO.js +16 -0
  156. package/readlineWorkspace-AQURUDN4.js +5357 -0
  157. package/removeDialogAgentAction-CXLST3N6.js +72 -0
  158. package/runAgentClientLoop-VQUEKGA5.js +288 -0
  159. package/runtimeDoctorCommands-LRHLPDRC.js +289 -0
  160. package/setDialogExtraReferencesAction-LP6VYGU7.js +59 -0
  161. package/setPrimaryDialogAgentAction-D3GGH23T.js +79 -0
  162. package/settingSlice-J4I3Z5H7.js +198 -0
  163. package/skillSummaryMarker-42HKSXYY.js +9 -0
  164. package/slateToRenderMarkdown-Y5IYN73U.js +7 -0
  165. package/slateUtils-2M7MUTWX.js +19 -0
  166. package/spaceCommands-R2RXD5UY.js +450 -0
  167. package/spaceSlice-5UT4JNIN.js +145 -0
  168. package/streamAgentChatTurn-NRWSQKFN.js +4503 -0
  169. package/tableCommands-66XEWHAK.js +1286 -0
  170. package/toolApiClient-QI3YBNWB.js +26 -0
  171. package/tools-TNMUDDRK.js +83 -0
  172. package/understanding-HCSFPE7R.js +318 -0
  173. package/updateCommands-VOSPKXFF.js +31 -0
  174. package/updateDialogTitleAction-IXOKAVX3.js +185 -0
@@ -0,0 +1,2127 @@
1
+ import {
2
+ MEMORY_USE_GUIDANCE,
3
+ wrapHistoricalSummaryWithReplayGuard
4
+ } from "./chunk-DA2OEKS6.js";
5
+ import {
6
+ ANTIGRAVITY_CLOUD_CODE_BASE_URL,
7
+ isAntigravityOAuthAgent
8
+ } from "./chunk-2MALU52L.js";
9
+ import {
10
+ clipMultilineText,
11
+ fetchAndSerializeTable
12
+ } from "./chunk-UVPF33PW.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-NXZGF7F7.js";
26
+ import {
27
+ estimateTokenCount,
28
+ fetchAndCacheMessages
29
+ } from "./chunk-KTI2WDDG.js";
30
+ import {
31
+ fetchServerSyncedCredential
32
+ } from "./chunk-543C7RDK.js";
33
+ import {
34
+ createSpaceKey
35
+ } from "./chunk-UAD2WT54.js";
36
+ import {
37
+ OPENAI_RESPONSES_ENDPOINT,
38
+ buildProviderAuthHeaders,
39
+ convertMessagesToResponsesInput,
40
+ isOpenAiResponsesModel,
41
+ resolvePlatformChatCompletionsEndpoint
42
+ } from "./chunk-XDVAYP26.js";
43
+ import {
44
+ canonicalizeToolNames
45
+ } from "./chunk-LM25IZBJ.js";
46
+ import {
47
+ getModelConfig,
48
+ isModelSupportReasoningEffort
49
+ } from "./chunk-572EKYLF.js";
50
+ import {
51
+ createFileCredentialBroker
52
+ } from "./chunk-TDIQFT2F.js";
53
+ import {
54
+ isDeepInfraKimiModel,
55
+ isFireworksKimiModel,
56
+ resolveFireworksKimiModel
57
+ } from "./chunk-BR2WP3DF.js";
58
+ import {
59
+ extractCustomId
60
+ } from "./chunk-DFFIZ25G.js";
61
+ import {
62
+ toErrorMessage
63
+ } from "./chunk-HNMXYYJR.js";
64
+ import {
65
+ read
66
+ } from "./chunk-G5H7RNFL.js";
67
+ import {
68
+ asNonEmptyStringArray
69
+ } from "./chunk-PN7AFLOK.js";
70
+ import {
71
+ asTrimmedLowercaseString
72
+ } from "./chunk-QSJ3HFEF.js";
73
+ import {
74
+ getRuntimeServerContext
75
+ } from "./chunk-EYEEHCU4.js";
76
+ import {
77
+ isAbortError
78
+ } from "./chunk-QYXLLLGL.js";
79
+ import {
80
+ isLoopbackUrl
81
+ } from "./chunk-4SN6J65J.js";
82
+ import {
83
+ API_ENDPOINTS
84
+ } from "./chunk-LCBAMY2M.js";
85
+ import {
86
+ asTrimmedString
87
+ } from "./chunk-3EUW3WEO.js";
88
+ import {
89
+ asOptionalTrimmedString
90
+ } from "./chunk-G3SUCT4W.js";
91
+
92
+ // packages/ai/skills/referenceRuntime.ts
93
+ var joinUniqueStrings = (...groups) => Array.from(new Set(groups.flatMap((items) => asNonEmptyStringArray(items))));
94
+ var extractRuntimePageCapabilities = (content) => {
95
+ const meta = resolvePageSkillMetadata(content);
96
+ const directTools = asNonEmptyStringArray(content?.tools);
97
+ const skillConfig = meta?.skillConfig;
98
+ const skillTools = skillConfig?.toolNames ?? [];
99
+ const softSkillHints = asNonEmptyStringArray([
100
+ skillConfig?.name,
101
+ ...meta?.recommendedSkills ?? []
102
+ ]);
103
+ return {
104
+ directTools,
105
+ hardSkillKeys: meta?.requiredSkills ?? [],
106
+ softSkillKeys: meta?.recommendedSkills ?? [],
107
+ hardSkillTools: meta?.kind === "skill" ? skillTools : [],
108
+ softSkillHints,
109
+ promptPatches: skillConfig?.promptPatch ? [skillConfig.promptPatch] : [],
110
+ shouldUpgradeReference: directTools.length > 0 || meta?.kind === "skill" || !!skillConfig?.promptPatch
111
+ };
112
+ };
113
+ var buildSkillGuidancePromptBlock = (options) => {
114
+ const title = asOptionalTrimmedString(options.title) ?? "--- \u6280\u80FD\u63D0\u793A ---";
115
+ const recommendedSkillHints = joinUniqueStrings(options.recommendedSkillHints);
116
+ const skillPromptPatches = joinUniqueStrings(options.skillPromptPatches);
117
+ if (recommendedSkillHints.length === 0 && skillPromptPatches.length === 0) {
118
+ return "";
119
+ }
120
+ return [
121
+ title,
122
+ 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")}` : "",
123
+ ...skillPromptPatches
124
+ ].filter(Boolean).join("\n");
125
+ };
126
+ var buildIdentifierCandidates = (identifier, contentByKey) => {
127
+ const trimmed = identifier.trim();
128
+ if (!trimmed || contentByKey.has(trimmed)) return trimmed;
129
+ const candidateToKey = /* @__PURE__ */ new Map();
130
+ for (const [key, page] of Array.from(contentByKey.entries())) {
131
+ const meta = resolvePageSkillMetadata(page);
132
+ for (const value of [key, page?.dbKey, page?.title, meta?.skillConfig?.id, meta?.skillConfig?.name]) {
133
+ const trimmedValue = asOptionalTrimmedString(value);
134
+ if (trimmedValue) {
135
+ candidateToKey.set(trimmedValue, key);
136
+ }
137
+ }
138
+ }
139
+ return candidateToKey.get(trimmed) ?? trimmed;
140
+ };
141
+ async function resolveSkillGraphFromRoots(options) {
142
+ const contentByKey = new Map(options.contentByKey ?? []);
143
+ const requiredTools = /* @__PURE__ */ new Set();
144
+ const recommendedTools = /* @__PURE__ */ new Set();
145
+ const recommendedSkillHints = /* @__PURE__ */ new Set();
146
+ const skillPromptPatches = /* @__PURE__ */ new Set();
147
+ const visits = [];
148
+ const visited = /* @__PURE__ */ new Set();
149
+ const loadPageCached = async (identifier) => {
150
+ const resolvedIdentifier = buildIdentifierCandidates(identifier, contentByKey);
151
+ if (!resolvedIdentifier) return null;
152
+ if (contentByKey.has(resolvedIdentifier)) {
153
+ return contentByKey.get(resolvedIdentifier) ?? null;
154
+ }
155
+ const page = await options.loadPage(resolvedIdentifier);
156
+ if (page) {
157
+ contentByKey.set(resolvedIdentifier, page);
158
+ if (page.dbKey) {
159
+ contentByKey.set(page.dbKey, page);
160
+ }
161
+ }
162
+ return page ?? null;
163
+ };
164
+ const visit = async (identifier, mode, sourceLabel) => {
165
+ const page = await loadPageCached(identifier);
166
+ if (!page?.dbKey) return;
167
+ const visitKey = `${mode}:${page.dbKey}`;
168
+ if (visited.has(visitKey)) return;
169
+ visited.add(visitKey);
170
+ const meta = resolvePageSkillMetadata(page);
171
+ const directTools = canonicalizeToolNames(page.tools ?? []);
172
+ const skillTools = canonicalizeToolNames(meta?.skillConfig?.toolNames ?? []);
173
+ const mergedTools = joinUniqueStrings(directTools, skillTools);
174
+ visits.push({
175
+ dbKey: page.dbKey,
176
+ title: page.title,
177
+ mode,
178
+ sourceLabel,
179
+ meta
180
+ });
181
+ if (mode === "required") {
182
+ mergedTools.forEach((toolName) => requiredTools.add(toolName));
183
+ if (meta?.skillConfig?.promptPatch) {
184
+ skillPromptPatches.add(meta.skillConfig.promptPatch);
185
+ }
186
+ } else {
187
+ mergedTools.forEach((toolName) => recommendedTools.add(toolName));
188
+ if (meta?.skillConfig?.name) {
189
+ recommendedSkillHints.add(meta.skillConfig.name);
190
+ }
191
+ }
192
+ const nextHard = meta?.requiredSkills ?? meta?.skillConfig?.requiredSkills ?? [];
193
+ const nextSoft = meta?.recommendedSkills ?? meta?.skillConfig?.recommendedSkills ?? [];
194
+ if (mode === "required") {
195
+ await Promise.all(nextHard.map((childKey) => visit(childKey, "required", page.dbKey)));
196
+ await Promise.all(nextSoft.map((childKey) => visit(childKey, "recommended", page.dbKey)));
197
+ return;
198
+ }
199
+ await Promise.all([...nextHard, ...nextSoft].map((childKey) => visit(childKey, "recommended", page.dbKey)));
200
+ };
201
+ await Promise.all(options.roots.map((root) => visit(root.identifier, root.mode, root.sourceLabel)));
202
+ return {
203
+ requiredTools: Array.from(requiredTools),
204
+ recommendedTools: Array.from(recommendedTools),
205
+ recommendedSkillHints: Array.from(recommendedSkillHints),
206
+ skillPromptPatches: Array.from(skillPromptPatches),
207
+ contentByKey,
208
+ visits
209
+ };
210
+ }
211
+
212
+ // packages/ai/agent/referenceUtils.ts
213
+ function mergeReferences(base, extra) {
214
+ const safeBase = Array.isArray(base) ? base : [];
215
+ const safeExtra = Array.isArray(extra) ? extra : [];
216
+ const seen = /* @__PURE__ */ new Set();
217
+ const merged = [];
218
+ for (const item of [...safeBase, ...safeExtra]) {
219
+ const key = item.dbKey;
220
+ if (key && seen.has(key)) continue;
221
+ if (key) seen.add(key);
222
+ merged.push(item);
223
+ }
224
+ return merged;
225
+ }
226
+ var loadContentsByKeys = async (keys, dispatch, preloaded) => {
227
+ const contentByKey = /* @__PURE__ */ new Map();
228
+ const uniqueKeys = Array.from(new Set(keys.filter(Boolean)));
229
+ await Promise.all(
230
+ uniqueKeys.map(async (dbKey) => {
231
+ if (preloaded?.has(dbKey)) {
232
+ const content = preloaded.get(dbKey);
233
+ if (content) contentByKey.set(dbKey, content);
234
+ return;
235
+ }
236
+ try {
237
+ const content = await dispatch(read({ dbKey })).unwrap();
238
+ if (content) contentByKey.set(dbKey, content);
239
+ } catch {
240
+ }
241
+ })
242
+ );
243
+ return contentByKey;
244
+ };
245
+ var resolveReferenceAssets = async (references, dispatch) => {
246
+ if (!Array.isArray(references) || references.length === 0) {
247
+ return {
248
+ references: [],
249
+ referencedTools: [],
250
+ recommendedSkillTools: [],
251
+ recommendedSkillHints: [],
252
+ skillPromptPatches: [],
253
+ contentByKey: /* @__PURE__ */ new Map()
254
+ };
255
+ }
256
+ const entries = await Promise.all(
257
+ references.filter((ref) => ref?.dbKey).map(async (ref) => {
258
+ try {
259
+ const content = await dispatch(read({ dbKey: ref.dbKey })).unwrap();
260
+ return { ref, content };
261
+ } catch {
262
+ return { ref, content: null };
263
+ }
264
+ })
265
+ );
266
+ const contentByKey = /* @__PURE__ */ new Map();
267
+ const toolSet = /* @__PURE__ */ new Set();
268
+ const recommendedToolSet = /* @__PURE__ */ new Set();
269
+ const recommendedSkillHints = /* @__PURE__ */ new Set();
270
+ const skillPromptPatches = /* @__PURE__ */ new Set();
271
+ const normalizedReferences = [];
272
+ const hardSkillKeys = /* @__PURE__ */ new Set();
273
+ const softSkillKeys = /* @__PURE__ */ new Set();
274
+ for (const { ref, content } of entries) {
275
+ if (content) {
276
+ contentByKey.set(ref.dbKey, content);
277
+ }
278
+ const capabilities = extractRuntimePageCapabilities(content);
279
+ for (const tool of capabilities.directTools) {
280
+ toolSet.add(tool);
281
+ }
282
+ for (const tool of capabilities.hardSkillTools) {
283
+ toolSet.add(tool);
284
+ }
285
+ for (const hint of capabilities.softSkillHints) {
286
+ recommendedSkillHints.add(hint);
287
+ }
288
+ for (const patch of capabilities.promptPatches) {
289
+ skillPromptPatches.add(patch);
290
+ }
291
+ for (const skillKey of capabilities.hardSkillKeys) {
292
+ hardSkillKeys.add(skillKey);
293
+ }
294
+ for (const skillKey of capabilities.softSkillKeys) {
295
+ softSkillKeys.add(skillKey);
296
+ }
297
+ normalizedReferences.push({
298
+ ...ref,
299
+ type: capabilities.shouldUpgradeReference ? "instruction" : ref.type
300
+ });
301
+ }
302
+ const resolvedSkillLinks = await resolveSkillGraphFromRoots({
303
+ roots: [
304
+ ...Array.from(hardSkillKeys).map((identifier) => ({ identifier, mode: "required" })),
305
+ ...Array.from(softSkillKeys).map((identifier) => ({ identifier, mode: "recommended" }))
306
+ ],
307
+ loadPage: async (identifier) => {
308
+ const loaded = await loadContentsByKeys([identifier], dispatch, contentByKey);
309
+ return loaded.get(identifier) ?? null;
310
+ },
311
+ contentByKey
312
+ });
313
+ resolvedSkillLinks.contentByKey.forEach((value, key) => contentByKey.set(key, value));
314
+ for (const tool of resolvedSkillLinks.requiredTools) {
315
+ toolSet.add(tool);
316
+ }
317
+ for (const tool of resolvedSkillLinks.recommendedTools) {
318
+ recommendedToolSet.add(tool);
319
+ }
320
+ for (const hint of resolvedSkillLinks.recommendedSkillHints) {
321
+ recommendedSkillHints.add(hint);
322
+ }
323
+ for (const patch of resolvedSkillLinks.skillPromptPatches) {
324
+ skillPromptPatches.add(patch);
325
+ }
326
+ return {
327
+ references: normalizedReferences,
328
+ referencedTools: Array.from(toolSet),
329
+ recommendedSkillTools: Array.from(recommendedToolSet),
330
+ recommendedSkillHints: Array.from(recommendedSkillHints),
331
+ skillPromptPatches: Array.from(skillPromptPatches),
332
+ contentByKey
333
+ };
334
+ };
335
+ var resolveToolsFromKeys = async (keys, dispatch, preloaded) => {
336
+ if (!Array.isArray(keys) || keys.length === 0) {
337
+ return {
338
+ tools: [],
339
+ recommendedSkillTools: [],
340
+ recommendedSkillHints: [],
341
+ skillPromptPatches: [],
342
+ contentByKey: /* @__PURE__ */ new Map()
343
+ };
344
+ }
345
+ const contentByKey = await loadContentsByKeys(keys, dispatch, preloaded);
346
+ const toolSet = /* @__PURE__ */ new Set();
347
+ const recommendedToolSet = /* @__PURE__ */ new Set();
348
+ const recommendedSkillHints = /* @__PURE__ */ new Set();
349
+ const skillPromptPatches = /* @__PURE__ */ new Set();
350
+ const hardSkillKeys = /* @__PURE__ */ new Set();
351
+ const softSkillKeys = /* @__PURE__ */ new Set();
352
+ for (const content of contentByKey.values()) {
353
+ const capabilities = extractRuntimePageCapabilities(content);
354
+ for (const tool of [...capabilities.directTools, ...capabilities.hardSkillTools]) {
355
+ toolSet.add(tool);
356
+ }
357
+ for (const hint of capabilities.softSkillHints) {
358
+ recommendedSkillHints.add(hint);
359
+ }
360
+ for (const patch of capabilities.promptPatches) {
361
+ skillPromptPatches.add(patch);
362
+ }
363
+ for (const skillKey of capabilities.hardSkillKeys) {
364
+ hardSkillKeys.add(skillKey);
365
+ }
366
+ for (const skillKey of capabilities.softSkillKeys) {
367
+ softSkillKeys.add(skillKey);
368
+ }
369
+ }
370
+ const resolvedSkillLinks = await resolveSkillGraphFromRoots({
371
+ roots: [
372
+ ...Array.from(hardSkillKeys).map((identifier) => ({ identifier, mode: "required" })),
373
+ ...Array.from(softSkillKeys).map((identifier) => ({ identifier, mode: "recommended" }))
374
+ ],
375
+ loadPage: async (identifier) => {
376
+ const loaded = await loadContentsByKeys([identifier], dispatch, contentByKey);
377
+ return loaded.get(identifier) ?? null;
378
+ },
379
+ contentByKey
380
+ });
381
+ resolvedSkillLinks.contentByKey.forEach((value, key) => contentByKey.set(key, value));
382
+ for (const tool of resolvedSkillLinks.requiredTools) {
383
+ toolSet.add(tool);
384
+ }
385
+ for (const tool of resolvedSkillLinks.recommendedTools) {
386
+ recommendedToolSet.add(tool);
387
+ }
388
+ for (const hint of resolvedSkillLinks.recommendedSkillHints) {
389
+ recommendedSkillHints.add(hint);
390
+ }
391
+ for (const patch of resolvedSkillLinks.skillPromptPatches) {
392
+ skillPromptPatches.add(patch);
393
+ }
394
+ return {
395
+ tools: Array.from(toolSet),
396
+ recommendedSkillTools: Array.from(recommendedToolSet),
397
+ recommendedSkillHints: Array.from(recommendedSkillHints),
398
+ skillPromptPatches: Array.from(skillPromptPatches),
399
+ contentByKey
400
+ };
401
+ };
402
+
403
+ // packages/agent-runtime/serverProxyPolicy.ts
404
+ var OAUTH_APIKEY_REFS = /* @__PURE__ */ new Set([
405
+ "antigravity",
406
+ "xai",
407
+ "chatgpt",
408
+ "claude"
409
+ ]);
410
+ function isGoogleFamilyProvider(provider) {
411
+ const normalized = asTrimmedLowercaseString(provider);
412
+ return normalized === "google" || normalized.startsWith("google-");
413
+ }
414
+ function isOAuthApiKeyRef(value) {
415
+ const ref = asTrimmedLowercaseString(value);
416
+ return ref.length > 0 && OAUTH_APIKEY_REFS.has(ref);
417
+ }
418
+ function shouldUseServerProxy(agentConfig, requestProvider) {
419
+ const effectiveProvider = (requestProvider || agentConfig.provider || "").toLowerCase();
420
+ if (isGoogleFamilyProvider(effectiveProvider)) {
421
+ return true;
422
+ }
423
+ if (isOAuthApiKeyRef(agentConfig.apiKeyRef)) {
424
+ return true;
425
+ }
426
+ if (agentConfig.apiSource === "custom" && isRemoteCustomEndpoint(agentConfig.customProviderUrl)) {
427
+ return true;
428
+ }
429
+ return !!agentConfig.useServerProxy;
430
+ }
431
+ var LOCAL_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "::1", "0.0.0.0"]);
432
+ function isRemoteCustomEndpoint(url) {
433
+ if (typeof url !== "string") return false;
434
+ try {
435
+ const host = new URL(url).hostname.toLowerCase();
436
+ return !LOCAL_HOSTS.has(host);
437
+ } catch {
438
+ return false;
439
+ }
440
+ }
441
+
442
+ // packages/agent-runtime/agentCallPlan.ts
443
+ var CODEX_RESPONSES_URL = "https://chatgpt.com/backend-api/codex/responses";
444
+ var CURSOR_AGENT_URL = "https://api2.cursor.sh/agent.v1.AgentService/Run";
445
+ function resolveClientWire(plan) {
446
+ if (plan.upstreamWire === "gemini-cca") return "chat.completions";
447
+ if (plan.upstreamWire === "anthropic-messages") return "chat.completions";
448
+ if (plan.upstreamWire === "cursor-connect") return "chat.completions";
449
+ if (plan.upstreamWire === "responses" && plan.authMethod.kind === "oauth" && plan.authMethod.ref === "chatgpt") {
450
+ return "chat.completions";
451
+ }
452
+ return plan.upstreamWire;
453
+ }
454
+ var XAI_CHAT_COMPLETIONS_URL = "https://api.x.ai/v1/chat/completions";
455
+ var ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages";
456
+ var CODEX_REQUIRED_HEADERS = [
457
+ "chatgpt-account-id",
458
+ "OpenAI-Beta",
459
+ "originator"
460
+ ];
461
+ var ANTIGRAVITY_REQUIRED_HEADERS = [
462
+ "User-Agent"
463
+ // antigravity-specific UA (matches getAntigravityUserAgent)
464
+ ];
465
+ function agentShouldUseServerProxy(agentConfig) {
466
+ return shouldUseServerProxy(agentConfig);
467
+ }
468
+ function resolveAgentCallPlan(agentConfig, _env) {
469
+ const apiKeyRef = asTrimmedLowercaseString(agentConfig.apiKeyRef);
470
+ const provider = asTrimmedLowercaseString(
471
+ agentConfig.provider ?? agentConfig.apiSource
472
+ );
473
+ if (isAntigravityOAuthAgent(agentConfig)) {
474
+ return {
475
+ authMethod: { kind: "oauth", ref: "antigravity" },
476
+ transport: "server-proxy",
477
+ upstreamWire: "gemini-cca",
478
+ endpoint: ANTIGRAVITY_CLOUD_CODE_BASE_URL,
479
+ requiredHeaders: [...ANTIGRAVITY_REQUIRED_HEADERS],
480
+ vendor: provider || "google-antigravity"
481
+ };
482
+ }
483
+ if (apiKeyRef === "chatgpt") {
484
+ return {
485
+ authMethod: { kind: "oauth", ref: "chatgpt" },
486
+ transport: "server-proxy",
487
+ upstreamWire: "responses",
488
+ endpoint: CODEX_RESPONSES_URL,
489
+ requiredHeaders: [...CODEX_REQUIRED_HEADERS],
490
+ vendor: provider || "openai"
491
+ };
492
+ }
493
+ if (apiKeyRef === "claude") {
494
+ return {
495
+ authMethod: { kind: "oauth", ref: "claude" },
496
+ transport: "server-proxy",
497
+ upstreamWire: "anthropic-messages",
498
+ endpoint: ANTHROPIC_MESSAGES_URL,
499
+ requiredHeaders: ["anthropic-version", "anthropic-beta"],
500
+ vendor: provider || "anthropic"
501
+ };
502
+ }
503
+ if (apiKeyRef === "xai") {
504
+ return {
505
+ authMethod: { kind: "oauth", ref: "xai" },
506
+ transport: "server-proxy",
507
+ upstreamWire: "chat.completions",
508
+ endpoint: XAI_CHAT_COMPLETIONS_URL,
509
+ requiredHeaders: [],
510
+ vendor: provider || "xai"
511
+ };
512
+ }
513
+ if (apiKeyRef === "cursor") {
514
+ return {
515
+ authMethod: { kind: "oauth", ref: "cursor" },
516
+ transport: "direct",
517
+ upstreamWire: "cursor-connect",
518
+ endpoint: CURSOR_AGENT_URL,
519
+ requiredHeaders: [
520
+ "x-cursor-client-version",
521
+ "x-cursor-client-type",
522
+ "x-ghost-mode"
523
+ ],
524
+ vendor: provider || "cursor"
525
+ };
526
+ }
527
+ if (agentConfig.cliProvider || agentConfig.apiSource === "cli" || provider === "cli") {
528
+ return {
529
+ authMethod: { kind: "cli", provider: agentConfig.cliProvider || provider || "codex" },
530
+ transport: "direct",
531
+ upstreamWire: "cli",
532
+ endpoint: "",
533
+ requiredHeaders: [],
534
+ vendor: provider || "cli"
535
+ };
536
+ }
537
+ if (agentConfig.customProviderUrl || agentConfig.apiSource === "custom") {
538
+ const transport2 = agentShouldUseServerProxy(agentConfig) ? "server-proxy" : "direct";
539
+ const endpoint2 = asOptionalTrimmedString(agentConfig.customProviderUrl) ?? "";
540
+ const upstreamWire2 = endpoint2.includes("/responses") ? "responses" : "chat.completions";
541
+ return {
542
+ authMethod: { kind: "custom-key" },
543
+ transport: transport2,
544
+ upstreamWire: upstreamWire2,
545
+ endpoint: endpoint2,
546
+ requiredHeaders: [],
547
+ vendor: provider || "custom"
548
+ };
549
+ }
550
+ const transport = agentShouldUseServerProxy(agentConfig) ? "server-proxy" : "direct";
551
+ const useResponses = isOpenAiResponsesModel({
552
+ provider,
553
+ model: agentConfig.model,
554
+ endpointKey: agentConfig.endpointKey
555
+ });
556
+ const upstreamWire = useResponses ? "responses" : "chat.completions";
557
+ const endpoint = useResponses ? OPENAI_RESPONSES_ENDPOINT : resolvePlatformChatCompletionsEndpoint(provider) ?? "";
558
+ return {
559
+ authMethod: { kind: "platform-key" },
560
+ transport,
561
+ upstreamWire,
562
+ endpoint,
563
+ requiredHeaders: [],
564
+ vendor: provider || "openai"
565
+ };
566
+ }
567
+
568
+ // packages/ai/llm/usageRequestOptions.ts
569
+ var STREAM_USAGE_PROVIDERS = /* @__PURE__ */ new Set([
570
+ "google",
571
+ "openrouter",
572
+ "xai",
573
+ "openai",
574
+ "fireworks",
575
+ "mistral",
576
+ "cloudflare",
577
+ "gmi"
578
+ ]);
579
+ var EXTRA_USAGE_FIELD_PROVIDERS = /* @__PURE__ */ new Set(["openrouter"]);
580
+ var normalizeProviderName = (providerName) => asTrimmedLowercaseString(providerName);
581
+ var getUsageRequestOptions = (providerName, options) => {
582
+ const normalizedProvider = normalizeProviderName(providerName);
583
+ const api = options?.api ?? "chat-completions";
584
+ if (api === "responses") {
585
+ return EXTRA_USAGE_FIELD_PROVIDERS.has(normalizedProvider) ? {
586
+ usage: {
587
+ include: true
588
+ }
589
+ } : {};
590
+ }
591
+ return {
592
+ ...STREAM_USAGE_PROVIDERS.has(normalizedProvider) ? {
593
+ stream_options: {
594
+ include_usage: true
595
+ }
596
+ } : {},
597
+ ...EXTRA_USAGE_FIELD_PROVIDERS.has(normalizedProvider) ? {
598
+ usage: {
599
+ include: true
600
+ }
601
+ } : {}
602
+ };
603
+ };
604
+
605
+ // packages/app/i18n/mapLanguage.ts
606
+ var languageMap = {
607
+ "en-US": "English",
608
+ "zh-CN": "Simplified Chinese",
609
+ "zh-TW": "Traditional Chinese",
610
+ "ja-JP": "Japanese"
611
+ // Add more mappings as needed
612
+ };
613
+ var mapLanguage = (responseLanguage) => {
614
+ return languageMap[responseLanguage] || responseLanguage;
615
+ };
616
+
617
+ // packages/ai/agent/contextLayerContract.ts
618
+ var buildContextLayerContractBlock = (options = {}) => {
619
+ const lines = [
620
+ "--- \u77E5\u8BC6\u5B58\u50A8\u7EA6\u5B9A ---",
621
+ "\u4E0D\u8981\u628A\u6240\u6709\u4FE1\u606F\u90FD\u585E\u8FDB\u540C\u4E00\u5C42\u3002\u4F18\u5148\u5229\u7528\u5DF2\u6709\u7684 memory / knowledge / doc\uFF0C\u800C\u4E0D\u662F\u628A\u5B83\u4EEC\u6DF7\u6210\u4E00\u6BB5\u957F\u5BF9\u8BDD\u3002",
622
+ "",
623
+ "\u5C42\u6B21\u8FB9\u754C\uFF1A",
624
+ "1. memory layer\uFF1A\u653E\u77ED\u5230\u4E2D\u671F\u3001\u53EF\u590D\u7528\u4F46\u4E0D\u5FC5\u6C38\u4E45\u6302\u8F7D\u7684\u504F\u597D\u3001\u8FD1\u671F\u5171\u8BC6\u548C\u538B\u7F29\u540E\u7684\u7ECF\u9A8C\uFF1B\u8981\u77ED\u3001\u53EF\u68C0\u7D22\u3001\u53EF\u66FF\u6362\u3002",
625
+ "2. knowledge layer\uFF1A\u653E\u7A33\u5B9A\u89C4\u5219\u3001\u957F\u671F\u6709\u6548\u4E8B\u5B9E\u548C\u6BCF\u8F6E\u90FD\u4F1A\u53CD\u590D\u4F9D\u8D56\u7684\u8BF4\u660E\uFF1B\u4F18\u5148\u901A\u8FC7 prompt / references \u81EA\u52A8\u52A0\u8F7D\u3002",
626
+ "3. doc layer\uFF1A\u653E\u9700\u8981\u8DE8\u8F6E\u6B21\u6301\u7EED\u7EF4\u62A4\u7684\u5916\u90E8\u5DE5\u4F5C\u53F0\uFF0C\u4F8B\u5982 runbook\u3001mission\u3001incident\u3001checkpoint\u3001idea backlog\u3001experiment log\uFF1B\u9700\u8981\u65F6\u663E\u5F0F\u8BFB\u53D6\u548C\u66F4\u65B0\u3002",
627
+ "",
628
+ "\u5199\u5165\u539F\u5219\uFF1A",
629
+ "- \u4E34\u65F6\u6B65\u9AA4\u3001\u539F\u59CB\u957F\u65E5\u5FD7\u3001\u4E00\u6B21\u6027\u601D\u8DEF\uFF0C\u4E0D\u8981\u76F4\u63A5\u5199\u8FDB memory \u6216 knowledge\u3002",
630
+ "- \u7A33\u5B9A\u884C\u4E3A\u89C4\u5219\u3001\u957F\u671F\u56FA\u5B9A\u7EA6\u675F\uFF0C\u4F18\u5148\u6C89\u6DC0\u5230 knowledge layer\u3002",
631
+ "- \u7528\u6237\u504F\u597D\u3001\u6700\u8FD1\u5F62\u6210\u7684\u534F\u4F5C\u5171\u8BC6\u3001\u8FD1\u671F\u53CD\u590D\u6709\u7528\u7684\u7ECF\u9A8C\uFF0C\u4F18\u5148\u6C89\u6DC0\u5230 memory layer\u3002",
632
+ "- \u9700\u8981\u8DE8\u8F6E\u6B21\u63A5\u529B\u7684\u4EFB\u52A1\u72B6\u6001\u3001\u8FD0\u884C\u624B\u518C\u3001\u4E8B\u6545\u8BB0\u5F55\u3001\u68C0\u67E5\u70B9\uFF0C\u4F18\u5148\u5199\u5165 doc layer\u3002"
633
+ ];
634
+ if (options.hasRememberMemoryTool) {
635
+ lines.push(
636
+ "- \u5F53\u67D0\u6761\u504F\u597D\u3001\u8FD1\u671F\u5171\u8BC6\u6216\u590D\u7528\u7ECF\u9A8C\u5BF9\u672A\u6765\u660E\u663E\u6709\u5E2E\u52A9\u65F6\uFF0C\u53EF\u4EE5\u8C03\u7528 rememberMemory\uFF0C\u4F46\u8981\u5199\u6210\u7B80\u6D01\u53EF\u590D\u7528\u7684\u4E00\u53E5\u8BDD\uFF1B\u53EA\u6709\u5F53\u524D dialog \u660E\u786E\u7ED1\u5B9A\u4E86 space\uFF0C\u4E14\u5185\u5BB9\u5C5E\u4E8E\u5171\u4EAB\u534F\u4F5C\u89C4\u5219\u65F6\u624D\u5199 space memory\u3002"
637
+ );
638
+ }
639
+ if (options.hasDocTools) {
640
+ lines.push(
641
+ "- \u5F53\u4EFB\u52A1\u9700\u8981 24h \u8FDE\u7EED\u8FD0\u884C\u3001\u8DE8 dialog \u63A5\u529B\u6216\u4EBA\u5DE5\u4E0E agent \u5171\u8BFB\u65F6\uFF0C\u4F18\u5148\u628A mission / runbook / incident / checkpoint / idea backlog / experiment log \u5199\u5165 doc layer\u3002"
642
+ );
643
+ }
644
+ return lines.join("\n");
645
+ };
646
+
647
+ // packages/ai/agent/startupProtocol.ts
648
+ var buildStartupProtocolBlock = (options = {}) => {
649
+ const lines = [
650
+ "--- \u542F\u52A8\u534F\u8BAE ---",
651
+ "\u542F\u52A8\u987A\u5E8F\uFF1A",
652
+ "1. \u5148\u8BFB\u53D6 policy / knowledge\uFF1A\u4F60\u7684\u6838\u5FC3 prompt\u3001\u81EA\u52A8\u52A0\u8F7D\u7684 references\u3001\u4EE5\u53CA\u7528\u6237\u7B56\u7565\u7EA6\u675F\u3002",
653
+ "2. \u518D\u63D0\u70BC current mission\uFF1A\u4F18\u5148\u4ECE\u5F53\u524D\u7528\u6237\u8F93\u5165\u548C\u5F53\u524D\u8F93\u5165\u4E0A\u4E0B\u6587\u91CC\u786E\u8BA4\u672C\u8F6E\u76EE\u6807\u3001\u4EA4\u4ED8\u7269\u548C\u505C\u6B62\u6761\u4EF6\u3002",
654
+ "3. \u518D\u5438\u6536 recent memory\uFF1A\u7ED3\u5408 Memory Overlay\u3001\u5386\u53F2\u6458\u8981\u3001\u6700\u8FD1\u5DE5\u4F5C\u8BB0\u5FC6\u548C\u5FC5\u8981\u7684\u5386\u53F2\u5F15\u7528\uFF0C\u53EA\u4FDD\u7559\u5BF9\u672C\u8F6E\u771F\u6B63\u6709\u5E2E\u52A9\u7684\u90E8\u5206\u3002",
655
+ "4. \u9700\u8981\u65F6\u518D\u8BFB\u53D6 doc\uFF1A\u5982\u679C\u4EFB\u52A1\u6D89\u53CA\u8DE8\u8F6E\u6B21\u63A5\u529B\u3001\u8FD0\u884C\u624B\u518C\u6216\u5171\u4EAB\u5DE5\u4F5C\u53F0\uFF0C\u8BFB\u53D6\u76F8\u5173 doc \u83B7\u53D6\u6700\u65B0\u72B6\u6001\u3002",
656
+ "",
657
+ "\u5728\u7B2C\u4E00\u6B21\u5DE5\u5177\u8C03\u7528\u524D\uFF0C\u5148\u5F62\u6210\u4E00\u4EFD\u5185\u90E8 working state\uFF0C\u81F3\u5C11\u5305\u542B\uFF1A",
658
+ "- current_goal\uFF1A\u8FD9\u4E00\u8F6E\u771F\u6B63\u8981\u5B8C\u6210\u4EC0\u4E48",
659
+ "- constraints\uFF1A\u5F53\u524D\u7EA6\u675F\u3001\u504F\u597D\u3001\u8FB9\u754C\u6761\u4EF6",
660
+ "- missing_facts\uFF1A\u8FD8\u7F3A\u54EA\u4E9B\u4E8B\u5B9E\u624D\u80FD\u5B89\u5168\u884C\u52A8",
661
+ "- next_action\uFF1A\u4E0B\u4E00\u6B65\u6700\u5C0F\u4E14\u9AD8\u4EF7\u503C\u7684\u52A8\u4F5C",
662
+ "",
663
+ "\u51B3\u7B56\u89C4\u5219\uFF1A",
664
+ "- \u5982\u679C policy / knowledge \u5DF2\u7ECF\u8DB3\u591F\u56DE\u7B54\uFF0C\u5C31\u76F4\u63A5\u56DE\u7B54\uFF0C\u4E0D\u8981\u4E3A\u4E86\u663E\u5F97\u5FD9\u800C\u4E71\u8C03\u7528\u5DE5\u5177\u3002",
665
+ "- \u5982\u679C recent memory \u4E0E\u5F53\u524D\u7528\u6237\u8F93\u5165\u51B2\u7A81\uFF0C\u4EE5\u5F53\u524D\u7528\u6237\u8F93\u5165\u4E3A\u51C6\u3002",
666
+ "- \u5982\u679C\u9700\u8981\u4F9D\u8D56\u73AF\u5883\u3001\u6587\u4EF6\u72B6\u6001\u3001\u8FD0\u884C\u65F6\u4E8B\u5B9E\u6216\u5916\u90E8\u771F\u503C\uFF0C\u5148\u9A8C\u8BC1\uFF0C\u518D\u884C\u52A8\u3002",
667
+ "- \u4F18\u5148\u5C0F\u6B65\u63A8\u8FDB\uFF1B\u6BCF\u4E00\u8F6E\u5148\u505A\u6700\u80FD\u964D\u4F4E\u4E0D\u786E\u5B9A\u6027\u7684\u52A8\u4F5C\u3002"
668
+ ];
669
+ if (options.hasCheckEnvTool || options.hasExecShellTool) {
670
+ lines.push(
671
+ "- \u53EA\u8981\u4EFB\u52A1\u6D89\u53CA\u547D\u4EE4\u6267\u884C\u3001shell \u8BED\u6CD5\u3001\u8DEF\u5F84\u7EA6\u5B9A\u3001\u8FD0\u884C\u5E73\u53F0\u6216\u670D\u52A1\u72B6\u6001\uFF0C\u5E76\u4E14\u8FD9\u4E9B\u4E8B\u5B9E\u8FD8\u4E0D\u591F\u660E\u786E\uFF0C\u5C31\u5148\u786E\u8BA4\u73AF\u5883\u3002"
672
+ );
673
+ }
674
+ if (options.hasCheckEnvTool) {
675
+ lines.push(
676
+ "- \u73AF\u5883\u4E0D\u660E\u786E\u65F6\uFF0C\u4F18\u5148\u8C03\u7528 checkEnv({ check: 'context' })\uFF0C\u518D\u51B3\u5B9A\u540E\u7EED\u547D\u4EE4\u548C\u5DE5\u5177\u8DEF\u5F84\u3002"
677
+ );
678
+ }
679
+ if (options.hasExecShellTool) {
680
+ lines.push(
681
+ "- \u9700\u8981\u6267\u884C\u547D\u4EE4\u65F6\uFF0C\u5148\u6839\u636E\u5DF2\u786E\u8BA4\u7684\u73AF\u5883\u9009\u62E9 shell\uFF1BWindows \u9ED8\u8BA4 PowerShell\uFF0CLinux/macOS \u9ED8\u8BA4 bash\u3002"
682
+ );
683
+ lines.push(
684
+ "- \u5982\u679C\u53EA\u662F\u6536\u96C6\u591A\u4E2A\u53EA\u8BFB\u73AF\u5883\u4E8B\u5B9E\uFF0C\u4F18\u5148\u5408\u5E76\u6210\u4E00\u6B21 shell \u8C03\u7528\u6216\u4E00\u6761\u7EC4\u5408\u547D\u4EE4\uFF0C\u907F\u514D\u62C6\u6210\u5F88\u591A\u5C0F\u63A2\u9488\u3002"
685
+ );
686
+ }
687
+ return lines.join("\n");
688
+ };
689
+
690
+ // packages/ai/agent/runtimeGuidance.ts
691
+ var normalizeToolName = (name) => name.replace(/[-_]/g, "").toLowerCase();
692
+ var hasAnyTool = (normalizedTools, candidates) => candidates.some((candidate) => normalizedTools.has(normalizeToolName(candidate)));
693
+ var hasAllTools = (normalizedTools, candidates) => candidates.every((candidate) => normalizedTools.has(normalizeToolName(candidate)));
694
+ var buildEmailRegistrationWorkflowBlock = (enabled) => {
695
+ if (!enabled) return "";
696
+ return [
697
+ "--- \u90AE\u7BB1\u9A8C\u8BC1\u7801\u6CE8\u518C\u6D41\u7A0B ---",
698
+ "\u5F53\u7528\u6237\u8981\u6C42\u4F60\u6CE8\u518C\u7F51\u7AD9\u8D26\u53F7\u65F6\uFF0C\u53EA\u5141\u8BB8\u5904\u7406\u7528\u6237\u660E\u786E\u6307\u5B9A\u7684\u5F53\u524D\u76EE\u6807\u7F51\u7AD9\uFF0C\u4E0D\u8981\u81EA\u884C\u6269\u5C55\u5230\u5176\u4ED6\u7F51\u7AD9\u3001\u6279\u91CF\u6CE8\u518C\u6216\u89C4\u907F\u5E73\u53F0\u98CE\u63A7\u3002",
699
+ "",
700
+ "\u5206\u9636\u6BB5\u534F\u8BAE\uFF1Adiscover before acting -> assess supportability -> register -> verify -> closeout\u3002",
701
+ "",
702
+ "\u63A8\u8350\u6D41\u7A0B\uFF1A",
703
+ "1. discover before acting\uFF1A\u5148\u7528 browser_openSession / browser_readContent \u9605\u8BFB\u9875\u9762\uFF0C\u786E\u8BA4\u76EE\u6807\u6CE8\u518C\u9875 URL\u3001\u8D26\u53F7\u7528\u9014\u3001\u5FC5\u586B\u9879\u548C\u505C\u6B62\u6761\u4EF6\uFF1B\u4E0D\u8981\u4E00\u6253\u5F00\u9875\u9762\u5C31\u76F2\u70B9\u6309\u94AE\u3002\u5982\u679C\u7F3A\u5C11\u76EE\u6807\u7F51\u7AD9\uFF0C\u5148\u8BE2\u95EE\u7528\u6237\u3002",
704
+ "2. assess supportability\uFF1A\u5148\u5224\u65AD\u8BE5\u6D41\u7A0B\u662F\u5426\u652F\u6301\u5F53\u524D\u53D7\u63A7\u81EA\u52A8\u5316\u3002\u9047\u5230 CAPTCHA\u3001\u624B\u673A\u53F7\u9A8C\u8BC1\u3001\u652F\u4ED8\u3001\u8EAB\u4EFD/KYC\u3001OAuth-only\u3001\u670D\u52A1\u6761\u6B3E\u786E\u8BA4\u3001\u6216\u4EFB\u4F55\u770B\u8D77\u6765\u50CF\u89C4\u907F\u98CE\u63A7\u7684\u6B65\u9AA4\u65F6\uFF0C\u5FC5\u987B\u7ACB\u5373\u505C\u6B62\u5E76\u5411\u7528\u6237\u8BF4\u660E blockingReason\uFF1B\u4E0D\u8981\u786C\u95EF\u3002",
705
+ "3. register\uFF1A\u53EA\u6709\u5728\u786E\u8BA4\u652F\u6301\u540E\uFF0C\u624D\u4F7F\u7528 email_provision_identity \u4E3A\u5F53\u524D agent \u751F\u6210\u53D7\u63A7\u57DF\u540D\u90AE\u7BB1\u8EAB\u4EFD\uFF0C\u518D\u4F7F\u7528 browser_openSession / browser_typeText / browser_click / browser_readContent \u586B\u5199\u5E76\u63D0\u4EA4\u6CE8\u518C\u8868\u5355\u3002",
706
+ "4. verify\uFF1A\u63D0\u4EA4\u540E\u4F7F\u7528 email_wait_for \u7B49\u5F85\u8BE5 agent \u6536\u4EF6\u7BB1\u91CC\u7684\u9A8C\u8BC1\u90AE\u4EF6\uFF0C\u518D\u7528 email_extract_verification \u63D0\u53D6\u9A8C\u8BC1\u7801\u6216\u9A8C\u8BC1\u94FE\u63A5\uFF0C\u56DE\u586B\u9A8C\u8BC1\u7801\u6216\u6253\u5F00\u9A8C\u8BC1\u94FE\u63A5\u5B8C\u6210\u9A8C\u8BC1\u3002",
707
+ "5. closeout\uFF1A\u65E0\u8BBA\u6210\u529F\u8FD8\u662F\u5931\u8D25\u90FD\u8981 always close sessions\uFF0C\u4E3B\u52A8\u6E05\u7406\u6D4F\u89C8\u5668\u4F1A\u8BDD\uFF08\u4F8B\u5982 browser_closeSession\uFF09\u3002\u5982\u679C\u6D41\u7A0B\u5931\u8D25\uFF0C\u5FC5\u987B\u660E\u786E failedStage \u4E0E blockingReason\uFF0C\u5E76\u8BF4\u660E\u53EF\u6062\u590D\u9009\u9879\uFF1B\u4E0D\u8981\u76F2\u76EE\u5C1D\u8BD5\u65E0\u5173\u7F51\u7AD9\u6216\u7ED5\u8FC7\u9A8C\u8BC1\u3002",
708
+ "6. \u6700\u7EC8\u53EA\u5728\u5BF9\u8BDD\u4E2D\u8FD4\u56DE\u8D26\u53F7\u3001\u90AE\u7BB1\u548C\u4E00\u6B21\u6027\u751F\u6210\u7684\u5BC6\u7801\uFF1B\u4E0D\u8981\u6301\u4E45\u5316\u5BC6\u7801\uFF0C\u4E0D\u8981\u5199\u5165 agent metadata\u3001\u6570\u636E\u5E93\u3001\u6587\u6863\u6216\u8BB0\u5FC6\u3002",
709
+ "",
710
+ "\u5FC5\u987B\u6682\u505C\u5E76\u8BE2\u95EE\u7528\u6237\u7684\u60C5\u51B5\uFF1ACAPTCHA\u3001\u624B\u673A\u53F7\u9A8C\u8BC1\u3001\u652F\u4ED8\u3001\u8EAB\u4EFD/KYC\u3001OAuth \u6388\u6743\u3001OAuth-only\u3001\u670D\u52A1\u6761\u6B3E\u786E\u8BA4\u3001\u6216\u4EFB\u4F55\u770B\u8D77\u6765\u50CF\u89C4\u907F\u98CE\u63A7\u7684\u6B65\u9AA4\u3002",
711
+ "\u5982\u679C\u6D41\u7A0B\u5931\u8D25\uFF0C\u8BF4\u660E failedStage\u3001blockingReason \u548C\u53EF\u6062\u590D\u9009\u9879\uFF0C\u4E0D\u8981\u76F2\u76EE\u5C1D\u8BD5\u65E0\u5173\u7F51\u7AD9\u6216\u7ED5\u8FC7\u9A8C\u8BC1\u3002"
712
+ ].join("\n");
713
+ };
714
+ var buildWebResearchToolPolicyBlock = (hasExecShellTool, hasFetchWebpageTool) => {
715
+ if (!hasExecShellTool || !hasFetchWebpageTool) return "";
716
+ return [
717
+ "--- \u751F\u4EA7\u73AF\u5883\u7F51\u9875\u7814\u7A76\u5DE5\u5177\u7B56\u7565 ---",
718
+ "\u751F\u4EA7\u73AF\u5883\u7F51\u9875\u7814\u7A76\u4F18\u5148\u4F7F\u7528 fetchWebpage\u3001\u7AD9\u70B9 Markdown / llms.txt\u3001\u6216\u4E13\u7528\u6D4F\u89C8/\u641C\u7D22\u5DE5\u5177\u3002",
719
+ "\u4E0D\u8981\u7528 execShell \u8C03 curl\u3001grep\u3001sed \u7B49\u547D\u4EE4\u6293\u7F51\u9875\u6216\u622A\u53D6\u7F51\u9875\u6BB5\u843D\uFF1B\u751F\u4EA7\u73AF\u5883\u901A\u5E38\u4F1A\u7981\u7528 dev shell\uFF0C\u53CD\u590D\u5C1D\u8BD5\u53EA\u4F1A\u6D6A\u8D39\u56DE\u5408\u3002",
720
+ "\u5982\u679C\u7F51\u9875\u5185\u5BB9\u8FC7\u957F\u6216\u951A\u70B9\u6BB5\u843D\u6CA1\u6709\u88AB\u5355\u72EC\u63D0\u53D6\uFF0C\u5148\u5BFB\u627E\u8BE5\u6587\u6863\u7AD9\u63D0\u4F9B\u7684 Markdown \u7248\u672C\u3001\u72EC\u7ACB\u9875\u9762\u3001llms.txt \u7D22\u5F15\u6216\u66F4\u5177\u4F53 URL\uFF0C\u518D\u7EE7\u7EED\u56DE\u7B54\u3002"
721
+ ].join("\n");
722
+ };
723
+ var resolveRuntimeGuidanceToolOptions = (tools = []) => {
724
+ const normalizedTools = canonicalizeToolNames(tools);
725
+ const normalizedToolSet = new Set(normalizedTools.map(normalizeToolName));
726
+ const hasBrowserTools = hasAllTools(normalizedToolSet, [
727
+ "browser_openSession",
728
+ "browser_readContent",
729
+ "browser_typeText",
730
+ "browser_click",
731
+ "browser_closeSession"
732
+ ]);
733
+ const hasBrowserProbe = hasAnyTool(normalizedToolSet, ["browser_probePage", "browserProbePage"]);
734
+ const hasEmailRegistrationTools = hasAllTools(normalizedToolSet, [
735
+ "email_provision_identity",
736
+ "email_wait_for",
737
+ "email_extract_verification"
738
+ ]);
739
+ return {
740
+ hasCheckEnvTool: normalizedTools.includes("checkEnv"),
741
+ hasExecShellTool: normalizedTools.includes("execShell"),
742
+ hasRememberMemoryTool: normalizedTools.includes("rememberMemory"),
743
+ hasDocTools: normalizedTools.some(
744
+ (tool) => ["read", "readDoc", "readPage", "createDoc", "updateDoc"].includes(tool)
745
+ ),
746
+ hasBrowserTools,
747
+ hasEmailRegistrationTools,
748
+ // Require browser_probePage to be present before enabling email registration workflow guidance.
749
+ hasEmailRegistrationWorkflow: hasBrowserTools && hasBrowserProbe && hasEmailRegistrationTools
750
+ };
751
+ };
752
+ var buildRuntimeGuidanceBlocks = (tools = []) => {
753
+ const options = resolveRuntimeGuidanceToolOptions(tools);
754
+ const normalizedTools = canonicalizeToolNames(tools);
755
+ return {
756
+ startupProtocol: buildStartupProtocolBlock({
757
+ hasCheckEnvTool: options.hasCheckEnvTool,
758
+ hasExecShellTool: options.hasExecShellTool
759
+ }),
760
+ contextLayerContract: buildContextLayerContractBlock({
761
+ hasRememberMemoryTool: options.hasRememberMemoryTool,
762
+ hasDocTools: options.hasDocTools
763
+ }),
764
+ emailRegistrationWorkflow: buildEmailRegistrationWorkflowBlock(
765
+ options.hasEmailRegistrationWorkflow
766
+ ),
767
+ webResearchToolPolicy: buildWebResearchToolPolicyBlock(
768
+ options.hasExecShellTool,
769
+ normalizedTools.includes("fetchWebpage")
770
+ )
771
+ };
772
+ };
773
+
774
+ // packages/ai/agent/pageBuilderHandoffRules.ts
775
+ var PAGE_BUILDER_AGENT_PUBLIC_KEY = "agent-pub-01PAGEBUILDR00000000FT7R9G";
776
+ var PAGE_BUILDER_SCENARIOS = [
777
+ {
778
+ id: "information-display",
779
+ label: "\u4FE1\u606F\u5C55\u793A",
780
+ 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",
781
+ 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"
782
+ },
783
+ {
784
+ id: "data-analysis",
785
+ label: "\u6570\u636E\u5206\u6790",
786
+ 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",
787
+ 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"
788
+ },
789
+ {
790
+ id: "process-guide",
791
+ label: "\u6D41\u7A0B\u8BF4\u660E",
792
+ userIntent: "\u6559\u7A0B\u3001SOP\u3001onboarding\u3001\u64CD\u4F5C\u6307\u5357\u3001\u8BFE\u7A0B\u6B65\u9AA4\u3001\u7533\u8BF7\u6D41\u7A0B",
793
+ 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"
794
+ },
795
+ {
796
+ id: "decision-comparison",
797
+ label: "\u51B3\u7B56\u6BD4\u8F83",
798
+ 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",
799
+ 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"
800
+ },
801
+ {
802
+ id: "plan-roadmap",
803
+ label: "\u8BA1\u5212\u6392\u5E03",
804
+ 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",
805
+ 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"
806
+ },
807
+ {
808
+ id: "mixed-pitch",
809
+ label: "\u6DF7\u5408\u957F\u5C3E",
810
+ 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",
811
+ 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"
812
+ }
813
+ ];
814
+ var scenarioLines = PAGE_BUILDER_SCENARIOS.map(
815
+ (scenario) => `- ${scenario.label}\uFF1A${scenario.userIntent}`
816
+ ).join("\n");
817
+ var PAGE_BUILDER_HANDOFF_INSTRUCTIONS = `--- \u9875\u9762\u751F\u6210\u52A9\u624B handoff ---
818
+ \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
819
+
820
+ \u76EE\u6807 Agent:
821
+ - agentKey: ${PAGE_BUILDER_AGENT_PUBLIC_KEY}
822
+ - \u63A8\u8350\u5DE5\u5177: runStreamingAgent
823
+
824
+ \u9002\u5408 handoff \u7684\u89C6\u89C9\u610F\u56FE\u5927\u7C7B\uFF1A
825
+ ${scenarioLines}
826
+
827
+ \u8C03\u7528\u8FB9\u754C\uFF1A
828
+ - \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
829
+ - \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
830
+ - \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
831
+ - 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
832
+ - \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`;
833
+
834
+ // packages/ai/agent/contextCompiler.ts
835
+ function createHash(_algo) {
836
+ let buf = "";
837
+ return {
838
+ update(s) {
839
+ buf += s;
840
+ return this;
841
+ },
842
+ digest(_enc) {
843
+ let h = 2166136261;
844
+ for (let i = 0; i < buf.length; i++) {
845
+ h ^= buf.charCodeAt(i);
846
+ h = h * 16777619 >>> 0;
847
+ }
848
+ return h.toString(16).padStart(8, "0");
849
+ }
850
+ };
851
+ }
852
+ var hasLayerContent = (layer) => Boolean(layer.content);
853
+ var estimateContextTokens = (content) => Math.ceil(content.length / 4);
854
+ var compileContextLayers = (layers) => {
855
+ const compiledLayers = [];
856
+ for (const layer of layers) {
857
+ if (!hasLayerContent(layer)) continue;
858
+ const estimatedTokens = estimateContextTokens(layer.content);
859
+ compiledLayers.push({
860
+ id: layer.id,
861
+ owner: layer.owner,
862
+ content: layer.content,
863
+ cacheScope: layer.cacheScope ?? "turn",
864
+ charCount: layer.content.length,
865
+ estimatedTokens,
866
+ tokenBudget: layer.tokenBudget,
867
+ budgetStatus: typeof layer.tokenBudget === "number" ? estimatedTokens <= layer.tokenBudget ? "within-budget" : "over-budget" : void 0
868
+ });
869
+ }
870
+ const stablePrefixLayers = [];
871
+ for (const layer of compiledLayers) {
872
+ if (layer.cacheScope === "turn") break;
873
+ stablePrefixLayers.push(layer);
874
+ }
875
+ const stablePrefixContent = stablePrefixLayers.map((layer) => layer.content).join("\n\n");
876
+ return {
877
+ content: compiledLayers.map((layer) => layer.content).join("\n\n"),
878
+ layers: compiledLayers,
879
+ cacheProfile: {
880
+ stablePrefixHash: createHash("sha256").update(stablePrefixContent).digest("hex"),
881
+ stablePrefixLayerIds: stablePrefixLayers.map((layer) => layer.id),
882
+ stablePrefixCharCount: stablePrefixContent.length,
883
+ stablePrefixEstimatedTokens: estimateContextTokens(stablePrefixContent)
884
+ }
885
+ };
886
+ };
887
+
888
+ // packages/ai/agent/currentTimeContext.ts
889
+ var pad2 = (value) => String(value).padStart(2, "0");
890
+ var resolveDefaultTimeZone = () => {
891
+ try {
892
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
893
+ } catch {
894
+ return "UTC";
895
+ }
896
+ };
897
+ var partsForTimeZone = (date, timeZone) => {
898
+ const parts = new Intl.DateTimeFormat("en-US", {
899
+ timeZone,
900
+ year: "numeric",
901
+ month: "2-digit",
902
+ day: "2-digit",
903
+ hour: "2-digit",
904
+ minute: "2-digit",
905
+ second: "2-digit",
906
+ hour12: false
907
+ }).formatToParts(date);
908
+ return Object.fromEntries(
909
+ parts.filter((part) => part.type !== "literal").map((part) => [part.type, part.value])
910
+ );
911
+ };
912
+ var zonedDateTime = (date, timeZone) => {
913
+ const parts = partsForTimeZone(date, timeZone);
914
+ return [
915
+ `${parts.year}-${parts.month}-${parts.day}`,
916
+ `${parts.hour}:${parts.minute}:${parts.second}`
917
+ ].join(" ");
918
+ };
919
+ var timeZoneOffset = (date, timeZone) => {
920
+ const parts = partsForTimeZone(date, timeZone);
921
+ const utcMs = Date.UTC(
922
+ Number(parts.year),
923
+ Number(parts.month) - 1,
924
+ Number(parts.day),
925
+ Number(parts.hour),
926
+ Number(parts.minute),
927
+ Number(parts.second)
928
+ );
929
+ const offsetMinutes = Math.round((utcMs - date.getTime()) / 6e4);
930
+ const sign = offsetMinutes >= 0 ? "+" : "-";
931
+ const absolute = Math.abs(offsetMinutes);
932
+ return `UTC${sign}${pad2(Math.floor(absolute / 60))}:${pad2(absolute % 60)}`;
933
+ };
934
+ var buildCurrentTimeBlock = (now = /* @__PURE__ */ new Date(), timeZone = resolveDefaultTimeZone()) => [
935
+ "--- \u5F53\u524D\u65F6\u95F4 ---",
936
+ `\u5F53\u524D\u65E5\u671F: ${zonedDateTime(now, timeZone).slice(0, 10)}`,
937
+ `\u5F53\u524D\u672C\u5730\u65F6\u95F4: ${zonedDateTime(now, timeZone)}`,
938
+ `\u672C\u5730\u65F6\u533A: ${timeZone} / ${timeZoneOffset(now, timeZone)}`,
939
+ `UTC \u65F6\u95F4: ${now.toISOString()}`,
940
+ "\u5F53\u7528\u6237\u95EE\u201C\u73B0\u5728\u201D\u201C\u5F53\u524D\u65F6\u95F4\u201D\u201C\u5317\u4EAC\u65F6\u95F4\u201D\u7B49\u65F6\u95F4\u95EE\u9898\u65F6\uFF0C\u76F4\u63A5\u4F7F\u7528\u8FD9\u91CC\u7684\u5F53\u524D\u65F6\u95F4\uFF1B\u4E0D\u8981\u53EA\u56DE\u7B54\u65E5\u671F\u3002",
941
+ "\u5F53\u7528\u6237\u8BF4\u201C\u4ECA\u5929\u201D\u201C\u4ECA\u65E5\u201D\u6216 today \u65F6\uFF0C\u9ED8\u8BA4\u6307\u5F53\u524D\u672C\u5730\u65E5\u671F\uFF0C\u9664\u975E\u7528\u6237\u660E\u786E\u7ED9\u51FA\u5176\u5B83\u65E5\u671F\u3002"
942
+ ].join("\n");
943
+
944
+ // packages/ai/agent/buildSystemPrompt.ts
945
+ var CONTEXT_USAGE_INSTRUCTIONS = `\u53C2\u8003\u8D44\u6599\u4F7F\u7528\u8BF4\u660E\uFF1A
946
+ - \u4E0B\u65B9\u63D0\u4F9B\u7684\u8D44\u6599\u662F\u4F60\u7684\u4E3B\u8981\u6743\u5A01\u4FE1\u606F\u6765\u6E90\u3002
947
+ - \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
948
+ - \u4F7F\u7528\u5176\u4E2D\u7684\u4E8B\u5B9E\u3001\u6570\u636E\u548C\u540D\u79F0\u65F6\uFF0C\u8981\u4FDD\u6301\u7CBE\u51C6\u3002
949
+ - \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
950
+ - \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
951
+ - \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`;
952
+ var MENU_USAGE_INSTRUCTIONS = `--- \u4EA4\u4E92\u8BF4\u660E ---
953
+ \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
954
+
955
+ ## \u4F55\u65F6\u8C03\u7528 ui_ask_choice
956
+ \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
957
+ 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
958
+ 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
959
+ 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
960
+
961
+ ## \u8C03\u7528 ui_ask_choice \u7684\u89C4\u8303
962
+ - \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
963
+ - \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
964
+ - \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
965
+ - \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
966
+ - \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`;
967
+ var WEBPAGE_ACCESS_INSTRUCTIONS = `--- \u7F51\u9875\u8BBF\u95EE\u80FD\u529B (Web Access) ---
968
+ \u83B7\u53D6\u5916\u90E8\u4FE1\u606F\u65F6\u7531\u7B80\u5165\u7E41\uFF1A
969
+ 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
970
+ 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
971
+ 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
972
+ 3. \u9700\u767B\u5F55/\u586B\u8868/\u591A\u6B65\u4EA4\u4E92 \u2192 browser_openSession\uFF08openSession \u62FF ID \u2192 typeText/click/readContent\uFF09\u3002
973
+ 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`;
974
+ var AGENT_ORCHESTRATION_INSTRUCTIONS = `--- Agent \u7F16\u6392\u4E0E\u534F\u4F5C ---
975
+ \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
976
+
977
+ 1\uFF09\u5B50 Agent \u534F\u4F5C
978
+ - \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
979
+ - \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
980
+ - \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
981
+ - 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
982
+ - \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
983
+ - \u5F53\u7528\u6237\u9700\u8981\u591A\u89C6\u89D2\u5206\u6790\u6216\u8FA9\u8BBA\u65F6\uFF0C\u4F60\u53EF\u4EE5\uFF1A
984
+ - \u5148\u7528 callAgent \u4F9D\u6B21\u8BE2\u95EE\u591A\u4E2A Agent \u5BF9\u540C\u4E00\u95EE\u9898\u7684\u770B\u6CD5\uFF1B
985
+ - \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
986
+
987
+ 2\uFF09\u5DE5\u4F5C\u6D41 / Workflow \u5DE5\u5177
988
+ - \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
989
+ - \u8C03\u7528\u5DE5\u4F5C\u6D41\u5DE5\u5177\u65F6\uFF0C\u4F60\u8D1F\u8D23\uFF1A
990
+ - \u6E05\u695A\u63CF\u8FF0\u76EE\u6807\u548C\u7EA6\u675F\uFF1B
991
+ - \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
992
+ - \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
993
+
994
+ 3\uFF09\u5371\u9669 / \u4E0D\u53EF\u9006\u64CD\u4F5C
995
+ - \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
996
+ - \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`;
997
+ var KNOWLEDGE_MANAGEMENT_INSTRUCTIONS = `--- \u77E5\u8BC6\u7BA1\u7406 ---
998
+ \u4E09\u5C42\u77E5\u8BC6\uFF1A
999
+ 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
1000
+ 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
1001
+ \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
1002
+ \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`;
1003
+ var MEMORY_CAPTURE_INSTRUCTIONS = `--- \u957F\u671F\u8BB0\u5FC6 ---
1004
+ \u4F60\u53EF\u7528 rememberMemory \u628A\u503C\u5F97\u957F\u671F\u4FDD\u7559\u7684\u4FE1\u606F\u5199\u6210\u4E00\u6761 episodic memory\u3002
1005
+ - \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
1006
+ - \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
1007
+ - scope \u6309\u5185\u5BB9\u6027\u8D28\u9009\uFF0C\u4E0D\u56FA\u5B9A\u4F18\u5148\u67D0\u4E00\u5C42\uFF1A
1008
+ - Space \u534F\u4F5C\u7EA6\u5B9A/\u56E2\u961F\u89C4\u5219 \u2192 scope=space\uFF08\u4EC5\u5F53\u5F53\u524D dialog \u5DF2\u7ED1\u5B9A space\uFF09
1009
+ - \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
1010
+ - \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
1011
+ - \u5F53\u524D\u4EFB\u52A1\u7684\u4E34\u65F6\u8FDB\u5EA6 \u2192 \u4E0D\u8C03\u7528\uFF0C\u8D70\u5BF9\u8BDD\u4E0A\u4E0B\u6587
1012
+ - \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`;
1013
+ var SELF_UPDATE_INSTRUCTIONS = `--- Agent \u81EA\u6211\u66F4\u65B0\u80FD\u529B ---
1014
+
1015
+ ## \u4F55\u65F6\u66F4\u65B0\u81EA\u5DF1
1016
+ - \u91CD\u8981\u51B3\u7B56/\u8FDB\u5EA6\u53D8\u5316 \u2192 updateDoc \u5199\u56DE\u72B6\u6001\u9875
1017
+ - \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
1018
+ - \u5C0F\u5E45\u4F53\u9A8C\u4F18\u5316 \u2192 updateSelf \u8C03\u6574 greeting / introduction / tags
1019
+
1020
+ ## \u66F4\u65B0\u539F\u5219
1021
+ - \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
1022
+ - \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
1023
+ - 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
1024
+ - \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
1025
+ - \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`;
1026
+ var GENERIC_AGENT_UPDATE_INSTRUCTIONS = `--- Agent \u7EF4\u62A4\u80FD\u529B ---
1027
+ \u4F60\u62E5\u6709 updateAgent \u6743\u9650\uFF0C\u53EF\u4EE5\u66F4\u65B0\u6307\u5B9A\u7684 Agent\u3002
1028
+
1029
+ ## \u4F55\u65F6\u66F4\u65B0\u522B\u7684 Agent
1030
+ - \u7528\u6237\u660E\u786E\u8981\u6C42\u4F60\u7EF4\u62A4\u3001\u4FEE\u590D\u6216\u6279\u91CF\u8C03\u6574\u53E6\u4E00\u4E2A Agent
1031
+ - \u4F60\u9700\u8981\u4FEE\u6539\u7684\u76EE\u6807\u4E0D\u662F\u5F53\u524D\u6B63\u5728\u8FD0\u884C\u7684\u81EA\u5DF1
1032
+
1033
+ ## \u66F4\u65B0\u539F\u5219
1034
+ - \u9ED8\u8BA4\u628A updateAgent \u5F53\u6210\u9AD8\u98CE\u9669\u7EF4\u62A4\u64CD\u4F5C\uFF0C\u4F18\u5148\u6700\u5C0F\u6539\u52A8
1035
+ - \u4FEE\u6539\u524D\u5148\u786E\u8BA4\u76EE\u6807 Agent \u662F\u5426\u6B63\u786E\uFF0C\u907F\u514D\u8BEF\u6539
1036
+ - \u5982\u679C\u5DE5\u5177\u8FD4\u56DE\u9700\u8981\u786E\u8BA4\uFF0C\u4E0D\u8981\u7ED5\u8FC7\u786E\u8BA4\u6D41\u7A0B`;
1037
+ 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`;
1038
+ var isBrowser = typeof window !== "undefined";
1039
+ var TOOL_GUIDED_SECTIONS = [
1040
+ {
1041
+ id: "agentOrchestration",
1042
+ triggerTools: ["callAgent", "runStreamingAgent"],
1043
+ build: (tools) => [
1044
+ AGENT_ORCHESTRATION_INSTRUCTIONS,
1045
+ tools.includes("runStreamingAgent") ? PAGE_BUILDER_HANDOFF_INSTRUCTIONS : ""
1046
+ ].filter(Boolean).join("\n\n")
1047
+ },
1048
+ { id: "menuUsage", triggerTools: ["ui_ask_choice"], build: () => MENU_USAGE_INSTRUCTIONS },
1049
+ {
1050
+ id: "webAccess",
1051
+ triggerTools: ["exa_search", "fetchWebpage", "browser_openSession", "read_x_post"],
1052
+ build: () => WEBPAGE_ACCESS_INSTRUCTIONS
1053
+ },
1054
+ {
1055
+ id: "knowledgeManagement",
1056
+ triggerTools: ["createDoc", "updateDoc", "read", "readDoc", "readPage"],
1057
+ build: () => KNOWLEDGE_MANAGEMENT_INSTRUCTIONS
1058
+ },
1059
+ { id: "memoryCapture", triggerTools: ["rememberMemory"], build: () => MEMORY_CAPTURE_INSTRUCTIONS },
1060
+ { id: "selfUpdate", triggerTools: ["updateSelf"], build: () => SELF_UPDATE_INSTRUCTIONS },
1061
+ { id: "genericAgentUpdate", triggerTools: ["updateAgent"], build: () => GENERIC_AGENT_UPDATE_INSTRUCTIONS }
1062
+ ];
1063
+ function resolveToolGuidedSections(agentTools) {
1064
+ const out = {};
1065
+ for (const section of TOOL_GUIDED_SECTIONS) {
1066
+ if (section.triggerTools.some((t) => agentTools.includes(t))) {
1067
+ out[section.id] = section.build(agentTools);
1068
+ } else {
1069
+ out[section.id] = "";
1070
+ }
1071
+ }
1072
+ return out;
1073
+ }
1074
+ var createContextSection = (title, description, content) => content ? `### ${title}
1075
+ ${description}
1076
+
1077
+ ${content} ` : "";
1078
+ var buildResponseGuidelines = (isMobile) => {
1079
+ if (isMobile) {
1080
+ return `-- - \u54CD\u5E94\u5C55\u793A\u6307\u5357-- -
1081
+ \u8BF7\u4E3A\u79FB\u52A8\u7AEF\u8FDB\u884C\u4F18\u5316\uFF1A
1082
+ - \u4F7F\u7528\u66F4\u77ED\u7684\u6BB5\u843D\u548C\u7B80\u6D01\u7684\u9879\u76EE\u7B26\u53F7\u5217\u8868\u3002
1083
+ - \u907F\u514D\u8FC7\u5BBD\u7684\u8868\u683C\u6216\u4EE3\u7801\u5757\uFF0C\u4EE5\u514D\u4EA7\u751F\u6A2A\u5411\u6EDA\u52A8\u3002
1084
+ - \u4F18\u5148\u91C7\u7528\u5782\u76F4\u6392\u5E03\uFF0C\u800C\u4E0D\u662F\u5DE6\u53F3\u5E76\u6392\u7684\u5E03\u5C40\u3002`;
1085
+ }
1086
+ return `-- - \u54CD\u5E94\u5C55\u793A\u6307\u5357-- -
1087
+ \u4F60\u7684\u56DE\u590D\u5C06\u663E\u793A\u5728\u5927\u5C4F\u5E55\u4E0A\u3002\u4F60\u53EF\u4EE5\uFF1A
1088
+ - \u63D0\u4F9B\u66F4\u4E30\u5BCC\u7684\u63A8\u7406\u8FC7\u7A0B\u8BF4\u660E\u548C\u66F4\u6709\u5C42\u6B21\u7684\u7ED3\u6784\u3002
1089
+ - \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`;
1090
+ };
1091
+ var buildReferenceMaterialsBlock = (contexts) => {
1092
+ const sections = [
1093
+ createContextSection(
1094
+ "\u8BF4\u660E\u6027\u6587\u6863\uFF08Instructional Documents\uFF09",
1095
+ "\uFF08\u6700\u9AD8\u4F18\u5148\u7EA7\uFF1A\u5177\u4F53\u89C4\u5219\u4E0E\u6D41\u7A0B\uFF09",
1096
+ contexts.botInstructionsContext
1097
+ ),
1098
+ createContextSection(
1099
+ "\u5F53\u524D\u8F93\u5165\u4E0A\u4E0B\u6587\uFF08Current Input Context\uFF09",
1100
+ "\uFF08\u9AD8\u4F18\u5148\u7EA7\uFF1A\u6765\u81EA\u7528\u6237\u672C\u6B21\u8F93\u5165\uFF09",
1101
+ contexts.currentInputContext
1102
+ ),
1103
+ createContextSection(
1104
+ "\u4F1A\u8BDD\u5386\u53F2\u5F15\u7528\uFF08Conversation History References\uFF09",
1105
+ "\uFF08\u4E2D\u7B49\u4F18\u5148\u7EA7\uFF1A\u6765\u81EA\u8FC7\u5F80\u6D88\u606F\uFF09",
1106
+ contexts.historyContext
1107
+ ),
1108
+ createContextSection(
1109
+ "\u77E5\u8BC6\u5E93\u6587\u6863\uFF08Knowledge Base Documents\uFF09",
1110
+ "\uFF08\u53C2\u8003\u4F18\u5148\u7EA7\uFF1A\u7528\u4E8E\u901A\u7528\u67E5\u9605\uFF09",
1111
+ contexts.botKnowledgeContext
1112
+ )
1113
+ ].filter(Boolean);
1114
+ if (sections.length === 0) {
1115
+ return "";
1116
+ }
1117
+ return [
1118
+ "--- \u53C2\u8003\u8D44\u6599 ---",
1119
+ CONTEXT_USAGE_INSTRUCTIONS,
1120
+ "",
1121
+ sections.join("\n\n")
1122
+ ].join("\n");
1123
+ };
1124
+ var buildEditingContextBlock = (contexts) => {
1125
+ if (!contexts.editingContext) return "";
1126
+ return [
1127
+ "--- \u5F53\u524D\u7F16\u8F91\u4E0A\u4E0B\u6587 ---",
1128
+ "\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",
1129
+ "",
1130
+ contexts.editingContext
1131
+ ].join("\n");
1132
+ };
1133
+ var buildAppWorkingMemoryBlock = (contexts) => {
1134
+ if (!contexts.appWorkingMemory) return "";
1135
+ return [
1136
+ "--- \u6700\u8FD1\u5E94\u7528\u5DE5\u4F5C\u8BB0\u5FC6 ---",
1137
+ "\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",
1138
+ "",
1139
+ contexts.appWorkingMemory
1140
+ ].join("\n");
1141
+ };
1142
+ var buildSpaceContextBlock = (contexts) => {
1143
+ if (!contexts.spaceContext) return "";
1144
+ return [
1145
+ contexts.spaceContext,
1146
+ "",
1147
+ "\u91CD\u8981\u6307\u4EE4 (Space Awareness)\uFF1A",
1148
+ "- \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",
1149
+ " - \u4F7F\u7528 `read` \u5DE5\u5177\u67E5\u9605\u666E\u901A\u6570\u636E\u8BB0\u5F55\u6216\u6570\u636E\u8868\u9879\u3002",
1150
+ "- \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",
1151
+ "",
1152
+ "\u8DE8\u7A7A\u95F4\u5BFC\u822A (Cross-Space Navigation)\uFF1A",
1153
+ "- \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",
1154
+ '- \u4F7F\u7528 `read({ dbKey: "space-{spaceId}" })` \u53EF\u83B7\u53D6\u6307\u5B9A Space \u7684\u5B8C\u6574\u6570\u636E\uFF0C\u5305\u62EC\uFF1A',
1155
+ " - categories: \u5206\u7C7B\u5B57\u5178\uFF0Ckey \u662F\u5206\u7C7B ID\uFF0Cvalue \u5305\u542B name \u548C order",
1156
+ " - contents: \u5185\u5BB9\u5B57\u5178\uFF0C\u6BCF\u9879\u5305\u542B contentKey\uFF08dbKey\uFF09\u3001title\u3001type\u3001categoryId"
1157
+ ].join("\n");
1158
+ };
1159
+ var buildSkillGuidanceBlock = (agentConfig) => {
1160
+ const recommendedSkillHints = Array.isArray(agentConfig.recommendedSkillHints) ? agentConfig.recommendedSkillHints.filter(Boolean) : [];
1161
+ const skillPromptPatches = Array.isArray(agentConfig.skillPromptPatches) ? agentConfig.skillPromptPatches.filter(Boolean) : [];
1162
+ if (recommendedSkillHints.length === 0 && skillPromptPatches.length === 0) {
1163
+ return "";
1164
+ }
1165
+ return buildSkillGuidancePromptBlock({
1166
+ title: "--- \u6280\u80FD\u63D0\u793A ---",
1167
+ recommendedSkillHints,
1168
+ skillPromptPatches
1169
+ });
1170
+ };
1171
+ var buildSystemPrompt = (options) => buildSystemPromptContext(options).content;
1172
+ var buildSystemPromptContext = (options) => {
1173
+ const {
1174
+ agentConfig,
1175
+ contexts = {},
1176
+ viewport,
1177
+ mobileBreakpoint = 768,
1178
+ now = /* @__PURE__ */ new Date(),
1179
+ timeZone
1180
+ } = options;
1181
+ const safeLanguage = options.language ?? (typeof navigator !== "undefined" ? navigator.language : "en");
1182
+ const { name, prompt: mainPrompt, dbKey, model } = agentConfig;
1183
+ const mappedLanguage = mapLanguage(safeLanguage);
1184
+ const identitySection = [
1185
+ "--- \u8EAB\u4EFD\u4FE1\u606F ---",
1186
+ name ? `\u540D\u79F0: ${name} ` : "",
1187
+ dbKey ? `ID: ${dbKey} ` : "",
1188
+ model ? `\u6A21\u578B: ${model} ` : "",
1189
+ mappedLanguage ? `\u56DE\u590D\u8BED\u8A00: ${mappedLanguage} ` : ""
1190
+ ].filter(Boolean).join("\n");
1191
+ const corePersonaSection = mainPrompt ? `-- - \u6838\u5FC3\u89D2\u8272\u4E0E\u4EFB\u52A1-- -
1192
+ ${mainPrompt}` : "";
1193
+ const agentTools = canonicalizeToolNames(agentConfig.tools ?? []);
1194
+ const toolSections = resolveToolGuidedSections(agentTools);
1195
+ const {
1196
+ startupProtocol,
1197
+ contextLayerContract,
1198
+ emailRegistrationWorkflow,
1199
+ webResearchToolPolicy
1200
+ } = buildRuntimeGuidanceBlocks(agentTools);
1201
+ const clarifyingSection = !mainPrompt ? CLARIFICATION_MODE_INSTRUCTIONS : "";
1202
+ const userGlobalPromptSection = contexts.userGlobalPrompt?.trim() ? `-- - \u7528\u6237\u5168\u5C40\u504F\u597D-- -
1203
+ ${contexts.userGlobalPrompt.trim()} ` : "";
1204
+ const fallbackViewportWidth = isBrowser && typeof window !== "undefined" ? window.innerWidth : 1440;
1205
+ const isMobile = (viewport?.width ?? fallbackViewportWidth) < mobileBreakpoint;
1206
+ const responseGuidelinesSection = buildResponseGuidelines(isMobile);
1207
+ const editingContextSection = buildEditingContextBlock(contexts);
1208
+ const appWorkingMemorySection = buildAppWorkingMemoryBlock(contexts);
1209
+ const spaceContextSection = buildSpaceContextBlock(contexts);
1210
+ const rawMemoryOverlay = asOptionalTrimmedString(contexts.memoryOverlay) ?? "";
1211
+ const memoryOverlaySection = rawMemoryOverlay ? rawMemoryOverlay + "\n\n" + MEMORY_USE_GUIDANCE : "";
1212
+ const skillGuidanceSection = buildSkillGuidanceBlock(agentConfig);
1213
+ const referenceMaterialsSection = buildReferenceMaterialsBlock(contexts);
1214
+ const dialogSummarySection = contexts.dialogSummary?.trim() ? `--- \u5386\u53F2\u5BF9\u8BDD\u6458\u8981 ---
1215
+ ${wrapHistoricalSummaryWithReplayGuard(contexts.dialogSummary)}` : "";
1216
+ const proactiveSummarySection = contexts.proactiveSummary?.trim() ? `--- \u9636\u6BB5\u5DE5\u4F5C\u6458\u8981 ---
1217
+ ${wrapHistoricalSummaryWithReplayGuard(contexts.proactiveSummary)}` : "";
1218
+ return compileContextLayers([
1219
+ { id: "identity", owner: "platform", cacheScope: "session", content: identitySection },
1220
+ { id: "startup-protocol", owner: "platform", cacheScope: "static", content: startupProtocol },
1221
+ { id: "core-persona", owner: "agent", cacheScope: "session", content: corePersonaSection },
1222
+ { id: "agent-orchestration", owner: "platform", cacheScope: "session", content: toolSections.agentOrchestration },
1223
+ { id: "web-access", owner: "platform", cacheScope: "session", content: toolSections.webAccess },
1224
+ { id: "menu-usage", owner: "platform", cacheScope: "session", content: toolSections.menuUsage },
1225
+ { id: "clarification-mode", owner: "platform", cacheScope: "session", content: clarifyingSection },
1226
+ { id: "knowledge-management", owner: "platform", cacheScope: "session", content: toolSections.knowledgeManagement },
1227
+ { id: "memory-capture", owner: "platform", cacheScope: "session", content: toolSections.memoryCapture },
1228
+ { id: "self-update", owner: "platform", cacheScope: "session", content: toolSections.selfUpdate },
1229
+ { id: "generic-agent-update", owner: "platform", cacheScope: "session", content: toolSections.genericAgentUpdate },
1230
+ { id: "context-layer-contract", owner: "platform", cacheScope: "static", content: contextLayerContract },
1231
+ {
1232
+ id: "email-registration-workflow",
1233
+ owner: "platform",
1234
+ cacheScope: "static",
1235
+ content: emailRegistrationWorkflow
1236
+ },
1237
+ {
1238
+ id: "web-research-tool-policy",
1239
+ owner: "platform",
1240
+ cacheScope: "static",
1241
+ content: webResearchToolPolicy
1242
+ },
1243
+ { id: "user-global-prompt", owner: "user", cacheScope: "session", content: userGlobalPromptSection },
1244
+ { id: "response-guidelines", owner: "platform", cacheScope: "session", content: responseGuidelinesSection },
1245
+ { id: "skill-guidance", owner: "runtime", cacheScope: "turn", content: skillGuidanceSection },
1246
+ { id: "space-context", owner: "runtime", cacheScope: "turn", content: spaceContextSection },
1247
+ { id: "reference-materials", owner: "agent", cacheScope: "turn", content: referenceMaterialsSection },
1248
+ { id: "memory-overlay", owner: "runtime", cacheScope: "turn", content: memoryOverlaySection },
1249
+ { id: "app-working-memory", owner: "runtime", cacheScope: "turn", content: appWorkingMemorySection },
1250
+ { id: "dialog-summary", owner: "runtime", cacheScope: "turn", content: dialogSummarySection },
1251
+ { id: "proactive-summary", owner: "runtime", cacheScope: "turn", content: proactiveSummarySection },
1252
+ { id: "editing-context", owner: "runtime", cacheScope: "turn", content: editingContextSection },
1253
+ {
1254
+ id: "current-time",
1255
+ owner: "platform",
1256
+ cacheScope: "turn",
1257
+ content: buildCurrentTimeBlock(now, timeZone)
1258
+ }
1259
+ ]);
1260
+ };
1261
+
1262
+ // packages/integrations/openai/providerBodyCompatibility.ts
1263
+ var normalizeChatCompletionsBodyForProvider = ({
1264
+ body,
1265
+ provider,
1266
+ model
1267
+ }) => {
1268
+ const nextBody = { ...body, model };
1269
+ const normalizedProvider = asTrimmedLowercaseString(provider);
1270
+ if (normalizedProvider === "fireworks" && isFireworksKimiModel(model)) {
1271
+ delete nextBody.reasoning;
1272
+ delete nextBody.reasoning_effort;
1273
+ }
1274
+ return nextBody;
1275
+ };
1276
+
1277
+ // packages/integrations/openai/generateOpenAIRequestBody.ts
1278
+ var isClaudeModel = (model) => !!model && (model.includes("claude") || model.includes("anthropic"));
1279
+ var applyClaudeCache = (content) => {
1280
+ if (typeof content === "string") {
1281
+ return [
1282
+ { type: "text", text: content, cache_control: { type: "ephemeral" } }
1283
+ ];
1284
+ }
1285
+ if (Array.isArray(content)) {
1286
+ const lastIdx = content.length - 1;
1287
+ return content.map((part, idx) => {
1288
+ if (idx === lastIdx && typeof part === "object") {
1289
+ return { ...part, cache_control: { type: "ephemeral" } };
1290
+ }
1291
+ return part;
1292
+ });
1293
+ }
1294
+ return content;
1295
+ };
1296
+ var prependPromptMessage = (messages, agentConfig, resolvedModel, language, contexts, prependSystemPrompt = true) => {
1297
+ if (!prependSystemPrompt) return messages;
1298
+ if (!contexts && !agentConfig.prompt) return messages;
1299
+ const promptContent = buildSystemPrompt({ agentConfig, language, contexts });
1300
+ if (!promptContent.trim()) return messages;
1301
+ const content = isClaudeModel(resolvedModel) ? applyClaudeCache(promptContent) : promptContent;
1302
+ const systemMessage = { role: "system", content };
1303
+ return [systemMessage, ...messages];
1304
+ };
1305
+ var shouldInjectLlamaCppThinkingToggle = (agentConfig) => {
1306
+ if (typeof agentConfig.enableThinking !== "boolean") return false;
1307
+ if (!isLoopbackUrl(agentConfig.customProviderUrl)) return false;
1308
+ return /qwen/i.test(agentConfig.model ?? "");
1309
+ };
1310
+ var shouldDisableMiMoThinking = (agentConfig) => {
1311
+ if (agentConfig.enableThinking === true) return false;
1312
+ return /xiaomimimo\.com/i.test(agentConfig.customProviderUrl ?? "") || (agentConfig.provider ?? "").toLowerCase() === "mimo";
1313
+ };
1314
+ var shouldDisableKimiThinking = (agentConfig, providerName, resolvedModel) => {
1315
+ if (agentConfig.enableThinking !== false) return false;
1316
+ if (providerName === "deepinfra") return isDeepInfraKimiModel(resolvedModel);
1317
+ if (providerName === "fireworks") return isFireworksKimiModel(resolvedModel);
1318
+ return false;
1319
+ };
1320
+ var normalizeChatCompletionsContent = (content) => {
1321
+ if (typeof content === "string" || Array.isArray(content)) return content;
1322
+ if (content == null) return null;
1323
+ return JSON.stringify(content);
1324
+ };
1325
+ var sanitizeChatCompletionsMessage = (message) => {
1326
+ const sanitized = {
1327
+ role: message.role,
1328
+ content: normalizeChatCompletionsContent(message.content)
1329
+ };
1330
+ const name = asOptionalTrimmedString(message.name);
1331
+ if (name) sanitized.name = name;
1332
+ const toolCallId = asOptionalTrimmedString(message.tool_call_id);
1333
+ if (toolCallId) sanitized.tool_call_id = toolCallId;
1334
+ if (Array.isArray(message.tool_calls)) {
1335
+ sanitized.tool_calls = message.tool_calls;
1336
+ }
1337
+ if (message.role === "assistant" && typeof message.reasoning_content === "string" && message.reasoning_content) {
1338
+ sanitized.reasoning_content = message.reasoning_content;
1339
+ }
1340
+ return sanitized;
1341
+ };
1342
+ var buildRequestBody = (options) => {
1343
+ const {
1344
+ model,
1345
+ messages,
1346
+ providerName,
1347
+ temperature,
1348
+ top_p,
1349
+ frequency_penalty,
1350
+ presence_penalty,
1351
+ max_tokens,
1352
+ reasoning_effort
1353
+ } = options;
1354
+ const cleanedMessages = messages.map(
1355
+ (message) => sanitizeChatCompletionsMessage(message)
1356
+ );
1357
+ const bodyData = {
1358
+ model,
1359
+ messages: cleanedMessages,
1360
+ stream: true
1361
+ };
1362
+ const usageRequestOptions = getUsageRequestOptions(providerName, {
1363
+ api: "chat-completions"
1364
+ });
1365
+ Object.assign(bodyData, usageRequestOptions);
1366
+ if (reasoning_effort && isModelSupportReasoningEffort(model)) {
1367
+ bodyData.reasoning_effort = reasoning_effort;
1368
+ }
1369
+ if (typeof temperature === "number") bodyData.temperature = temperature;
1370
+ if (typeof top_p === "number") bodyData.top_p = top_p;
1371
+ if (typeof frequency_penalty === "number")
1372
+ bodyData.frequency_penalty = frequency_penalty;
1373
+ if (typeof presence_penalty === "number")
1374
+ bodyData.presence_penalty = presence_penalty;
1375
+ if (typeof max_tokens === "number") bodyData.max_tokens = max_tokens;
1376
+ return bodyData;
1377
+ };
1378
+ var generateOpenAIRequestBody = (agentConfig, providerName, messages, contexts, stableMessages = [], prependSystemPrompt = true) => {
1379
+ const resolvedModel = providerName === "fireworks" ? resolveFireworksKimiModel(agentConfig.model) : agentConfig.model ?? "";
1380
+ let processedStable = [...stableMessages];
1381
+ if (isClaudeModel(resolvedModel) && processedStable.length > 0) {
1382
+ const lastStableIdx = processedStable.length - 1;
1383
+ processedStable[lastStableIdx] = {
1384
+ ...processedStable[lastStableIdx],
1385
+ content: applyClaudeCache(processedStable[lastStableIdx].content)
1386
+ };
1387
+ }
1388
+ const fullMessages = [...processedStable, ...messages];
1389
+ const messagesWithPrompt = prependPromptMessage(
1390
+ fullMessages,
1391
+ agentConfig,
1392
+ resolvedModel,
1393
+ typeof navigator !== "undefined" ? navigator.language : "en",
1394
+ contexts,
1395
+ prependSystemPrompt
1396
+ );
1397
+ const requestBody = buildRequestBody({
1398
+ model: resolvedModel,
1399
+ messages: messagesWithPrompt,
1400
+ providerName,
1401
+ temperature: agentConfig.temperature,
1402
+ top_p: agentConfig.top_p,
1403
+ frequency_penalty: agentConfig.frequency_penalty,
1404
+ presence_penalty: agentConfig.presence_penalty,
1405
+ max_tokens: agentConfig.max_tokens,
1406
+ reasoning_effort: agentConfig.reasoning_effort
1407
+ });
1408
+ if (shouldInjectLlamaCppThinkingToggle(agentConfig)) {
1409
+ requestBody.chat_template_kwargs = {
1410
+ ...requestBody.chat_template_kwargs ?? {},
1411
+ enable_thinking: agentConfig.enableThinking
1412
+ };
1413
+ }
1414
+ if (shouldDisableMiMoThinking(agentConfig)) {
1415
+ requestBody.thinking = { type: "disabled" };
1416
+ }
1417
+ if (shouldDisableKimiThinking(agentConfig, providerName, resolvedModel)) {
1418
+ requestBody.thinking = { type: "disabled" };
1419
+ requestBody.reasoning_effort = "none";
1420
+ requestBody.reasoning = { enabled: false };
1421
+ }
1422
+ return normalizeChatCompletionsBodyForProvider({
1423
+ body: requestBody,
1424
+ provider: providerName,
1425
+ model: requestBody.model
1426
+ });
1427
+ };
1428
+
1429
+ // packages/integrations/openai/generateResponseRequestBody.ts
1430
+ function generateResponseRequestBody(agentConfig, msgs, contexts, prependSystemPrompt = true) {
1431
+ const language = typeof navigator !== "undefined" && navigator.language ? navigator.language : "zh-CN";
1432
+ const input = convertMessagesToResponsesInput(msgs);
1433
+ const body = {
1434
+ model: agentConfig.model,
1435
+ input,
1436
+ stream: true,
1437
+ ...getUsageRequestOptions(agentConfig.provider, { api: "responses" })
1438
+ };
1439
+ if (prependSystemPrompt) {
1440
+ const promptContent = buildSystemPrompt({
1441
+ agentConfig,
1442
+ language,
1443
+ contexts
1444
+ });
1445
+ body.instructions = promptContent;
1446
+ }
1447
+ if (agentConfig.temperature !== void 0) {
1448
+ body.temperature = agentConfig.temperature;
1449
+ }
1450
+ if (agentConfig.top_p !== void 0) {
1451
+ body.top_p = agentConfig.top_p;
1452
+ }
1453
+ if (agentConfig.max_tokens !== void 0) {
1454
+ body.max_output_tokens = agentConfig.max_tokens;
1455
+ }
1456
+ if (agentConfig.max_tool_calls !== void 0) {
1457
+ body.max_tool_calls = agentConfig.max_tool_calls;
1458
+ }
1459
+ if (agentConfig.user !== void 0) {
1460
+ body.user = agentConfig.user;
1461
+ }
1462
+ if (agentConfig.include !== void 0) {
1463
+ body.include = agentConfig.include;
1464
+ }
1465
+ if (agentConfig.metadata !== void 0) {
1466
+ body.metadata = agentConfig.metadata;
1467
+ }
1468
+ return body;
1469
+ }
1470
+
1471
+ // packages/ai/llm/generateRequestBody.ts
1472
+ var IMAGE_OUTPUT_EXECUTION_PROMPT = [
1473
+ "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.",
1474
+ "When the user asks you to generate, edit, redraw, or return an image, you must return the image in this turn.",
1475
+ "Do not answer with only a textual description.",
1476
+ "Do not claim that you uploaded, attached, or sent an image unless the response actually includes image output.",
1477
+ "Only return text without an image when the user explicitly asks for analysis, recommendations, or explanation without generating an image."
1478
+ ].join(" ");
1479
+ var getImageOutputSettings = (agentConfig, provider) => {
1480
+ const modelName = agentConfig.model;
1481
+ if (!modelName) {
1482
+ return { shouldEnableImage: false, modelConfig: null };
1483
+ }
1484
+ try {
1485
+ const modelConfig = getModelConfig(provider, modelName);
1486
+ const hasImageOutput = !!modelConfig.hasImageOutput;
1487
+ const isExplicitlyDisabled = agentConfig.imageConfig?.enabled === false;
1488
+ return {
1489
+ shouldEnableImage: hasImageOutput && !isExplicitlyDisabled,
1490
+ modelConfig
1491
+ };
1492
+ } catch {
1493
+ return { shouldEnableImage: false, modelConfig: null };
1494
+ }
1495
+ };
1496
+ var withImageOutputPromptGuard = (agentConfig, shouldEnableImage) => {
1497
+ if (!shouldEnableImage) return agentConfig;
1498
+ const basePrompt = asTrimmedString(agentConfig.prompt);
1499
+ if (basePrompt.includes(IMAGE_OUTPUT_EXECUTION_PROMPT)) {
1500
+ return agentConfig;
1501
+ }
1502
+ return {
1503
+ ...agentConfig,
1504
+ prompt: basePrompt ? `${basePrompt}
1505
+
1506
+ ${IMAGE_OUTPUT_EXECUTION_PROMPT}` : IMAGE_OUTPUT_EXECUTION_PROMPT
1507
+ };
1508
+ };
1509
+ var applyImageConfigIfNeeded = (body, agentConfig, provider) => {
1510
+ const { shouldEnableImage, modelConfig } = getImageOutputSettings(
1511
+ agentConfig,
1512
+ provider
1513
+ );
1514
+ const agentImageCfg = agentConfig.imageConfig;
1515
+ if (!shouldEnableImage || !modelConfig) {
1516
+ return body;
1517
+ }
1518
+ const modalities = agentImageCfg?.forceModalities ?? modelConfig.defaultModalities ?? (modelConfig.requiresImageModalities ? ["image", "text"] : void 0);
1519
+ if (modalities && !body.modalities) {
1520
+ body.modalities = modalities;
1521
+ }
1522
+ if (!modelConfig.supportsImageConfig) {
1523
+ return body;
1524
+ }
1525
+ const aspectRatio = agentImageCfg?.aspectRatio;
1526
+ const imageSize = agentImageCfg?.imageSize;
1527
+ if (!aspectRatio && !imageSize) {
1528
+ return body;
1529
+ }
1530
+ body.image_config = {
1531
+ ...body.image_config ?? {},
1532
+ ...aspectRatio ? { aspect_ratio: aspectRatio } : {},
1533
+ ...imageSize ? { image_size: imageSize } : {}
1534
+ };
1535
+ return body;
1536
+ };
1537
+ var generateRequestBody = ({
1538
+ agentConfig,
1539
+ messages,
1540
+ contexts,
1541
+ stableMessages,
1542
+ prependSystemPrompt = true
1543
+ }) => {
1544
+ const provider = (agentConfig.provider || "").toLowerCase();
1545
+ const imageSettings = getImageOutputSettings(agentConfig, provider);
1546
+ const agentConfigForRequest = withImageOutputPromptGuard(
1547
+ agentConfig,
1548
+ imageSettings.shouldEnableImage
1549
+ );
1550
+ const clientWire = resolveClientWire(
1551
+ resolveAgentCallPlan(agentConfigForRequest, {})
1552
+ );
1553
+ if (clientWire === "responses") {
1554
+ return generateResponseRequestBody(
1555
+ agentConfigForRequest,
1556
+ [...stableMessages ?? [], ...messages],
1557
+ contexts,
1558
+ prependSystemPrompt
1559
+ );
1560
+ }
1561
+ const baseBody = generateOpenAIRequestBody(
1562
+ agentConfigForRequest,
1563
+ provider,
1564
+ messages,
1565
+ contexts,
1566
+ stableMessages,
1567
+ prependSystemPrompt
1568
+ );
1569
+ return applyImageConfigIfNeeded(baseBody, agentConfigForRequest, provider);
1570
+ };
1571
+
1572
+ // packages/ai/chat/serverProxyRetry.ts
1573
+ var RETRYABLE_SERVER_PROXY_STATUSES = /* @__PURE__ */ new Set([502, 503, 504]);
1574
+ var DEFAULT_SERVER_PROXY_RETRY_AFTER_MS = 1500;
1575
+ var MAX_SERVER_PROXY_RETRIES = 2;
1576
+ var MAX_STATUS_RETRIES = 1;
1577
+ var resolveServerProxyRetryAfterMs = (response) => parseRetryAfterHeaderMs(response.headers.get("Retry-After")) ?? DEFAULT_SERVER_PROXY_RETRY_AFTER_MS;
1578
+ var isRetryableServerProxyFetchError = (error) => {
1579
+ if (!error || isAbortError(error)) return false;
1580
+ const message = typeof error?.message === "string" ? error.message : String(error);
1581
+ return /ECONNREFUSED|ECONNRESET|EPIPE|socket hang up|network error|failed to fetch|fetch failed|connection closed|load failed|502|503|504/i.test(
1582
+ message
1583
+ );
1584
+ };
1585
+ var waitForServerProxyRetry = async (retryAfterMs, signal) => {
1586
+ if (retryAfterMs <= 0) return;
1587
+ if (signal?.aborted) {
1588
+ const abortError = new Error("Aborted");
1589
+ abortError.name = "AbortError";
1590
+ throw abortError;
1591
+ }
1592
+ await new Promise((resolve, reject) => {
1593
+ const onAbort = () => {
1594
+ clearTimeout(timeoutId);
1595
+ signal?.removeEventListener("abort", onAbort);
1596
+ const abortError = new Error("Aborted");
1597
+ abortError.name = "AbortError";
1598
+ reject(abortError);
1599
+ };
1600
+ const timeoutId = setTimeout(() => {
1601
+ signal?.removeEventListener("abort", onAbort);
1602
+ resolve();
1603
+ }, normalizeNonNegativeMs(retryAfterMs, DEFAULT_SERVER_PROXY_RETRY_AFTER_MS));
1604
+ signal?.addEventListener("abort", onAbort, { once: true });
1605
+ });
1606
+ };
1607
+ var performServerProxyFetchWithRetry = async ({
1608
+ execute,
1609
+ signal,
1610
+ logPrefix = "[fetchWithServerProxy]"
1611
+ }) => {
1612
+ for (let attempt = 0; attempt <= MAX_SERVER_PROXY_RETRIES; attempt += 1) {
1613
+ try {
1614
+ const response = await execute();
1615
+ if (attempt < MAX_STATUS_RETRIES && RETRYABLE_SERVER_PROXY_STATUSES.has(response.status)) {
1616
+ const retryAfterMs = resolveServerProxyRetryAfterMs(response);
1617
+ console.warn(
1618
+ `${logPrefix} \u68C0\u6D4B\u5230${response.status}\u72B6\u6001\uFF0C${retryAfterMs}ms\u540E\u91CD\u8BD5\u4E00\u6B21...`
1619
+ );
1620
+ await waitForServerProxyRetry(retryAfterMs, signal);
1621
+ continue;
1622
+ }
1623
+ return response;
1624
+ } catch (error) {
1625
+ if (attempt < MAX_SERVER_PROXY_RETRIES && isRetryableServerProxyFetchError(error)) {
1626
+ const retryDelay = (attempt + 1) * 1e3;
1627
+ console.warn(
1628
+ `${logPrefix} \u68C0\u6D4B\u5230\u7F51\u7EDC\u77AC\u65AD\uFF0C${retryDelay}ms\u540E\u91CD\u8BD5(\u7B2C${attempt + 1}\u6B21)...`,
1629
+ error
1630
+ );
1631
+ await waitForServerProxyRetry(retryDelay, signal);
1632
+ continue;
1633
+ }
1634
+ throw error;
1635
+ }
1636
+ }
1637
+ throw new Error("server proxy retry exhausted unexpectedly");
1638
+ };
1639
+
1640
+ // packages/ai/chat/resolveDirectRequestApiKey.ts
1641
+ 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";
1642
+ var DirectApiKeyResolutionError = class extends Error {
1643
+ constructor(message = DIRECT_API_KEY_UNAVAILABLE_MESSAGE) {
1644
+ super(message);
1645
+ this.name = "DirectApiKeyResolutionError";
1646
+ }
1647
+ };
1648
+ var createDirectCredentialBroker = createFileCredentialBroker;
1649
+ function readNonEmpty(value) {
1650
+ return asTrimmedString(value);
1651
+ }
1652
+ async function resolveDirectRequestApiKey(agentConfig, options) {
1653
+ const rawKey = readNonEmpty(agentConfig.apiKey);
1654
+ if (rawKey) return rawKey;
1655
+ const credentialRef = readNonEmpty(agentConfig.credentialRef);
1656
+ if (!credentialRef) return void 0;
1657
+ const factory = options?.brokerFactory ?? createDirectCredentialBroker;
1658
+ const broker = factory();
1659
+ const local = await safeBrokerGet(broker, credentialRef);
1660
+ if (local) return local;
1661
+ if (agentConfig.credentialSynced && options?.syncFetcher) {
1662
+ const synced = await options.syncFetcher(credentialRef);
1663
+ const trimmed = asTrimmedString(synced);
1664
+ if (trimmed) {
1665
+ try {
1666
+ await broker.put(credentialRef, trimmed);
1667
+ } catch {
1668
+ }
1669
+ return trimmed;
1670
+ }
1671
+ }
1672
+ throw new DirectApiKeyResolutionError();
1673
+ }
1674
+ async function safeBrokerGet(broker, ref) {
1675
+ try {
1676
+ return asTrimmedString(await broker.get(ref)) || null;
1677
+ } catch {
1678
+ return null;
1679
+ }
1680
+ }
1681
+
1682
+ // packages/ai/chat/fetchUtils.ts
1683
+ var buildProxyPayload = (bodyData, api, agentConfig, dialogId) => {
1684
+ const apiSource = agentConfig.apiSource === "custom" || agentConfig.apiSource === "cli" ? agentConfig.apiSource : void 0;
1685
+ const provider = bodyData.provider || agentConfig.provider || (apiSource === "custom" ? "custom" : void 0);
1686
+ const apiKey = asOptionalTrimmedString(agentConfig.apiKey);
1687
+ return {
1688
+ ...bodyData,
1689
+ url: api,
1690
+ provider,
1691
+ agentKey: agentConfig.dbKey,
1692
+ ...asOptionalTrimmedString(dialogId) ? { dialogId: asOptionalTrimmedString(dialogId) } : {},
1693
+ ...apiSource ? { apiSource } : {},
1694
+ ...agentConfig.apiKeyHeader ? { apiKeyHeader: agentConfig.apiKeyHeader } : {},
1695
+ KEY: apiKey
1696
+ };
1697
+ };
1698
+ var fetchDirectly = async (params) => {
1699
+ const { api, agentConfig, bodyData, signal, currentServer, token } = params;
1700
+ try {
1701
+ const apiKey = await resolveDirectRequestApiKey(agentConfig, {
1702
+ syncFetcher: currentServer && token ? (ref) => fetchServerSyncedCredential({ currentServer, authToken: token }, ref) : void 0
1703
+ });
1704
+ const authHeaders = buildProviderAuthHeaders({
1705
+ endpoint: api,
1706
+ apiKey: apiKey ?? "",
1707
+ apiKeyHeader: agentConfig.apiKeyHeader
1708
+ });
1709
+ return await fetch(api, {
1710
+ method: "POST",
1711
+ headers: {
1712
+ "Content-Type": "application/json",
1713
+ ...authHeaders,
1714
+ ...api.includes("openrouter.ai") ? {
1715
+ "HTTP-Referer": "https://nolo.chat",
1716
+ "X-Title": "nolo"
1717
+ } : {}
1718
+ },
1719
+ body: JSON.stringify(bodyData),
1720
+ signal
1721
+ // 可选参数,直接传递
1722
+ });
1723
+ } catch (error) {
1724
+ console.error("[fetchDirectly] \u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25:", error);
1725
+ throw error;
1726
+ }
1727
+ };
1728
+ var fetchWithServerProxy = async ({
1729
+ currentServer,
1730
+ api,
1731
+ bodyData,
1732
+ agentConfig,
1733
+ token,
1734
+ signal,
1735
+ dialogId
1736
+ }) => {
1737
+ try {
1738
+ const payload = buildProxyPayload(bodyData, api, agentConfig, dialogId);
1739
+ return await performServerProxyFetchWithRetry({
1740
+ signal,
1741
+ execute: () => fetch(`${currentServer}${API_ENDPOINTS.CHAT}`, {
1742
+ method: "POST",
1743
+ headers: {
1744
+ "Content-Type": "application/json",
1745
+ Authorization: `Bearer ${token}`
1746
+ // 使用 Authorization 头传递 token
1747
+ },
1748
+ body: JSON.stringify(payload),
1749
+ signal
1750
+ })
1751
+ });
1752
+ } catch (error) {
1753
+ console.error("[fetchWithServerProxy] \u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25:", error);
1754
+ throw error;
1755
+ }
1756
+ };
1757
+ var formatFriendlyNetworkErrorMessage = (error) => {
1758
+ if (typeof window !== "undefined" && typeof navigator !== "undefined" && navigator.onLine === false) {
1759
+ return "\u7F51\u7EDC\u8FDE\u63A5\u5DF2\u65AD\u5F00\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5\u540E\u91CD\u8BD5";
1760
+ }
1761
+ const rawMessage = toErrorMessage(error);
1762
+ if (/failed to fetch|networkerror|network error|econnrefused|econnreset|socket hang up/i.test(
1763
+ rawMessage
1764
+ )) {
1765
+ return "\u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5\u6216\u4EE3\u7406/VPN\u8BBE\u7F6E";
1766
+ }
1767
+ return rawMessage;
1768
+ };
1769
+ var performFetchRequest = async (params) => {
1770
+ try {
1771
+ const planConfig = {
1772
+ ...params.agentConfig,
1773
+ provider: params.bodyData.provider || params.agentConfig.provider
1774
+ };
1775
+ return resolveAgentCallPlan(planConfig, {}).transport === "server-proxy" ? await fetchWithServerProxy(params) : await fetchDirectly(params);
1776
+ } catch (error) {
1777
+ console.error("[performFetchRequest] \u8BF7\u6C42\u8FC7\u7A0B\u4E2D\u53D1\u751F\u9519\u8BEF:", error);
1778
+ const friendlyMsg = formatFriendlyNetworkErrorMessage(error);
1779
+ throw new Error(
1780
+ friendlyMsg.startsWith("\u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25") ? friendlyMsg : `\u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25: ${friendlyMsg}`
1781
+ );
1782
+ }
1783
+ };
1784
+
1785
+ // packages/create/editor/transforms/slateToText.ts
1786
+ function getNodeText(node) {
1787
+ if (node.text) {
1788
+ return node.text;
1789
+ }
1790
+ if (node.children && Array.isArray(node.children)) {
1791
+ return node.children.map(getNodeText).join("\n");
1792
+ }
1793
+ return "";
1794
+ }
1795
+ function slateToText(nodes) {
1796
+ if (!nodes || nodes.length === 0) {
1797
+ return "";
1798
+ }
1799
+ return nodes.map(getNodeText).join("\n\n");
1800
+ }
1801
+
1802
+ // packages/ai/context/buildReferenceContext.ts
1803
+ var MAX_META_TEXT_LENGTH = 80;
1804
+ var DIALOG_REFERENCE_MESSAGE_LIMIT = 20;
1805
+ var DIALOG_REFERENCE_SNIPPET_CHARS = 1200;
1806
+ var DIALOG_HANDOFF_SNIPPET_CHARS = 360;
1807
+ var truncateMetaText = (value, max = MAX_META_TEXT_LENGTH) => {
1808
+ if (!value) return "";
1809
+ if (value.length <= max) return value;
1810
+ return `${value.slice(0, max - 3)}...`;
1811
+ };
1812
+ var readSafe = async (dispatch, dbKey) => {
1813
+ try {
1814
+ return await dispatch(read({
1815
+ dbKey
1816
+ })).unwrap();
1817
+ } catch {
1818
+ return null;
1819
+ }
1820
+ };
1821
+ var buildMentionMetaMap = async (slateData, dispatch) => {
1822
+ const metaMap = /* @__PURE__ */ new Map();
1823
+ const mentions = extractCategorizedMentions(slateData);
1824
+ if (!mentions) return metaMap;
1825
+ const pageEntries = await Promise.all(
1826
+ (mentions.pages || []).map(async (pageId) => {
1827
+ const pageData = await readSafe(dispatch, pageId);
1828
+ if (!pageData) {
1829
+ return [`page:${pageId}`, { displayType: "page", metaParts: [] }];
1830
+ }
1831
+ if (pageData.type === "dialog" /* DIALOG */) {
1832
+ const agentCount = Array.isArray(pageData.cybots) ? pageData.cybots.length : 0;
1833
+ return [
1834
+ `page:${pageId}`,
1835
+ {
1836
+ displayType: "dialog",
1837
+ title: pageData.title,
1838
+ metaParts: [
1839
+ `agents=${agentCount}`,
1840
+ `updated=${pageData.updatedAt || pageData.updated_at || pageData.updated || "Unknown"}`
1841
+ ]
1842
+ }
1843
+ ];
1844
+ }
1845
+ const tags = pageData.tags && pageData.tags.length > 0 ? pageData.tags.slice(0, 5).join(", ") : "";
1846
+ return [
1847
+ `page:${pageId}`,
1848
+ {
1849
+ displayType: "page",
1850
+ title: pageData.title,
1851
+ metaParts: [
1852
+ pageData.spaceId ? `space=${pageData.spaceId}` : "",
1853
+ tags ? `tags=${tags}` : "",
1854
+ `updated=${pageData.updatedAt || pageData.updated_at || pageData.updated || "Unknown"}`
1855
+ ].filter(Boolean)
1856
+ }
1857
+ ];
1858
+ })
1859
+ );
1860
+ pageEntries.forEach((entry) => metaMap.set(entry[0], entry[1]));
1861
+ const agentEntries = await Promise.all(
1862
+ (mentions.agents || []).map(async (agentId) => {
1863
+ const agentData = await readSafe(dispatch, agentId);
1864
+ if (!agentData) {
1865
+ return [`agent:${agentId}`, { displayType: "agent", metaParts: [] }];
1866
+ }
1867
+ const desc = truncateMetaText(
1868
+ agentData.description || agentData.introduction || ""
1869
+ );
1870
+ return [
1871
+ `agent:${agentId}`,
1872
+ {
1873
+ displayType: "agent",
1874
+ title: agentData.name,
1875
+ metaParts: [
1876
+ `public=${agentData.isPublic ? "yes" : "no"}`,
1877
+ desc ? `desc=${desc}` : ""
1878
+ ].filter(Boolean)
1879
+ }
1880
+ ];
1881
+ })
1882
+ );
1883
+ agentEntries.forEach((entry) => metaMap.set(entry[0], entry[1]));
1884
+ const spaceEntries = await Promise.all(
1885
+ (mentions.spaces || []).map(async (spaceId) => {
1886
+ const spaceKey = createSpaceKey.space(spaceId);
1887
+ const spaceData = await readSafe(dispatch, spaceKey);
1888
+ if (!spaceData) {
1889
+ return [`space:${spaceId}`, { displayType: "space", metaParts: [] }];
1890
+ }
1891
+ const desc = truncateMetaText(spaceData.description || "");
1892
+ const categoriesCount = Object.keys(spaceData.categories || {}).length;
1893
+ const contentsCount = Object.keys(spaceData.contents || {}).length;
1894
+ return [
1895
+ `space:${spaceId}`,
1896
+ {
1897
+ displayType: "space",
1898
+ title: spaceData.name,
1899
+ metaParts: [
1900
+ desc ? `desc=${desc}` : "",
1901
+ `categories=${categoriesCount}`,
1902
+ `contents=${contentsCount}`
1903
+ ].filter(Boolean)
1904
+ }
1905
+ ];
1906
+ })
1907
+ );
1908
+ spaceEntries.forEach((entry) => metaMap.set(entry[0], entry[1]));
1909
+ return metaMap;
1910
+ };
1911
+ var buildInlineMention = (node, metaMap) => {
1912
+ const resourceType = node.resourceType || "unknown";
1913
+ const resourceId = node.resourceId || "unknown";
1914
+ const key = `${resourceType}:${resourceId}`;
1915
+ const meta = metaMap.get(key);
1916
+ const label = meta?.title || node.label || resourceId || "mention";
1917
+ const displayType = meta?.displayType || resourceType;
1918
+ const metaParts = meta?.metaParts ?? [];
1919
+ const idPart = resourceType === "tool" ? `tool=${resourceId}` : `dbkey=${resourceId}`;
1920
+ const metaSuffix = metaParts.length ? ` | ${metaParts.join(" | ")}` : "";
1921
+ return `@${label}(${displayType} | ${idPart}${metaSuffix})`;
1922
+ };
1923
+ var clipReferenceText = (value, max) => {
1924
+ const raw = typeof value === "string" ? value : value == null ? "" : JSON.stringify(value);
1925
+ return clipMultilineText(raw, max);
1926
+ };
1927
+ var fetchDialogReference = async (dbKey, refContent, dispatch) => {
1928
+ const dialogConfig = refContent;
1929
+ const dialogTitle = dialogConfig.title || `Untitled Dialog (${dbKey})`;
1930
+ const dialogId = extractCustomId(dbKey) || dbKey.replace(/^dialog-/, "");
1931
+ const checkpoint = dialogConfig.runtimeCheckpoint || null;
1932
+ const summary = asTrimmedString(dialogConfig.summary);
1933
+ const proactiveSummary = asTrimmedString(dialogConfig.proactiveSummary);
1934
+ const messages = await dispatch(
1935
+ async (_dispatch, getState, { db }) => {
1936
+ const state = getState();
1937
+ const { currentToken: token, remoteServers } = getRuntimeServerContext(state);
1938
+ return await fetchAndCacheMessages({
1939
+ db,
1940
+ dialogId,
1941
+ limit: DIALOG_REFERENCE_MESSAGE_LIMIT,
1942
+ token,
1943
+ remoteServers: remoteServers.length > 0 ? remoteServers : void 0
1944
+ });
1945
+ }
1946
+ );
1947
+ const sortedMessages = [...messages].reverse();
1948
+ const formatContent = (content) => clipReferenceText(content, DIALOG_REFERENCE_SNIPPET_CHARS);
1949
+ const transcript = sortedMessages.map((msg, index) => {
1950
+ const toolLine = msg.toolName ? ` tool=${msg.toolName}` : "";
1951
+ const agentLine = msg.cybotKey ? ` agent=${msg.cybotKey}` : "";
1952
+ const createdLine = msg.createdAt ? ` at=${msg.createdAt}` : "";
1953
+ return [
1954
+ `### Message ${index + 1}: ${msg.role || "unknown"} id=${msg.id || "unknown"}${toolLine}${agentLine}${createdLine}`,
1955
+ formatContent(msg.content) || "[empty]"
1956
+ ].join("\n");
1957
+ }).join("\n\n");
1958
+ const checkpointLines = [];
1959
+ if (checkpoint && typeof checkpoint === "object") {
1960
+ if (checkpoint.status) checkpointLines.push(`- status: ${checkpoint.status}`);
1961
+ if (checkpoint.lastUserInput) checkpointLines.push(`- lastUserInput: ${formatContent(checkpoint.lastUserInput)}`);
1962
+ if (checkpoint.lastAssistantText) checkpointLines.push(`- lastAssistantText: ${formatContent(checkpoint.lastAssistantText)}`);
1963
+ if (Array.isArray(checkpoint.lastToolNames) && checkpoint.lastToolNames.length) {
1964
+ checkpointLines.push(`- lastToolNames: ${checkpoint.lastToolNames.join(", ")}`);
1965
+ }
1966
+ if (Array.isArray(checkpoint.availableToolNames) && checkpoint.availableToolNames.length) {
1967
+ checkpointLines.push(`- availableToolNames: ${checkpoint.availableToolNames.join(", ")}`);
1968
+ }
1969
+ }
1970
+ const recentToolEvidence = sortedMessages.filter((msg) => msg.role === "tool" || msg.toolName).slice(-3).map((msg) => {
1971
+ const label = msg.toolName ? `${msg.toolName}` : "tool";
1972
+ return `- ${label} id=${msg.id || "unknown"}: ${clipReferenceText(msg.content, DIALOG_HANDOFF_SNIPPET_CHARS) || "[empty]"}`;
1973
+ });
1974
+ const handoffLines = [
1975
+ `- Use this when continuing work, transferring to another Agent, comparing with the current task, or preparing a document/plan from the prior discussion.`,
1976
+ `- Current state source: ${checkpointLines.length ? "Runtime Checkpoint" : "summaries and recent transcript"}.`,
1977
+ summary ? `- Compressed background: passive summary is available below; treat it as lossy, not original wording.` : "",
1978
+ proactiveSummary ? `- Recent work: proactive summary is available below; use it for current direction, not exact evidence.` : "",
1979
+ recentToolEvidence.length ? `- Recent tool evidence:
1980
+ ${recentToolEvidence.join("\n")}` : `- Recent tool evidence: none loaded in the latest ${DIALOG_REFERENCE_MESSAGE_LIMIT} messages.`,
1981
+ `- 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}.`
1982
+ ].filter(Boolean);
1983
+ const referenceBody = [
1984
+ `Conversation Reference:`,
1985
+ `DB Key: ${dbKey}`,
1986
+ `Title: ${dialogTitle}`,
1987
+ `Status: ${dialogConfig.status || "unknown"}`,
1988
+ `Loaded Recent Messages: ${sortedMessages.length}`,
1989
+ `Conversation Handoff:
1990
+ ${handoffLines.join("\n")}`,
1991
+ checkpointLines.length ? `Runtime Checkpoint:
1992
+ ${checkpointLines.join("\n")}` : "",
1993
+ summary ? `Passive Summary (compressed history, not original wording):
1994
+ ${wrapHistoricalSummaryWithReplayGuard(summary)}` : "",
1995
+ proactiveSummary ? `Proactive Summary (recent work summary, not original wording):
1996
+ ${wrapHistoricalSummaryWithReplayGuard(proactiveSummary)}` : "",
1997
+ `Recent Transcript (original message excerpts, oldest to newest):
1998
+ ${transcript || "[no recent messages loaded]"}`,
1999
+ [
2000
+ `Coverage Note: This reference intentionally loads only the latest ${DIALOG_REFERENCE_MESSAGE_LIMIT} messages plus summaries/checkpoint to control token load.`,
2001
+ `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.`
2002
+ ].join("\n")
2003
+ ].filter(Boolean).join("\n\n");
2004
+ const tokenEstimate = estimateTokenCount(referenceBody);
2005
+ return `${referenceBody}
2006
+
2007
+ Token Load Estimate: ${tokenEstimate} tokens for this conversation reference.
2008
+ ---
2009
+
2010
+ `;
2011
+ };
2012
+ var fetchTableReference = async (dbKey, refContent, dispatch) => {
2013
+ const tableMeta = refContent;
2014
+ const title = tableMeta.displayName || tableMeta.description || `Untitled Table (${dbKey})`;
2015
+ const { markdown: tableMd } = await dispatch(
2016
+ async (_dispatch, getState, { db }) => {
2017
+ const state = getState();
2018
+ const { currentToken: token, remoteServers } = getRuntimeServerContext(state);
2019
+ return await fetchAndSerializeTable(tableMeta, db, {
2020
+ token,
2021
+ remoteServers
2022
+ });
2023
+ }
2024
+ );
2025
+ const tags = tableMeta.tags?.length ? tableMeta.tags.join(", ") : "None";
2026
+ const description = tableMeta.description || "No description provided.";
2027
+ return `Reference Item (Table):
2028
+ DB Key: ${dbKey}
2029
+ Title: ${title}
2030
+ Description: ${description}
2031
+ Tags: ${tags}
2032
+ Content (Markdown Table):
2033
+
2034
+ ${tableMd}
2035
+ ---
2036
+
2037
+ `;
2038
+ };
2039
+ var fetchSlateReference = async (dbKey, refContent, dispatch, options) => {
2040
+ if (!refContent?.slateData) return null;
2041
+ const title = refContent.title || `Untitled (${dbKey})`;
2042
+ let contentString;
2043
+ let contentType;
2044
+ const inlineMentionMeta = options.inlineMentionMeta ?? options.format === "simplified_markdown";
2045
+ switch (options.format) {
2046
+ case "text":
2047
+ contentType = "Plain Text";
2048
+ contentString = slateToText(refContent.slateData);
2049
+ break;
2050
+ case "simplified_markdown":
2051
+ contentType = "Simplified Markdown";
2052
+ if (inlineMentionMeta) {
2053
+ const metaMap = await buildMentionMetaMap(refContent.slateData, dispatch);
2054
+ contentString = slateToSimplifiedMarkdown(refContent.slateData, {
2055
+ mentionResolver: (node) => buildInlineMention(node, metaMap)
2056
+ });
2057
+ } else {
2058
+ contentString = slateToSimplifiedMarkdown(refContent.slateData);
2059
+ }
2060
+ break;
2061
+ case "json":
2062
+ default:
2063
+ contentType = "Slate JSON";
2064
+ contentString = JSON.stringify(refContent.slateData, null, 2);
2065
+ break;
2066
+ }
2067
+ if (!contentString || typeof contentString === "string" && !contentString.trim() || contentString === "[]") {
2068
+ return null;
2069
+ }
2070
+ const tags = (refContent.tags || []).length > 0 ? refContent.tags.join(", ") : "None";
2071
+ const createdAt = refContent.created || "Unknown Creation Date";
2072
+ const updatedAt = refContent.updated || "Unknown Update Date";
2073
+ return `Reference Item:
2074
+ DB Key: ${dbKey}
2075
+ Title: ${title}
2076
+ Content (${contentType}):
2077
+ ${contentString}
2078
+ Tags: ${tags}
2079
+ Created At: ${createdAt}
2080
+ Updated At: ${updatedAt}
2081
+ ---
2082
+
2083
+ `;
2084
+ };
2085
+ var fetchReferenceContents = async (references, dispatch, options = { format: "simplified_markdown" }) => {
2086
+ const result = /* @__PURE__ */ new Map();
2087
+ if (!references || references.length === 0) return result;
2088
+ const referencePromises = references.map(async (dbKey) => {
2089
+ try {
2090
+ const hasPreloaded = options.preloaded?.has(dbKey);
2091
+ const refContent = hasPreloaded ? options.preloaded?.get(dbKey) : await dispatch(read({
2092
+ dbKey
2093
+ })).unwrap();
2094
+ if (!refContent) return null;
2095
+ let formatted = null;
2096
+ if (refContent.type === "dialog" /* DIALOG */) {
2097
+ formatted = await fetchDialogReference(dbKey, refContent, dispatch);
2098
+ } else if (refContent.type === "table" /* TABLE */) {
2099
+ formatted = await fetchTableReference(dbKey, refContent, dispatch);
2100
+ } else {
2101
+ formatted = await fetchSlateReference(dbKey, refContent, dispatch, options);
2102
+ }
2103
+ if (formatted) return [dbKey, formatted];
2104
+ return null;
2105
+ } catch (error) {
2106
+ console.error(`Error fetching reference ${dbKey}:`, error);
2107
+ return null;
2108
+ }
2109
+ });
2110
+ const resolved = await Promise.all(referencePromises);
2111
+ resolved.forEach((item) => {
2112
+ if (item) result.set(item[0], item[1]);
2113
+ });
2114
+ return result;
2115
+ };
2116
+
2117
+ export {
2118
+ fetchReferenceContents,
2119
+ mergeReferences,
2120
+ resolveReferenceAssets,
2121
+ resolveToolsFromKeys,
2122
+ resolveClientWire,
2123
+ resolveAgentCallPlan,
2124
+ generateRequestBody,
2125
+ performServerProxyFetchWithRetry,
2126
+ performFetchRequest
2127
+ };