nolo-cli 0.6.1 → 0.8.0-alpha.10

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 (175) hide show
  1. package/_executeModel-CPDNUUQV.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-OSUMJMZM.js +323 -0
  6. package/agentEmailCommands-OQTJIPQU.js +621 -0
  7. package/agentListCommands-FATQEUYT.js +219 -0
  8. package/agentMachineCommands-6LZWF4GL.js +421 -0
  9. package/agentPullCommand-O2MTUAFR.js +122 -0
  10. package/agentRecordCommands-TIHFU65Z.js +89 -0
  11. package/agentRunCommand-R64Y3HCH.js +102 -0
  12. package/agentRunControl-K4VKNEHF.js +57 -0
  13. package/agentRuntimeLocal-6PIWAHLQ.js +99 -0
  14. package/agentSlice-TP4VARJF.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-2MALU52L.js +51 -0
  20. package/chunk-2TPUKEU7.js +1078 -0
  21. package/chunk-3ASDTTEI.js +1774 -0
  22. package/chunk-3EUW3WEO.js +8 -0
  23. package/chunk-3LY4F7SV.js +9293 -0
  24. package/chunk-4CQLVGRV.js +50 -0
  25. package/chunk-4IJYA27C.js +342 -0
  26. package/chunk-4SN6J65J.js +38 -0
  27. package/chunk-4VNS5WPM.js +42 -0
  28. package/chunk-572EKYLF.js +792 -0
  29. package/chunk-5MIDPSSK.js +206 -0
  30. package/chunk-5MMAK75Q.js +15 -0
  31. package/chunk-5VV37AT4.js +222 -0
  32. package/chunk-63W5N6P3.js +150 -0
  33. package/chunk-6A5EF6IR.js +929 -0
  34. package/chunk-6HYVJV7B.js +102 -0
  35. package/chunk-6P2WX5IA.js +3631 -0
  36. package/chunk-6WD3OOJS.js +20 -0
  37. package/chunk-ATNTHIZI.js +13 -0
  38. package/chunk-AUGHVUFE.js +69 -0
  39. package/chunk-AVMKZHBC.js +85 -0
  40. package/chunk-AZPCASRE.js +36 -0
  41. package/chunk-BNMT7YY5.js +34 -0
  42. package/chunk-BR2WP3DF.js +548 -0
  43. package/chunk-BSTNFPHD.js +231 -0
  44. package/chunk-BU4OPIXC.js +171 -0
  45. package/chunk-CF2WZF4N.js +134 -0
  46. package/chunk-CF7PE763.js +10 -0
  47. package/chunk-CKOJQDKR.js +198 -0
  48. package/chunk-CM54RSSA.js +206 -0
  49. package/chunk-CWMSB67P.js +34 -0
  50. package/chunk-DA2OEKS6.js +27 -0
  51. package/chunk-DFFIZ25G.js +30 -0
  52. package/chunk-DWLEOOGR.js +8 -0
  53. package/chunk-DZ3XJVET.js +231 -0
  54. package/chunk-EHLHSX7R.js +1433 -0
  55. package/chunk-ELRRLDWI.js +478 -0
  56. package/chunk-EYEEHCU4.js +3066 -0
  57. package/chunk-FQZWM5YX.js +628 -0
  58. package/chunk-G3SUCT4W.js +8 -0
  59. package/chunk-G5H7RNFL.js +807 -0
  60. package/chunk-GAKEBQD6.js +30 -0
  61. package/chunk-GBRG75BQ.js +86 -0
  62. package/chunk-H2RMRZJE.js +113 -0
  63. package/chunk-H33743XH.js +25 -0
  64. package/chunk-HD63YREL.js +19 -0
  65. package/chunk-HEIIIZBX.js +104 -0
  66. package/chunk-HNMXYYJR.js +12 -0
  67. package/chunk-HOMYP7GZ.js +2152 -0
  68. package/chunk-HZFOMJRA.js +4300 -0
  69. package/chunk-IAXBCTTE.js +175 -0
  70. package/chunk-IDZTNRP2.js +85 -0
  71. package/chunk-IHHA5Y2S.js +9013 -0
  72. package/chunk-ISNCLGUZ.js +146 -0
  73. package/chunk-IYQV26RA.js +138 -0
  74. package/chunk-J4576WMJ.js +91 -0
  75. package/chunk-JBTJAPUF.js +35 -0
  76. package/chunk-JZPBVBIY.js +94 -0
  77. package/chunk-KQHGZWSV.js +63 -0
  78. package/chunk-KUG52IAP.js +8 -0
  79. package/chunk-KX6YBIHG.js +8 -0
  80. package/chunk-LCBAMY2M.js +60 -0
  81. package/chunk-LM25IZBJ.js +902 -0
  82. package/chunk-LM6IYQ3F.js +16 -0
  83. package/chunk-M76ECQRD.js +13658 -0
  84. package/chunk-MRC4Q34M.js +188 -0
  85. package/chunk-NEMRK4EK.js +944 -0
  86. package/chunk-NXZGF7F7.js +2878 -0
  87. package/chunk-OF5H3QWS.js +300 -0
  88. package/chunk-OLZBQWZU.js +6 -0
  89. package/chunk-OOYVBFM7.js +191 -0
  90. package/chunk-OWOHNGCN.js +50 -0
  91. package/chunk-PN7AFLOK.js +3401 -0
  92. package/chunk-POCFIDGQ.js +562 -0
  93. package/chunk-Q6WACBKB.js +1949 -0
  94. package/chunk-QFV2OAIM.js +421 -0
  95. package/chunk-QJ6V2NIN.js +1447 -0
  96. package/chunk-QSJ3HFEF.js +8 -0
  97. package/chunk-QUWDTOUP.js +190 -0
  98. package/chunk-QYXLLLGL.js +4519 -0
  99. package/chunk-ROWQEJRP.js +139 -0
  100. package/chunk-S7Z2HMCN.js +25 -0
  101. package/chunk-TDIQFT2F.js +301 -0
  102. package/chunk-TILFE6LV.js +381 -0
  103. package/chunk-TKOUBWBO.js +24674 -0
  104. package/chunk-TYH5JE6N.js +27158 -0
  105. package/chunk-U4TRT5V4.js +246 -0
  106. package/chunk-U6VC4MU4.js +8 -0
  107. package/chunk-UAD2WT54.js +64 -0
  108. package/chunk-USZMK5UT.js +105 -0
  109. package/chunk-VEJLAVTC.js +2052 -0
  110. package/chunk-VF4K2QE6.js +21 -0
  111. package/chunk-VHBWHNVT.js +59 -0
  112. package/chunk-VIDPVFP3.js +20 -0
  113. package/chunk-VP4WJWKW.js +8882 -0
  114. package/chunk-VQ2AJRGD.js +148 -0
  115. package/chunk-W4NVOSFF.js +37 -0
  116. package/chunk-WWC7I6TA.js +8 -0
  117. package/chunk-X7W4TNB4.js +1550 -0
  118. package/chunk-XDVAYP26.js +537 -0
  119. package/chunk-XKIMRZO2.js +221 -0
  120. package/chunk-Y5GCAMGP.js +9 -0
  121. package/chunk-YWPXYBY7.js +360 -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-KLKS2HGU.js +864 -0
  127. package/createDialogAction-Z33JMBF5.js +52 -0
  128. package/createPageAction-AQVNOAAI.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-W5PD6MZU.js +59 -0
  133. package/dialogSlice-RBJYVSAR.js +146 -0
  134. package/docCreateCommands-MM34S4Z3.js +215 -0
  135. package/docDeleteCommands-JJTU722V.js +176 -0
  136. package/docReadCommands-GLYDMCTU.js +129 -0
  137. package/docStore-5TYME4DO.js +96 -0
  138. package/docUpdateCommands-ZCGQ7URR.js +313 -0
  139. package/fetchMessages-JOCYIFKL.js +16 -0
  140. package/getPricing-PWPJ6MNV.js +30 -0
  141. package/handleSendMessageAction-KA2MRW6E.js +183 -0
  142. package/index.js +184 -112254
  143. package/lib-FYYBQIXS.js +19839 -0
  144. package/localDialogRead-D3BELSTF.js +26 -0
  145. package/localFirstLog-DHNOY2NA.js +19 -0
  146. package/localRuntimeAuthority-TEGCOWX4.js +471 -0
  147. package/localRuntimeDb-LGDF6FQP.js +12 -0
  148. package/machineCommands-ZB5WUSPF.js +774 -0
  149. package/machineInfo-M6KB6HZN.js +10 -0
  150. package/machineWsRunDispatch-GWCAPPCM.js +105 -0
  151. package/memoryCommands-O4MIPIWQ.js +476 -0
  152. package/models-XLEOET3E.js +9 -0
  153. package/offlineMarxistsAgentCommand-BCPJITJL.js +242 -0
  154. package/package.json +3 -25
  155. package/read-RIJCIVKX.js +17 -0
  156. package/readDocTool-GZD2N3LO.js +16 -0
  157. package/readlineWorkspace-FEDY44AA.js +5357 -0
  158. package/removeDialogAgentAction-CXLST3N6.js +72 -0
  159. package/runAgentClientLoop-W4NKE64V.js +288 -0
  160. package/runtimeDoctorCommands-LRHLPDRC.js +289 -0
  161. package/setDialogExtraReferencesAction-LP6VYGU7.js +59 -0
  162. package/setPrimaryDialogAgentAction-D3GGH23T.js +79 -0
  163. package/settingSlice-J4I3Z5H7.js +198 -0
  164. package/skillSummaryMarker-42HKSXYY.js +9 -0
  165. package/slateToRenderMarkdown-Y5IYN73U.js +7 -0
  166. package/slateUtils-2M7MUTWX.js +19 -0
  167. package/spaceCommands-LC4FDAKE.js +450 -0
  168. package/spaceSlice-32XOGBEF.js +145 -0
  169. package/streamAgentChatTurn-YQW32AQH.js +4503 -0
  170. package/tableCommands-GOFP7QKA.js +1286 -0
  171. package/toolApiClient-QI3YBNWB.js +26 -0
  172. package/tools-XGTFRYD7.js +83 -0
  173. package/understanding-HCSFPE7R.js +318 -0
  174. package/updateCommands-VOSPKXFF.js +31 -0
  175. package/updateDialogTitleAction-4LHQDNHQ.js +185 -0
@@ -0,0 +1,2152 @@
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-TYH5JE6N.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-TKOUBWBO.js";
30
+ import {
31
+ fetchServerSyncedCredential
32
+ } from "./chunk-POCFIDGQ.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
+ const dynamicLayers = compiledLayers.slice(stablePrefixLayers.length);
877
+ const dynamicContent = dynamicLayers.map((layer) => layer.content).join("\n\n");
878
+ return {
879
+ content: compiledLayers.map((layer) => layer.content).join("\n\n"),
880
+ stablePrefixContent,
881
+ dynamicContent,
882
+ layers: compiledLayers,
883
+ cacheProfile: {
884
+ stablePrefixHash: createHash("sha256").update(stablePrefixContent).digest("hex"),
885
+ stablePrefixLayerIds: stablePrefixLayers.map((layer) => layer.id),
886
+ stablePrefixCharCount: stablePrefixContent.length,
887
+ stablePrefixEstimatedTokens: estimateContextTokens(stablePrefixContent)
888
+ }
889
+ };
890
+ };
891
+
892
+ // packages/ai/agent/currentTimeContext.ts
893
+ var pad2 = (value) => String(value).padStart(2, "0");
894
+ var resolveDefaultTimeZone = () => {
895
+ try {
896
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
897
+ } catch {
898
+ return "UTC";
899
+ }
900
+ };
901
+ var partsForTimeZone = (date, timeZone) => {
902
+ const parts = new Intl.DateTimeFormat("en-US", {
903
+ timeZone,
904
+ year: "numeric",
905
+ month: "2-digit",
906
+ day: "2-digit",
907
+ hour: "2-digit",
908
+ minute: "2-digit",
909
+ second: "2-digit",
910
+ hour12: false
911
+ }).formatToParts(date);
912
+ return Object.fromEntries(
913
+ parts.filter((part) => part.type !== "literal").map((part) => [part.type, part.value])
914
+ );
915
+ };
916
+ var zonedDateTime = (date, timeZone) => {
917
+ const parts = partsForTimeZone(date, timeZone);
918
+ return [
919
+ `${parts.year}-${parts.month}-${parts.day}`,
920
+ `${parts.hour}:${parts.minute}:${parts.second}`
921
+ ].join(" ");
922
+ };
923
+ var timeZoneOffset = (date, timeZone) => {
924
+ const parts = partsForTimeZone(date, timeZone);
925
+ const utcMs = Date.UTC(
926
+ Number(parts.year),
927
+ Number(parts.month) - 1,
928
+ Number(parts.day),
929
+ Number(parts.hour),
930
+ Number(parts.minute),
931
+ Number(parts.second)
932
+ );
933
+ const offsetMinutes = Math.round((utcMs - date.getTime()) / 6e4);
934
+ const sign = offsetMinutes >= 0 ? "+" : "-";
935
+ const absolute = Math.abs(offsetMinutes);
936
+ return `UTC${sign}${pad2(Math.floor(absolute / 60))}:${pad2(absolute % 60)}`;
937
+ };
938
+ var buildCurrentTimeBlock = (now = /* @__PURE__ */ new Date(), timeZone = resolveDefaultTimeZone()) => [
939
+ "--- \u5F53\u524D\u65F6\u95F4 ---",
940
+ `\u5F53\u524D\u65E5\u671F: ${zonedDateTime(now, timeZone).slice(0, 10)}`,
941
+ `\u5F53\u524D\u672C\u5730\u65F6\u95F4: ${zonedDateTime(now, timeZone).slice(0, 16)}`,
942
+ // HH:MM only, no seconds
943
+ `\u672C\u5730\u65F6\u533A: ${timeZone} / ${timeZoneOffset(now, timeZone)}`,
944
+ `UTC \u65F6\u95F4: ${now.toISOString().slice(0, 16)}`,
945
+ // YYYY-MM-DDTHH:MM only
946
+ "\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",
947
+ "\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"
948
+ ].join("\n");
949
+
950
+ // packages/ai/agent/buildSystemPrompt.ts
951
+ var CONTEXT_USAGE_INSTRUCTIONS = `\u53C2\u8003\u8D44\u6599\u4F7F\u7528\u8BF4\u660E\uFF1A
952
+ - \u4E0B\u65B9\u63D0\u4F9B\u7684\u8D44\u6599\u662F\u4F60\u7684\u4E3B\u8981\u6743\u5A01\u4FE1\u606F\u6765\u6E90\u3002
953
+ - \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
954
+ - \u4F7F\u7528\u5176\u4E2D\u7684\u4E8B\u5B9E\u3001\u6570\u636E\u548C\u540D\u79F0\u65F6\uFF0C\u8981\u4FDD\u6301\u7CBE\u51C6\u3002
955
+ - \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
956
+ - \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
957
+ - \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`;
958
+ var MENU_USAGE_INSTRUCTIONS = `--- \u4EA4\u4E92\u8BF4\u660E ---
959
+ \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
960
+
961
+ ## \u4F55\u65F6\u8C03\u7528 ui_ask_choice
962
+ \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
963
+ 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
964
+ 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
965
+ 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
966
+
967
+ ## \u8C03\u7528 ui_ask_choice \u7684\u89C4\u8303
968
+ - \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
969
+ - \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
970
+ - \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
971
+ - \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
972
+ - \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`;
973
+ var WEBPAGE_ACCESS_INSTRUCTIONS = `--- \u7F51\u9875\u8BBF\u95EE\u80FD\u529B (Web Access) ---
974
+ \u83B7\u53D6\u5916\u90E8\u4FE1\u606F\u65F6\u7531\u7B80\u5165\u7E41\uFF1A
975
+ 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
976
+ 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
977
+ 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
978
+ 3. \u9700\u767B\u5F55/\u586B\u8868/\u591A\u6B65\u4EA4\u4E92 \u2192 browser_openSession\uFF08openSession \u62FF ID \u2192 typeText/click/readContent\uFF09\u3002
979
+ 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`;
980
+ var AGENT_ORCHESTRATION_INSTRUCTIONS = `--- Agent \u7F16\u6392\u4E0E\u534F\u4F5C ---
981
+ \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
982
+
983
+ 1\uFF09\u5B50 Agent \u534F\u4F5C
984
+ - \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
985
+ - \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
986
+ - \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
987
+ - 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
988
+ - \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
989
+ - \u5F53\u7528\u6237\u9700\u8981\u591A\u89C6\u89D2\u5206\u6790\u6216\u8FA9\u8BBA\u65F6\uFF0C\u4F60\u53EF\u4EE5\uFF1A
990
+ - \u5148\u7528 callAgent \u4F9D\u6B21\u8BE2\u95EE\u591A\u4E2A Agent \u5BF9\u540C\u4E00\u95EE\u9898\u7684\u770B\u6CD5\uFF1B
991
+ - \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
992
+
993
+ 2\uFF09\u5DE5\u4F5C\u6D41 / Workflow \u5DE5\u5177
994
+ - \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
995
+ - \u8C03\u7528\u5DE5\u4F5C\u6D41\u5DE5\u5177\u65F6\uFF0C\u4F60\u8D1F\u8D23\uFF1A
996
+ - \u6E05\u695A\u63CF\u8FF0\u76EE\u6807\u548C\u7EA6\u675F\uFF1B
997
+ - \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
998
+ - \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
999
+
1000
+ 3\uFF09\u5371\u9669 / \u4E0D\u53EF\u9006\u64CD\u4F5C
1001
+ - \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
1002
+ - \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`;
1003
+ var KNOWLEDGE_MANAGEMENT_INSTRUCTIONS = `--- \u77E5\u8BC6\u7BA1\u7406 ---
1004
+ \u4E09\u5C42\u77E5\u8BC6\uFF1A
1005
+ 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
1006
+ 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
1007
+ \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
1008
+ \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`;
1009
+ var MEMORY_CAPTURE_INSTRUCTIONS = `--- \u957F\u671F\u8BB0\u5FC6 ---
1010
+ \u4F60\u53EF\u7528 rememberMemory \u628A\u503C\u5F97\u957F\u671F\u4FDD\u7559\u7684\u4FE1\u606F\u5199\u6210\u4E00\u6761 episodic memory\u3002
1011
+ - \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
1012
+ - \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
1013
+ - scope \u6309\u5185\u5BB9\u6027\u8D28\u9009\uFF0C\u4E0D\u56FA\u5B9A\u4F18\u5148\u67D0\u4E00\u5C42\uFF1A
1014
+ - Space \u534F\u4F5C\u7EA6\u5B9A/\u56E2\u961F\u89C4\u5219 \u2192 scope=space\uFF08\u4EC5\u5F53\u5F53\u524D dialog \u5DF2\u7ED1\u5B9A space\uFF09
1015
+ - \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
1016
+ - \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
1017
+ - \u5F53\u524D\u4EFB\u52A1\u7684\u4E34\u65F6\u8FDB\u5EA6 \u2192 \u4E0D\u8C03\u7528\uFF0C\u8D70\u5BF9\u8BDD\u4E0A\u4E0B\u6587
1018
+ - \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`;
1019
+ var SELF_UPDATE_INSTRUCTIONS = `--- Agent \u81EA\u6211\u66F4\u65B0\u80FD\u529B ---
1020
+
1021
+ ## \u4F55\u65F6\u66F4\u65B0\u81EA\u5DF1
1022
+ - \u91CD\u8981\u51B3\u7B56/\u8FDB\u5EA6\u53D8\u5316 \u2192 updateDoc \u5199\u56DE\u72B6\u6001\u9875
1023
+ - \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
1024
+ - \u5C0F\u5E45\u4F53\u9A8C\u4F18\u5316 \u2192 updateSelf \u8C03\u6574 greeting / introduction / tags
1025
+
1026
+ ## \u66F4\u65B0\u539F\u5219
1027
+ - \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
1028
+ - \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
1029
+ - 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
1030
+ - \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
1031
+ - \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`;
1032
+ var GENERIC_AGENT_UPDATE_INSTRUCTIONS = `--- Agent \u7EF4\u62A4\u80FD\u529B ---
1033
+ \u4F60\u62E5\u6709 updateAgent \u6743\u9650\uFF0C\u53EF\u4EE5\u66F4\u65B0\u6307\u5B9A\u7684 Agent\u3002
1034
+
1035
+ ## \u4F55\u65F6\u66F4\u65B0\u522B\u7684 Agent
1036
+ - \u7528\u6237\u660E\u786E\u8981\u6C42\u4F60\u7EF4\u62A4\u3001\u4FEE\u590D\u6216\u6279\u91CF\u8C03\u6574\u53E6\u4E00\u4E2A Agent
1037
+ - \u4F60\u9700\u8981\u4FEE\u6539\u7684\u76EE\u6807\u4E0D\u662F\u5F53\u524D\u6B63\u5728\u8FD0\u884C\u7684\u81EA\u5DF1
1038
+
1039
+ ## \u66F4\u65B0\u539F\u5219
1040
+ - \u9ED8\u8BA4\u628A updateAgent \u5F53\u6210\u9AD8\u98CE\u9669\u7EF4\u62A4\u64CD\u4F5C\uFF0C\u4F18\u5148\u6700\u5C0F\u6539\u52A8
1041
+ - \u4FEE\u6539\u524D\u5148\u786E\u8BA4\u76EE\u6807 Agent \u662F\u5426\u6B63\u786E\uFF0C\u907F\u514D\u8BEF\u6539
1042
+ - \u5982\u679C\u5DE5\u5177\u8FD4\u56DE\u9700\u8981\u786E\u8BA4\uFF0C\u4E0D\u8981\u7ED5\u8FC7\u786E\u8BA4\u6D41\u7A0B`;
1043
+ 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`;
1044
+ var isBrowser = typeof window !== "undefined";
1045
+ var TOOL_GUIDED_SECTIONS = [
1046
+ {
1047
+ id: "agentOrchestration",
1048
+ triggerTools: ["callAgent", "runStreamingAgent"],
1049
+ build: (tools) => [
1050
+ AGENT_ORCHESTRATION_INSTRUCTIONS,
1051
+ tools.includes("runStreamingAgent") ? PAGE_BUILDER_HANDOFF_INSTRUCTIONS : ""
1052
+ ].filter(Boolean).join("\n\n")
1053
+ },
1054
+ { id: "menuUsage", triggerTools: ["ui_ask_choice"], build: () => MENU_USAGE_INSTRUCTIONS },
1055
+ {
1056
+ id: "webAccess",
1057
+ triggerTools: ["exa_search", "fetchWebpage", "browser_openSession", "read_x_post"],
1058
+ build: () => WEBPAGE_ACCESS_INSTRUCTIONS
1059
+ },
1060
+ {
1061
+ id: "knowledgeManagement",
1062
+ triggerTools: ["createDoc", "updateDoc", "read", "readDoc", "readPage"],
1063
+ build: () => KNOWLEDGE_MANAGEMENT_INSTRUCTIONS
1064
+ },
1065
+ { id: "memoryCapture", triggerTools: ["rememberMemory"], build: () => MEMORY_CAPTURE_INSTRUCTIONS },
1066
+ { id: "selfUpdate", triggerTools: ["updateSelf"], build: () => SELF_UPDATE_INSTRUCTIONS },
1067
+ { id: "genericAgentUpdate", triggerTools: ["updateAgent"], build: () => GENERIC_AGENT_UPDATE_INSTRUCTIONS }
1068
+ ];
1069
+ function resolveToolGuidedSections(agentTools) {
1070
+ const out = {};
1071
+ for (const section of TOOL_GUIDED_SECTIONS) {
1072
+ if (section.triggerTools.some((t) => agentTools.includes(t))) {
1073
+ out[section.id] = section.build(agentTools);
1074
+ } else {
1075
+ out[section.id] = "";
1076
+ }
1077
+ }
1078
+ return out;
1079
+ }
1080
+ var createContextSection = (title, description, content) => content ? `### ${title}
1081
+ ${description}
1082
+
1083
+ ${content} ` : "";
1084
+ var buildResponseGuidelines = (isMobile) => {
1085
+ if (isMobile) {
1086
+ return `-- - \u54CD\u5E94\u5C55\u793A\u6307\u5357-- -
1087
+ \u8BF7\u4E3A\u79FB\u52A8\u7AEF\u8FDB\u884C\u4F18\u5316\uFF1A
1088
+ - \u4F7F\u7528\u66F4\u77ED\u7684\u6BB5\u843D\u548C\u7B80\u6D01\u7684\u9879\u76EE\u7B26\u53F7\u5217\u8868\u3002
1089
+ - \u907F\u514D\u8FC7\u5BBD\u7684\u8868\u683C\u6216\u4EE3\u7801\u5757\uFF0C\u4EE5\u514D\u4EA7\u751F\u6A2A\u5411\u6EDA\u52A8\u3002
1090
+ - \u4F18\u5148\u91C7\u7528\u5782\u76F4\u6392\u5E03\uFF0C\u800C\u4E0D\u662F\u5DE6\u53F3\u5E76\u6392\u7684\u5E03\u5C40\u3002`;
1091
+ }
1092
+ return `-- - \u54CD\u5E94\u5C55\u793A\u6307\u5357-- -
1093
+ \u4F60\u7684\u56DE\u590D\u5C06\u663E\u793A\u5728\u5927\u5C4F\u5E55\u4E0A\u3002\u4F60\u53EF\u4EE5\uFF1A
1094
+ - \u63D0\u4F9B\u66F4\u4E30\u5BCC\u7684\u63A8\u7406\u8FC7\u7A0B\u8BF4\u660E\u548C\u66F4\u6709\u5C42\u6B21\u7684\u7ED3\u6784\u3002
1095
+ - \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`;
1096
+ };
1097
+ var buildReferenceMaterialsBlock = (contexts) => {
1098
+ const sections = [
1099
+ createContextSection(
1100
+ "\u8BF4\u660E\u6027\u6587\u6863\uFF08Instructional Documents\uFF09",
1101
+ "\uFF08\u6700\u9AD8\u4F18\u5148\u7EA7\uFF1A\u5177\u4F53\u89C4\u5219\u4E0E\u6D41\u7A0B\uFF09",
1102
+ contexts.botInstructionsContext
1103
+ ),
1104
+ createContextSection(
1105
+ "\u5F53\u524D\u8F93\u5165\u4E0A\u4E0B\u6587\uFF08Current Input Context\uFF09",
1106
+ "\uFF08\u9AD8\u4F18\u5148\u7EA7\uFF1A\u6765\u81EA\u7528\u6237\u672C\u6B21\u8F93\u5165\uFF09",
1107
+ contexts.currentInputContext
1108
+ ),
1109
+ createContextSection(
1110
+ "\u4F1A\u8BDD\u5386\u53F2\u5F15\u7528\uFF08Conversation History References\uFF09",
1111
+ "\uFF08\u4E2D\u7B49\u4F18\u5148\u7EA7\uFF1A\u6765\u81EA\u8FC7\u5F80\u6D88\u606F\uFF09",
1112
+ contexts.historyContext
1113
+ ),
1114
+ createContextSection(
1115
+ "\u77E5\u8BC6\u5E93\u6587\u6863\uFF08Knowledge Base Documents\uFF09",
1116
+ "\uFF08\u53C2\u8003\u4F18\u5148\u7EA7\uFF1A\u7528\u4E8E\u901A\u7528\u67E5\u9605\uFF09",
1117
+ contexts.botKnowledgeContext
1118
+ )
1119
+ ].filter(Boolean);
1120
+ if (sections.length === 0) {
1121
+ return "";
1122
+ }
1123
+ return [
1124
+ "--- \u53C2\u8003\u8D44\u6599 ---",
1125
+ CONTEXT_USAGE_INSTRUCTIONS,
1126
+ "",
1127
+ sections.join("\n\n")
1128
+ ].join("\n");
1129
+ };
1130
+ var buildEditingContextBlock = (contexts) => {
1131
+ if (!contexts.editingContext) return "";
1132
+ return [
1133
+ "--- \u5F53\u524D\u7F16\u8F91\u4E0A\u4E0B\u6587 ---",
1134
+ "\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",
1135
+ "",
1136
+ contexts.editingContext
1137
+ ].join("\n");
1138
+ };
1139
+ var buildAppWorkingMemoryBlock = (contexts) => {
1140
+ if (!contexts.appWorkingMemory) return "";
1141
+ return [
1142
+ "--- \u6700\u8FD1\u5E94\u7528\u5DE5\u4F5C\u8BB0\u5FC6 ---",
1143
+ "\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",
1144
+ "",
1145
+ contexts.appWorkingMemory
1146
+ ].join("\n");
1147
+ };
1148
+ var buildSpaceContextBlock = (contexts) => {
1149
+ if (!contexts.spaceContext) return "";
1150
+ return [
1151
+ contexts.spaceContext,
1152
+ "",
1153
+ "\u91CD\u8981\u6307\u4EE4 (Space Awareness)\uFF1A",
1154
+ "- \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",
1155
+ " - \u4F7F\u7528 `read` \u5DE5\u5177\u67E5\u9605\u666E\u901A\u6570\u636E\u8BB0\u5F55\u6216\u6570\u636E\u8868\u9879\u3002",
1156
+ "- \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",
1157
+ "",
1158
+ "\u8DE8\u7A7A\u95F4\u5BFC\u822A (Cross-Space Navigation)\uFF1A",
1159
+ "- \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",
1160
+ '- \u4F7F\u7528 `read({ dbKey: "space-{spaceId}" })` \u53EF\u83B7\u53D6\u6307\u5B9A Space \u7684\u5B8C\u6574\u6570\u636E\uFF0C\u5305\u62EC\uFF1A',
1161
+ " - categories: \u5206\u7C7B\u5B57\u5178\uFF0Ckey \u662F\u5206\u7C7B ID\uFF0Cvalue \u5305\u542B name \u548C order",
1162
+ " - contents: \u5185\u5BB9\u5B57\u5178\uFF0C\u6BCF\u9879\u5305\u542B contentKey\uFF08dbKey\uFF09\u3001title\u3001type\u3001categoryId"
1163
+ ].join("\n");
1164
+ };
1165
+ var buildSkillGuidanceBlock = (agentConfig) => {
1166
+ const recommendedSkillHints = Array.isArray(agentConfig.recommendedSkillHints) ? agentConfig.recommendedSkillHints.filter(Boolean) : [];
1167
+ const skillPromptPatches = Array.isArray(agentConfig.skillPromptPatches) ? agentConfig.skillPromptPatches.filter(Boolean) : [];
1168
+ if (recommendedSkillHints.length === 0 && skillPromptPatches.length === 0) {
1169
+ return "";
1170
+ }
1171
+ return buildSkillGuidancePromptBlock({
1172
+ title: "--- \u6280\u80FD\u63D0\u793A ---",
1173
+ recommendedSkillHints,
1174
+ skillPromptPatches
1175
+ });
1176
+ };
1177
+ var buildSystemPrompt = (options) => buildSystemPromptContext(options).content;
1178
+ var buildSystemPromptContext = (options) => {
1179
+ const {
1180
+ agentConfig,
1181
+ contexts = {},
1182
+ viewport,
1183
+ mobileBreakpoint = 768,
1184
+ now = /* @__PURE__ */ new Date(),
1185
+ timeZone
1186
+ } = options;
1187
+ const safeLanguage = options.language ?? (typeof navigator !== "undefined" ? navigator.language : "en");
1188
+ const { name, prompt: mainPrompt, dbKey, model } = agentConfig;
1189
+ const mappedLanguage = mapLanguage(safeLanguage);
1190
+ const identitySection = [
1191
+ "--- \u8EAB\u4EFD\u4FE1\u606F ---",
1192
+ name ? `\u540D\u79F0: ${name} ` : "",
1193
+ dbKey ? `ID: ${dbKey} ` : "",
1194
+ model ? `\u6A21\u578B: ${model} ` : "",
1195
+ mappedLanguage ? `\u56DE\u590D\u8BED\u8A00: ${mappedLanguage} ` : ""
1196
+ ].filter(Boolean).join("\n");
1197
+ const corePersonaSection = mainPrompt ? `-- - \u6838\u5FC3\u89D2\u8272\u4E0E\u4EFB\u52A1-- -
1198
+ ${mainPrompt}` : "";
1199
+ const agentTools = canonicalizeToolNames(agentConfig.tools ?? []);
1200
+ const toolSections = resolveToolGuidedSections(agentTools);
1201
+ const {
1202
+ startupProtocol,
1203
+ contextLayerContract,
1204
+ emailRegistrationWorkflow,
1205
+ webResearchToolPolicy
1206
+ } = buildRuntimeGuidanceBlocks(agentTools);
1207
+ const clarifyingSection = !mainPrompt ? CLARIFICATION_MODE_INSTRUCTIONS : "";
1208
+ const userGlobalPromptSection = contexts.userGlobalPrompt?.trim() ? `-- - \u7528\u6237\u5168\u5C40\u504F\u597D-- -
1209
+ ${contexts.userGlobalPrompt.trim()} ` : "";
1210
+ const fallbackViewportWidth = isBrowser && typeof window !== "undefined" ? window.innerWidth : 1440;
1211
+ const isMobile = (viewport?.width ?? fallbackViewportWidth) < mobileBreakpoint;
1212
+ const responseGuidelinesSection = buildResponseGuidelines(isMobile);
1213
+ const editingContextSection = buildEditingContextBlock(contexts);
1214
+ const appWorkingMemorySection = buildAppWorkingMemoryBlock(contexts);
1215
+ const spaceContextSection = buildSpaceContextBlock(contexts);
1216
+ const rawMemoryOverlay = asOptionalTrimmedString(contexts.memoryOverlay) ?? "";
1217
+ const memoryOverlaySection = rawMemoryOverlay ? rawMemoryOverlay + "\n\n" + MEMORY_USE_GUIDANCE : "";
1218
+ const skillGuidanceSection = buildSkillGuidanceBlock(agentConfig);
1219
+ const referenceMaterialsSection = buildReferenceMaterialsBlock(contexts);
1220
+ const dialogSummarySection = contexts.dialogSummary?.trim() ? `--- \u5386\u53F2\u5BF9\u8BDD\u6458\u8981 ---
1221
+ ${wrapHistoricalSummaryWithReplayGuard(contexts.dialogSummary)}` : "";
1222
+ const proactiveSummarySection = contexts.proactiveSummary?.trim() ? `--- \u9636\u6BB5\u5DE5\u4F5C\u6458\u8981 ---
1223
+ ${wrapHistoricalSummaryWithReplayGuard(contexts.proactiveSummary)}` : "";
1224
+ return compileContextLayers([
1225
+ { id: "identity", owner: "platform", cacheScope: "session", content: identitySection },
1226
+ { id: "startup-protocol", owner: "platform", cacheScope: "static", content: startupProtocol },
1227
+ { id: "core-persona", owner: "agent", cacheScope: "session", content: corePersonaSection },
1228
+ { id: "agent-orchestration", owner: "platform", cacheScope: "session", content: toolSections.agentOrchestration },
1229
+ { id: "web-access", owner: "platform", cacheScope: "session", content: toolSections.webAccess },
1230
+ { id: "menu-usage", owner: "platform", cacheScope: "session", content: toolSections.menuUsage },
1231
+ { id: "clarification-mode", owner: "platform", cacheScope: "session", content: clarifyingSection },
1232
+ { id: "knowledge-management", owner: "platform", cacheScope: "session", content: toolSections.knowledgeManagement },
1233
+ { id: "memory-capture", owner: "platform", cacheScope: "session", content: toolSections.memoryCapture },
1234
+ { id: "self-update", owner: "platform", cacheScope: "session", content: toolSections.selfUpdate },
1235
+ { id: "generic-agent-update", owner: "platform", cacheScope: "session", content: toolSections.genericAgentUpdate },
1236
+ { id: "context-layer-contract", owner: "platform", cacheScope: "static", content: contextLayerContract },
1237
+ {
1238
+ id: "email-registration-workflow",
1239
+ owner: "platform",
1240
+ cacheScope: "static",
1241
+ content: emailRegistrationWorkflow
1242
+ },
1243
+ {
1244
+ id: "web-research-tool-policy",
1245
+ owner: "platform",
1246
+ cacheScope: "static",
1247
+ content: webResearchToolPolicy
1248
+ },
1249
+ { id: "user-global-prompt", owner: "user", cacheScope: "session", content: userGlobalPromptSection },
1250
+ { id: "response-guidelines", owner: "platform", cacheScope: "session", content: responseGuidelinesSection },
1251
+ { id: "skill-guidance", owner: "runtime", cacheScope: "session", content: skillGuidanceSection },
1252
+ { id: "space-context", owner: "runtime", cacheScope: "turn", content: spaceContextSection },
1253
+ { id: "reference-materials", owner: "agent", cacheScope: "turn", content: referenceMaterialsSection },
1254
+ { id: "memory-overlay", owner: "runtime", cacheScope: "turn", content: memoryOverlaySection },
1255
+ { id: "app-working-memory", owner: "runtime", cacheScope: "turn", content: appWorkingMemorySection },
1256
+ { id: "dialog-summary", owner: "runtime", cacheScope: "turn", content: dialogSummarySection },
1257
+ { id: "proactive-summary", owner: "runtime", cacheScope: "turn", content: proactiveSummarySection },
1258
+ { id: "editing-context", owner: "runtime", cacheScope: "turn", content: editingContextSection },
1259
+ {
1260
+ id: "current-time",
1261
+ owner: "platform",
1262
+ cacheScope: "turn",
1263
+ content: buildCurrentTimeBlock(now, timeZone)
1264
+ }
1265
+ ]);
1266
+ };
1267
+
1268
+ // packages/integrations/openai/providerBodyCompatibility.ts
1269
+ var normalizeChatCompletionsBodyForProvider = ({
1270
+ body,
1271
+ provider,
1272
+ model
1273
+ }) => {
1274
+ const nextBody = { ...body, model };
1275
+ const normalizedProvider = asTrimmedLowercaseString(provider);
1276
+ if (normalizedProvider === "fireworks" && isFireworksKimiModel(model)) {
1277
+ delete nextBody.reasoning;
1278
+ delete nextBody.reasoning_effort;
1279
+ }
1280
+ return nextBody;
1281
+ };
1282
+
1283
+ // packages/integrations/openai/generateOpenAIRequestBody.ts
1284
+ var isClaudeModel = (model) => !!model && (model.includes("claude") || model.includes("anthropic"));
1285
+ var applyClaudeCache = (stableContent, dynamicContent) => {
1286
+ const parts = [];
1287
+ if (stableContent.trim()) {
1288
+ parts.push({
1289
+ type: "text",
1290
+ text: stableContent,
1291
+ cache_control: { type: "ephemeral" }
1292
+ });
1293
+ }
1294
+ if (dynamicContent.trim()) {
1295
+ parts.push({ type: "text", text: dynamicContent });
1296
+ }
1297
+ return parts.length > 0 ? parts : stableContent;
1298
+ };
1299
+ var prependPromptMessage = (messages, agentConfig, resolvedModel, language, contexts, prependSystemPrompt = true) => {
1300
+ if (!prependSystemPrompt) return messages;
1301
+ if (!contexts && !agentConfig.prompt) return messages;
1302
+ if (isClaudeModel(resolvedModel)) {
1303
+ const compiled = buildSystemPromptContext({ agentConfig, language, contexts });
1304
+ if (!compiled.content.trim()) return messages;
1305
+ const content = applyClaudeCache(
1306
+ compiled.stablePrefixContent,
1307
+ compiled.dynamicContent
1308
+ );
1309
+ const systemMessage2 = { role: "system", content };
1310
+ return [systemMessage2, ...messages];
1311
+ }
1312
+ const promptContent = buildSystemPrompt({ agentConfig, language, contexts });
1313
+ if (!promptContent.trim()) return messages;
1314
+ const systemMessage = { role: "system", content: promptContent };
1315
+ return [systemMessage, ...messages];
1316
+ };
1317
+ var shouldInjectLlamaCppThinkingToggle = (agentConfig) => {
1318
+ if (typeof agentConfig.enableThinking !== "boolean") return false;
1319
+ if (!isLoopbackUrl(agentConfig.customProviderUrl)) return false;
1320
+ return /qwen/i.test(agentConfig.model ?? "");
1321
+ };
1322
+ var shouldDisableMiMoThinking = (agentConfig) => {
1323
+ if (agentConfig.enableThinking === true) return false;
1324
+ return /xiaomimimo\.com/i.test(agentConfig.customProviderUrl ?? "") || (agentConfig.provider ?? "").toLowerCase() === "mimo";
1325
+ };
1326
+ var shouldDisableKimiThinking = (agentConfig, providerName, resolvedModel) => {
1327
+ if (agentConfig.enableThinking !== false) return false;
1328
+ if (providerName === "deepinfra") return isDeepInfraKimiModel(resolvedModel);
1329
+ if (providerName === "fireworks") return isFireworksKimiModel(resolvedModel);
1330
+ return false;
1331
+ };
1332
+ var normalizeChatCompletionsContent = (content) => {
1333
+ if (typeof content === "string" || Array.isArray(content)) return content;
1334
+ if (content == null) return null;
1335
+ return JSON.stringify(content);
1336
+ };
1337
+ var sanitizeChatCompletionsMessage = (message) => {
1338
+ const sanitized = {
1339
+ role: message.role,
1340
+ content: normalizeChatCompletionsContent(message.content)
1341
+ };
1342
+ const name = asOptionalTrimmedString(message.name);
1343
+ if (name) sanitized.name = name;
1344
+ const toolCallId = asOptionalTrimmedString(message.tool_call_id);
1345
+ if (toolCallId) sanitized.tool_call_id = toolCallId;
1346
+ if (Array.isArray(message.tool_calls)) {
1347
+ sanitized.tool_calls = message.tool_calls;
1348
+ }
1349
+ if (message.role === "assistant" && typeof message.reasoning_content === "string" && message.reasoning_content) {
1350
+ sanitized.reasoning_content = message.reasoning_content;
1351
+ }
1352
+ return sanitized;
1353
+ };
1354
+ var buildRequestBody = (options) => {
1355
+ const {
1356
+ model,
1357
+ messages,
1358
+ providerName,
1359
+ temperature,
1360
+ top_p,
1361
+ frequency_penalty,
1362
+ presence_penalty,
1363
+ max_tokens,
1364
+ reasoning_effort
1365
+ } = options;
1366
+ const cleanedMessages = messages.map(
1367
+ (message) => sanitizeChatCompletionsMessage(message)
1368
+ );
1369
+ const bodyData = {
1370
+ model,
1371
+ messages: cleanedMessages,
1372
+ stream: true
1373
+ };
1374
+ const usageRequestOptions = getUsageRequestOptions(providerName, {
1375
+ api: "chat-completions"
1376
+ });
1377
+ Object.assign(bodyData, usageRequestOptions);
1378
+ if (reasoning_effort && isModelSupportReasoningEffort(model)) {
1379
+ bodyData.reasoning_effort = reasoning_effort;
1380
+ }
1381
+ if (typeof temperature === "number") bodyData.temperature = temperature;
1382
+ if (typeof top_p === "number") bodyData.top_p = top_p;
1383
+ if (typeof frequency_penalty === "number")
1384
+ bodyData.frequency_penalty = frequency_penalty;
1385
+ if (typeof presence_penalty === "number")
1386
+ bodyData.presence_penalty = presence_penalty;
1387
+ if (typeof max_tokens === "number") bodyData.max_tokens = max_tokens;
1388
+ return bodyData;
1389
+ };
1390
+ var generateOpenAIRequestBody = (agentConfig, providerName, messages, contexts, stableMessages = [], prependSystemPrompt = true) => {
1391
+ const resolvedModel = providerName === "fireworks" ? resolveFireworksKimiModel(agentConfig.model) : agentConfig.model ?? "";
1392
+ let processedStable = [...stableMessages];
1393
+ if (isClaudeModel(resolvedModel) && processedStable.length > 0) {
1394
+ const lastStableIdx = processedStable.length - 1;
1395
+ const lastContent = processedStable[lastStableIdx].content;
1396
+ if (typeof lastContent === "string") {
1397
+ processedStable[lastStableIdx] = {
1398
+ ...processedStable[lastStableIdx],
1399
+ content: [
1400
+ { type: "text", text: lastContent, cache_control: { type: "ephemeral" } }
1401
+ ]
1402
+ };
1403
+ } else if (Array.isArray(lastContent)) {
1404
+ const lastPartIdx = lastContent.length - 1;
1405
+ processedStable[lastStableIdx] = {
1406
+ ...processedStable[lastStableIdx],
1407
+ content: lastContent.map(
1408
+ (part, idx) => idx === lastPartIdx && typeof part === "object" ? { ...part, cache_control: { type: "ephemeral" } } : part
1409
+ )
1410
+ };
1411
+ }
1412
+ }
1413
+ const fullMessages = [...processedStable, ...messages];
1414
+ const messagesWithPrompt = prependPromptMessage(
1415
+ fullMessages,
1416
+ agentConfig,
1417
+ resolvedModel,
1418
+ typeof navigator !== "undefined" ? navigator.language : "en",
1419
+ contexts,
1420
+ prependSystemPrompt
1421
+ );
1422
+ const requestBody = buildRequestBody({
1423
+ model: resolvedModel,
1424
+ messages: messagesWithPrompt,
1425
+ providerName,
1426
+ temperature: agentConfig.temperature,
1427
+ top_p: agentConfig.top_p,
1428
+ frequency_penalty: agentConfig.frequency_penalty,
1429
+ presence_penalty: agentConfig.presence_penalty,
1430
+ max_tokens: agentConfig.max_tokens,
1431
+ reasoning_effort: agentConfig.reasoning_effort
1432
+ });
1433
+ if (shouldInjectLlamaCppThinkingToggle(agentConfig)) {
1434
+ requestBody.chat_template_kwargs = {
1435
+ ...requestBody.chat_template_kwargs ?? {},
1436
+ enable_thinking: agentConfig.enableThinking
1437
+ };
1438
+ }
1439
+ if (shouldDisableMiMoThinking(agentConfig)) {
1440
+ requestBody.thinking = { type: "disabled" };
1441
+ }
1442
+ if (shouldDisableKimiThinking(agentConfig, providerName, resolvedModel)) {
1443
+ requestBody.thinking = { type: "disabled" };
1444
+ requestBody.reasoning_effort = "none";
1445
+ requestBody.reasoning = { enabled: false };
1446
+ }
1447
+ return normalizeChatCompletionsBodyForProvider({
1448
+ body: requestBody,
1449
+ provider: providerName,
1450
+ model: requestBody.model
1451
+ });
1452
+ };
1453
+
1454
+ // packages/integrations/openai/generateResponseRequestBody.ts
1455
+ function generateResponseRequestBody(agentConfig, msgs, contexts, prependSystemPrompt = true) {
1456
+ const language = typeof navigator !== "undefined" && navigator.language ? navigator.language : "zh-CN";
1457
+ const input = convertMessagesToResponsesInput(msgs);
1458
+ const body = {
1459
+ model: agentConfig.model,
1460
+ input,
1461
+ stream: true,
1462
+ ...getUsageRequestOptions(agentConfig.provider, { api: "responses" })
1463
+ };
1464
+ if (prependSystemPrompt) {
1465
+ const promptContent = buildSystemPrompt({
1466
+ agentConfig,
1467
+ language,
1468
+ contexts
1469
+ });
1470
+ body.instructions = promptContent;
1471
+ }
1472
+ if (agentConfig.temperature !== void 0) {
1473
+ body.temperature = agentConfig.temperature;
1474
+ }
1475
+ if (agentConfig.top_p !== void 0) {
1476
+ body.top_p = agentConfig.top_p;
1477
+ }
1478
+ if (agentConfig.max_tokens !== void 0) {
1479
+ body.max_output_tokens = agentConfig.max_tokens;
1480
+ }
1481
+ if (agentConfig.max_tool_calls !== void 0) {
1482
+ body.max_tool_calls = agentConfig.max_tool_calls;
1483
+ }
1484
+ if (agentConfig.user !== void 0) {
1485
+ body.user = agentConfig.user;
1486
+ }
1487
+ if (agentConfig.include !== void 0) {
1488
+ body.include = agentConfig.include;
1489
+ }
1490
+ if (agentConfig.metadata !== void 0) {
1491
+ body.metadata = agentConfig.metadata;
1492
+ }
1493
+ return body;
1494
+ }
1495
+
1496
+ // packages/ai/llm/generateRequestBody.ts
1497
+ var IMAGE_OUTPUT_EXECUTION_PROMPT = [
1498
+ "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.",
1499
+ "When the user asks you to generate, edit, redraw, or return an image, you must return the image in this turn.",
1500
+ "Do not answer with only a textual description.",
1501
+ "Do not claim that you uploaded, attached, or sent an image unless the response actually includes image output.",
1502
+ "Only return text without an image when the user explicitly asks for analysis, recommendations, or explanation without generating an image."
1503
+ ].join(" ");
1504
+ var getImageOutputSettings = (agentConfig, provider) => {
1505
+ const modelName = agentConfig.model;
1506
+ if (!modelName) {
1507
+ return { shouldEnableImage: false, modelConfig: null };
1508
+ }
1509
+ try {
1510
+ const modelConfig = getModelConfig(provider, modelName);
1511
+ const hasImageOutput = !!modelConfig.hasImageOutput;
1512
+ const isExplicitlyDisabled = agentConfig.imageConfig?.enabled === false;
1513
+ return {
1514
+ shouldEnableImage: hasImageOutput && !isExplicitlyDisabled,
1515
+ modelConfig
1516
+ };
1517
+ } catch {
1518
+ return { shouldEnableImage: false, modelConfig: null };
1519
+ }
1520
+ };
1521
+ var withImageOutputPromptGuard = (agentConfig, shouldEnableImage) => {
1522
+ if (!shouldEnableImage) return agentConfig;
1523
+ const basePrompt = asTrimmedString(agentConfig.prompt);
1524
+ if (basePrompt.includes(IMAGE_OUTPUT_EXECUTION_PROMPT)) {
1525
+ return agentConfig;
1526
+ }
1527
+ return {
1528
+ ...agentConfig,
1529
+ prompt: basePrompt ? `${basePrompt}
1530
+
1531
+ ${IMAGE_OUTPUT_EXECUTION_PROMPT}` : IMAGE_OUTPUT_EXECUTION_PROMPT
1532
+ };
1533
+ };
1534
+ var applyImageConfigIfNeeded = (body, agentConfig, provider) => {
1535
+ const { shouldEnableImage, modelConfig } = getImageOutputSettings(
1536
+ agentConfig,
1537
+ provider
1538
+ );
1539
+ const agentImageCfg = agentConfig.imageConfig;
1540
+ if (!shouldEnableImage || !modelConfig) {
1541
+ return body;
1542
+ }
1543
+ const modalities = agentImageCfg?.forceModalities ?? modelConfig.defaultModalities ?? (modelConfig.requiresImageModalities ? ["image", "text"] : void 0);
1544
+ if (modalities && !body.modalities) {
1545
+ body.modalities = modalities;
1546
+ }
1547
+ if (!modelConfig.supportsImageConfig) {
1548
+ return body;
1549
+ }
1550
+ const aspectRatio = agentImageCfg?.aspectRatio;
1551
+ const imageSize = agentImageCfg?.imageSize;
1552
+ if (!aspectRatio && !imageSize) {
1553
+ return body;
1554
+ }
1555
+ body.image_config = {
1556
+ ...body.image_config ?? {},
1557
+ ...aspectRatio ? { aspect_ratio: aspectRatio } : {},
1558
+ ...imageSize ? { image_size: imageSize } : {}
1559
+ };
1560
+ return body;
1561
+ };
1562
+ var generateRequestBody = ({
1563
+ agentConfig,
1564
+ messages,
1565
+ contexts,
1566
+ stableMessages,
1567
+ prependSystemPrompt = true
1568
+ }) => {
1569
+ const provider = (agentConfig.provider || "").toLowerCase();
1570
+ const imageSettings = getImageOutputSettings(agentConfig, provider);
1571
+ const agentConfigForRequest = withImageOutputPromptGuard(
1572
+ agentConfig,
1573
+ imageSettings.shouldEnableImage
1574
+ );
1575
+ const clientWire = resolveClientWire(
1576
+ resolveAgentCallPlan(agentConfigForRequest, {})
1577
+ );
1578
+ if (clientWire === "responses") {
1579
+ return generateResponseRequestBody(
1580
+ agentConfigForRequest,
1581
+ [...stableMessages ?? [], ...messages],
1582
+ contexts,
1583
+ prependSystemPrompt
1584
+ );
1585
+ }
1586
+ const baseBody = generateOpenAIRequestBody(
1587
+ agentConfigForRequest,
1588
+ provider,
1589
+ messages,
1590
+ contexts,
1591
+ stableMessages,
1592
+ prependSystemPrompt
1593
+ );
1594
+ return applyImageConfigIfNeeded(baseBody, agentConfigForRequest, provider);
1595
+ };
1596
+
1597
+ // packages/ai/chat/serverProxyRetry.ts
1598
+ var RETRYABLE_SERVER_PROXY_STATUSES = /* @__PURE__ */ new Set([502, 503, 504]);
1599
+ var DEFAULT_SERVER_PROXY_RETRY_AFTER_MS = 1500;
1600
+ var MAX_SERVER_PROXY_RETRIES = 2;
1601
+ var MAX_STATUS_RETRIES = 1;
1602
+ var resolveServerProxyRetryAfterMs = (response) => parseRetryAfterHeaderMs(response.headers.get("Retry-After")) ?? DEFAULT_SERVER_PROXY_RETRY_AFTER_MS;
1603
+ var isRetryableServerProxyFetchError = (error) => {
1604
+ if (!error || isAbortError(error)) return false;
1605
+ const message = typeof error?.message === "string" ? error.message : String(error);
1606
+ return /ECONNREFUSED|ECONNRESET|EPIPE|socket hang up|network error|failed to fetch|fetch failed|connection closed|load failed|502|503|504/i.test(
1607
+ message
1608
+ );
1609
+ };
1610
+ var waitForServerProxyRetry = async (retryAfterMs, signal) => {
1611
+ if (retryAfterMs <= 0) return;
1612
+ if (signal?.aborted) {
1613
+ const abortError = new Error("Aborted");
1614
+ abortError.name = "AbortError";
1615
+ throw abortError;
1616
+ }
1617
+ await new Promise((resolve, reject) => {
1618
+ const onAbort = () => {
1619
+ clearTimeout(timeoutId);
1620
+ signal?.removeEventListener("abort", onAbort);
1621
+ const abortError = new Error("Aborted");
1622
+ abortError.name = "AbortError";
1623
+ reject(abortError);
1624
+ };
1625
+ const timeoutId = setTimeout(() => {
1626
+ signal?.removeEventListener("abort", onAbort);
1627
+ resolve();
1628
+ }, normalizeNonNegativeMs(retryAfterMs, DEFAULT_SERVER_PROXY_RETRY_AFTER_MS));
1629
+ signal?.addEventListener("abort", onAbort, { once: true });
1630
+ });
1631
+ };
1632
+ var performServerProxyFetchWithRetry = async ({
1633
+ execute,
1634
+ signal,
1635
+ logPrefix = "[fetchWithServerProxy]"
1636
+ }) => {
1637
+ for (let attempt = 0; attempt <= MAX_SERVER_PROXY_RETRIES; attempt += 1) {
1638
+ try {
1639
+ const response = await execute();
1640
+ if (attempt < MAX_STATUS_RETRIES && RETRYABLE_SERVER_PROXY_STATUSES.has(response.status)) {
1641
+ const retryAfterMs = resolveServerProxyRetryAfterMs(response);
1642
+ console.warn(
1643
+ `${logPrefix} \u68C0\u6D4B\u5230${response.status}\u72B6\u6001\uFF0C${retryAfterMs}ms\u540E\u91CD\u8BD5\u4E00\u6B21...`
1644
+ );
1645
+ await waitForServerProxyRetry(retryAfterMs, signal);
1646
+ continue;
1647
+ }
1648
+ return response;
1649
+ } catch (error) {
1650
+ if (attempt < MAX_SERVER_PROXY_RETRIES && isRetryableServerProxyFetchError(error)) {
1651
+ const retryDelay = (attempt + 1) * 1e3;
1652
+ console.warn(
1653
+ `${logPrefix} \u68C0\u6D4B\u5230\u7F51\u7EDC\u77AC\u65AD\uFF0C${retryDelay}ms\u540E\u91CD\u8BD5(\u7B2C${attempt + 1}\u6B21)...`,
1654
+ error
1655
+ );
1656
+ await waitForServerProxyRetry(retryDelay, signal);
1657
+ continue;
1658
+ }
1659
+ throw error;
1660
+ }
1661
+ }
1662
+ throw new Error("server proxy retry exhausted unexpectedly");
1663
+ };
1664
+
1665
+ // packages/ai/chat/resolveDirectRequestApiKey.ts
1666
+ 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";
1667
+ var DirectApiKeyResolutionError = class extends Error {
1668
+ constructor(message = DIRECT_API_KEY_UNAVAILABLE_MESSAGE) {
1669
+ super(message);
1670
+ this.name = "DirectApiKeyResolutionError";
1671
+ }
1672
+ };
1673
+ var createDirectCredentialBroker = createFileCredentialBroker;
1674
+ function readNonEmpty(value) {
1675
+ return asTrimmedString(value);
1676
+ }
1677
+ async function resolveDirectRequestApiKey(agentConfig, options) {
1678
+ const rawKey = readNonEmpty(agentConfig.apiKey);
1679
+ if (rawKey) return rawKey;
1680
+ const credentialRef = readNonEmpty(agentConfig.credentialRef);
1681
+ if (!credentialRef) return void 0;
1682
+ const factory = options?.brokerFactory ?? createDirectCredentialBroker;
1683
+ const broker = factory();
1684
+ const local = await safeBrokerGet(broker, credentialRef);
1685
+ if (local) return local;
1686
+ if (agentConfig.credentialSynced && options?.syncFetcher) {
1687
+ const synced = await options.syncFetcher(credentialRef);
1688
+ const trimmed = asTrimmedString(synced);
1689
+ if (trimmed) {
1690
+ try {
1691
+ await broker.put(credentialRef, trimmed);
1692
+ } catch {
1693
+ }
1694
+ return trimmed;
1695
+ }
1696
+ }
1697
+ throw new DirectApiKeyResolutionError();
1698
+ }
1699
+ async function safeBrokerGet(broker, ref) {
1700
+ try {
1701
+ return asTrimmedString(await broker.get(ref)) || null;
1702
+ } catch {
1703
+ return null;
1704
+ }
1705
+ }
1706
+
1707
+ // packages/ai/chat/fetchUtils.ts
1708
+ var buildProxyPayload = (bodyData, api, agentConfig, dialogId) => {
1709
+ const apiSource = agentConfig.apiSource === "custom" || agentConfig.apiSource === "cli" ? agentConfig.apiSource : void 0;
1710
+ const provider = bodyData.provider || agentConfig.provider || (apiSource === "custom" ? "custom" : void 0);
1711
+ const apiKey = asOptionalTrimmedString(agentConfig.apiKey);
1712
+ return {
1713
+ ...bodyData,
1714
+ url: api,
1715
+ provider,
1716
+ agentKey: agentConfig.dbKey,
1717
+ ...asOptionalTrimmedString(dialogId) ? { dialogId: asOptionalTrimmedString(dialogId) } : {},
1718
+ ...apiSource ? { apiSource } : {},
1719
+ ...agentConfig.apiKeyHeader ? { apiKeyHeader: agentConfig.apiKeyHeader } : {},
1720
+ KEY: apiKey
1721
+ };
1722
+ };
1723
+ var fetchDirectly = async (params) => {
1724
+ const { api, agentConfig, bodyData, signal, currentServer, token } = params;
1725
+ try {
1726
+ const apiKey = await resolveDirectRequestApiKey(agentConfig, {
1727
+ syncFetcher: currentServer && token ? (ref) => fetchServerSyncedCredential({ currentServer, authToken: token }, ref) : void 0
1728
+ });
1729
+ const authHeaders = buildProviderAuthHeaders({
1730
+ endpoint: api,
1731
+ apiKey: apiKey ?? "",
1732
+ apiKeyHeader: agentConfig.apiKeyHeader
1733
+ });
1734
+ return await fetch(api, {
1735
+ method: "POST",
1736
+ headers: {
1737
+ "Content-Type": "application/json",
1738
+ ...authHeaders,
1739
+ ...api.includes("openrouter.ai") ? {
1740
+ "HTTP-Referer": "https://nolo.chat",
1741
+ "X-Title": "nolo"
1742
+ } : {}
1743
+ },
1744
+ body: JSON.stringify(bodyData),
1745
+ signal
1746
+ // 可选参数,直接传递
1747
+ });
1748
+ } catch (error) {
1749
+ console.error("[fetchDirectly] \u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25:", error);
1750
+ throw error;
1751
+ }
1752
+ };
1753
+ var fetchWithServerProxy = async ({
1754
+ currentServer,
1755
+ api,
1756
+ bodyData,
1757
+ agentConfig,
1758
+ token,
1759
+ signal,
1760
+ dialogId
1761
+ }) => {
1762
+ try {
1763
+ const payload = buildProxyPayload(bodyData, api, agentConfig, dialogId);
1764
+ return await performServerProxyFetchWithRetry({
1765
+ signal,
1766
+ execute: () => fetch(`${currentServer}${API_ENDPOINTS.CHAT}`, {
1767
+ method: "POST",
1768
+ headers: {
1769
+ "Content-Type": "application/json",
1770
+ Authorization: `Bearer ${token}`
1771
+ // 使用 Authorization 头传递 token
1772
+ },
1773
+ body: JSON.stringify(payload),
1774
+ signal
1775
+ })
1776
+ });
1777
+ } catch (error) {
1778
+ console.error("[fetchWithServerProxy] \u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25:", error);
1779
+ throw error;
1780
+ }
1781
+ };
1782
+ var formatFriendlyNetworkErrorMessage = (error) => {
1783
+ if (typeof window !== "undefined" && typeof navigator !== "undefined" && navigator.onLine === false) {
1784
+ return "\u7F51\u7EDC\u8FDE\u63A5\u5DF2\u65AD\u5F00\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5\u540E\u91CD\u8BD5";
1785
+ }
1786
+ const rawMessage = toErrorMessage(error);
1787
+ if (/failed to fetch|networkerror|network error|econnrefused|econnreset|socket hang up/i.test(
1788
+ rawMessage
1789
+ )) {
1790
+ return "\u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5\u6216\u4EE3\u7406/VPN\u8BBE\u7F6E";
1791
+ }
1792
+ return rawMessage;
1793
+ };
1794
+ var performFetchRequest = async (params) => {
1795
+ try {
1796
+ const planConfig = {
1797
+ ...params.agentConfig,
1798
+ provider: params.bodyData.provider || params.agentConfig.provider
1799
+ };
1800
+ return resolveAgentCallPlan(planConfig, {}).transport === "server-proxy" ? await fetchWithServerProxy(params) : await fetchDirectly(params);
1801
+ } catch (error) {
1802
+ console.error("[performFetchRequest] \u8BF7\u6C42\u8FC7\u7A0B\u4E2D\u53D1\u751F\u9519\u8BEF:", error);
1803
+ const friendlyMsg = formatFriendlyNetworkErrorMessage(error);
1804
+ throw new Error(
1805
+ friendlyMsg.startsWith("\u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25") ? friendlyMsg : `\u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25: ${friendlyMsg}`
1806
+ );
1807
+ }
1808
+ };
1809
+
1810
+ // packages/create/editor/transforms/slateToText.ts
1811
+ function getNodeText(node) {
1812
+ if (node.text) {
1813
+ return node.text;
1814
+ }
1815
+ if (node.children && Array.isArray(node.children)) {
1816
+ return node.children.map(getNodeText).join("\n");
1817
+ }
1818
+ return "";
1819
+ }
1820
+ function slateToText(nodes) {
1821
+ if (!nodes || nodes.length === 0) {
1822
+ return "";
1823
+ }
1824
+ return nodes.map(getNodeText).join("\n\n");
1825
+ }
1826
+
1827
+ // packages/ai/context/buildReferenceContext.ts
1828
+ var MAX_META_TEXT_LENGTH = 80;
1829
+ var DIALOG_REFERENCE_MESSAGE_LIMIT = 20;
1830
+ var DIALOG_REFERENCE_SNIPPET_CHARS = 1200;
1831
+ var DIALOG_HANDOFF_SNIPPET_CHARS = 360;
1832
+ var truncateMetaText = (value, max = MAX_META_TEXT_LENGTH) => {
1833
+ if (!value) return "";
1834
+ if (value.length <= max) return value;
1835
+ return `${value.slice(0, max - 3)}...`;
1836
+ };
1837
+ var readSafe = async (dispatch, dbKey) => {
1838
+ try {
1839
+ return await dispatch(read({
1840
+ dbKey
1841
+ })).unwrap();
1842
+ } catch {
1843
+ return null;
1844
+ }
1845
+ };
1846
+ var buildMentionMetaMap = async (slateData, dispatch) => {
1847
+ const metaMap = /* @__PURE__ */ new Map();
1848
+ const mentions = extractCategorizedMentions(slateData);
1849
+ if (!mentions) return metaMap;
1850
+ const pageEntries = await Promise.all(
1851
+ (mentions.pages || []).map(async (pageId) => {
1852
+ const pageData = await readSafe(dispatch, pageId);
1853
+ if (!pageData) {
1854
+ return [`page:${pageId}`, { displayType: "page", metaParts: [] }];
1855
+ }
1856
+ if (pageData.type === "dialog" /* DIALOG */) {
1857
+ const agentCount = Array.isArray(pageData.cybots) ? pageData.cybots.length : 0;
1858
+ return [
1859
+ `page:${pageId}`,
1860
+ {
1861
+ displayType: "dialog",
1862
+ title: pageData.title,
1863
+ metaParts: [
1864
+ `agents=${agentCount}`,
1865
+ `updated=${pageData.updatedAt || pageData.updated_at || pageData.updated || "Unknown"}`
1866
+ ]
1867
+ }
1868
+ ];
1869
+ }
1870
+ const tags = pageData.tags && pageData.tags.length > 0 ? pageData.tags.slice(0, 5).join(", ") : "";
1871
+ return [
1872
+ `page:${pageId}`,
1873
+ {
1874
+ displayType: "page",
1875
+ title: pageData.title,
1876
+ metaParts: [
1877
+ pageData.spaceId ? `space=${pageData.spaceId}` : "",
1878
+ tags ? `tags=${tags}` : "",
1879
+ `updated=${pageData.updatedAt || pageData.updated_at || pageData.updated || "Unknown"}`
1880
+ ].filter(Boolean)
1881
+ }
1882
+ ];
1883
+ })
1884
+ );
1885
+ pageEntries.forEach((entry) => metaMap.set(entry[0], entry[1]));
1886
+ const agentEntries = await Promise.all(
1887
+ (mentions.agents || []).map(async (agentId) => {
1888
+ const agentData = await readSafe(dispatch, agentId);
1889
+ if (!agentData) {
1890
+ return [`agent:${agentId}`, { displayType: "agent", metaParts: [] }];
1891
+ }
1892
+ const desc = truncateMetaText(
1893
+ agentData.description || agentData.introduction || ""
1894
+ );
1895
+ return [
1896
+ `agent:${agentId}`,
1897
+ {
1898
+ displayType: "agent",
1899
+ title: agentData.name,
1900
+ metaParts: [
1901
+ `public=${agentData.isPublic ? "yes" : "no"}`,
1902
+ desc ? `desc=${desc}` : ""
1903
+ ].filter(Boolean)
1904
+ }
1905
+ ];
1906
+ })
1907
+ );
1908
+ agentEntries.forEach((entry) => metaMap.set(entry[0], entry[1]));
1909
+ const spaceEntries = await Promise.all(
1910
+ (mentions.spaces || []).map(async (spaceId) => {
1911
+ const spaceKey = createSpaceKey.space(spaceId);
1912
+ const spaceData = await readSafe(dispatch, spaceKey);
1913
+ if (!spaceData) {
1914
+ return [`space:${spaceId}`, { displayType: "space", metaParts: [] }];
1915
+ }
1916
+ const desc = truncateMetaText(spaceData.description || "");
1917
+ const categoriesCount = Object.keys(spaceData.categories || {}).length;
1918
+ const contentsCount = Object.keys(spaceData.contents || {}).length;
1919
+ return [
1920
+ `space:${spaceId}`,
1921
+ {
1922
+ displayType: "space",
1923
+ title: spaceData.name,
1924
+ metaParts: [
1925
+ desc ? `desc=${desc}` : "",
1926
+ `categories=${categoriesCount}`,
1927
+ `contents=${contentsCount}`
1928
+ ].filter(Boolean)
1929
+ }
1930
+ ];
1931
+ })
1932
+ );
1933
+ spaceEntries.forEach((entry) => metaMap.set(entry[0], entry[1]));
1934
+ return metaMap;
1935
+ };
1936
+ var buildInlineMention = (node, metaMap) => {
1937
+ const resourceType = node.resourceType || "unknown";
1938
+ const resourceId = node.resourceId || "unknown";
1939
+ const key = `${resourceType}:${resourceId}`;
1940
+ const meta = metaMap.get(key);
1941
+ const label = meta?.title || node.label || resourceId || "mention";
1942
+ const displayType = meta?.displayType || resourceType;
1943
+ const metaParts = meta?.metaParts ?? [];
1944
+ const idPart = resourceType === "tool" ? `tool=${resourceId}` : `dbkey=${resourceId}`;
1945
+ const metaSuffix = metaParts.length ? ` | ${metaParts.join(" | ")}` : "";
1946
+ return `@${label}(${displayType} | ${idPart}${metaSuffix})`;
1947
+ };
1948
+ var clipReferenceText = (value, max) => {
1949
+ const raw = typeof value === "string" ? value : value == null ? "" : JSON.stringify(value);
1950
+ return clipMultilineText(raw, max);
1951
+ };
1952
+ var fetchDialogReference = async (dbKey, refContent, dispatch) => {
1953
+ const dialogConfig = refContent;
1954
+ const dialogTitle = dialogConfig.title || `Untitled Dialog (${dbKey})`;
1955
+ const dialogId = extractCustomId(dbKey) || dbKey.replace(/^dialog-/, "");
1956
+ const checkpoint = dialogConfig.runtimeCheckpoint || null;
1957
+ const summary = asTrimmedString(dialogConfig.summary);
1958
+ const proactiveSummary = asTrimmedString(dialogConfig.proactiveSummary);
1959
+ const messages = await dispatch(
1960
+ async (_dispatch, getState, { db }) => {
1961
+ const state = getState();
1962
+ const { currentToken: token, remoteServers } = getRuntimeServerContext(state);
1963
+ return await fetchAndCacheMessages({
1964
+ db,
1965
+ dialogId,
1966
+ limit: DIALOG_REFERENCE_MESSAGE_LIMIT,
1967
+ token,
1968
+ remoteServers: remoteServers.length > 0 ? remoteServers : void 0
1969
+ });
1970
+ }
1971
+ );
1972
+ const sortedMessages = [...messages].reverse();
1973
+ const formatContent = (content) => clipReferenceText(content, DIALOG_REFERENCE_SNIPPET_CHARS);
1974
+ const transcript = sortedMessages.map((msg, index) => {
1975
+ const toolLine = msg.toolName ? ` tool=${msg.toolName}` : "";
1976
+ const agentLine = msg.cybotKey ? ` agent=${msg.cybotKey}` : "";
1977
+ const createdLine = msg.createdAt ? ` at=${msg.createdAt}` : "";
1978
+ return [
1979
+ `### Message ${index + 1}: ${msg.role || "unknown"} id=${msg.id || "unknown"}${toolLine}${agentLine}${createdLine}`,
1980
+ formatContent(msg.content) || "[empty]"
1981
+ ].join("\n");
1982
+ }).join("\n\n");
1983
+ const checkpointLines = [];
1984
+ if (checkpoint && typeof checkpoint === "object") {
1985
+ if (checkpoint.status) checkpointLines.push(`- status: ${checkpoint.status}`);
1986
+ if (checkpoint.lastUserInput) checkpointLines.push(`- lastUserInput: ${formatContent(checkpoint.lastUserInput)}`);
1987
+ if (checkpoint.lastAssistantText) checkpointLines.push(`- lastAssistantText: ${formatContent(checkpoint.lastAssistantText)}`);
1988
+ if (Array.isArray(checkpoint.lastToolNames) && checkpoint.lastToolNames.length) {
1989
+ checkpointLines.push(`- lastToolNames: ${checkpoint.lastToolNames.join(", ")}`);
1990
+ }
1991
+ if (Array.isArray(checkpoint.availableToolNames) && checkpoint.availableToolNames.length) {
1992
+ checkpointLines.push(`- availableToolNames: ${checkpoint.availableToolNames.join(", ")}`);
1993
+ }
1994
+ }
1995
+ const recentToolEvidence = sortedMessages.filter((msg) => msg.role === "tool" || msg.toolName).slice(-3).map((msg) => {
1996
+ const label = msg.toolName ? `${msg.toolName}` : "tool";
1997
+ return `- ${label} id=${msg.id || "unknown"}: ${clipReferenceText(msg.content, DIALOG_HANDOFF_SNIPPET_CHARS) || "[empty]"}`;
1998
+ });
1999
+ const handoffLines = [
2000
+ `- Use this when continuing work, transferring to another Agent, comparing with the current task, or preparing a document/plan from the prior discussion.`,
2001
+ `- Current state source: ${checkpointLines.length ? "Runtime Checkpoint" : "summaries and recent transcript"}.`,
2002
+ summary ? `- Compressed background: passive summary is available below; treat it as lossy, not original wording.` : "",
2003
+ proactiveSummary ? `- Recent work: proactive summary is available below; use it for current direction, not exact evidence.` : "",
2004
+ recentToolEvidence.length ? `- Recent tool evidence:
2005
+ ${recentToolEvidence.join("\n")}` : `- Recent tool evidence: none loaded in the latest ${DIALOG_REFERENCE_MESSAGE_LIMIT} messages.`,
2006
+ `- 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}.`
2007
+ ].filter(Boolean);
2008
+ const referenceBody = [
2009
+ `Conversation Reference:`,
2010
+ `DB Key: ${dbKey}`,
2011
+ `Title: ${dialogTitle}`,
2012
+ `Status: ${dialogConfig.status || "unknown"}`,
2013
+ `Loaded Recent Messages: ${sortedMessages.length}`,
2014
+ `Conversation Handoff:
2015
+ ${handoffLines.join("\n")}`,
2016
+ checkpointLines.length ? `Runtime Checkpoint:
2017
+ ${checkpointLines.join("\n")}` : "",
2018
+ summary ? `Passive Summary (compressed history, not original wording):
2019
+ ${wrapHistoricalSummaryWithReplayGuard(summary)}` : "",
2020
+ proactiveSummary ? `Proactive Summary (recent work summary, not original wording):
2021
+ ${wrapHistoricalSummaryWithReplayGuard(proactiveSummary)}` : "",
2022
+ `Recent Transcript (original message excerpts, oldest to newest):
2023
+ ${transcript || "[no recent messages loaded]"}`,
2024
+ [
2025
+ `Coverage Note: This reference intentionally loads only the latest ${DIALOG_REFERENCE_MESSAGE_LIMIT} messages plus summaries/checkpoint to control token load.`,
2026
+ `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.`
2027
+ ].join("\n")
2028
+ ].filter(Boolean).join("\n\n");
2029
+ const tokenEstimate = estimateTokenCount(referenceBody);
2030
+ return `${referenceBody}
2031
+
2032
+ Token Load Estimate: ${tokenEstimate} tokens for this conversation reference.
2033
+ ---
2034
+
2035
+ `;
2036
+ };
2037
+ var fetchTableReference = async (dbKey, refContent, dispatch) => {
2038
+ const tableMeta = refContent;
2039
+ const title = tableMeta.displayName || tableMeta.description || `Untitled Table (${dbKey})`;
2040
+ const { markdown: tableMd } = await dispatch(
2041
+ async (_dispatch, getState, { db }) => {
2042
+ const state = getState();
2043
+ const { currentToken: token, remoteServers } = getRuntimeServerContext(state);
2044
+ return await fetchAndSerializeTable(tableMeta, db, {
2045
+ token,
2046
+ remoteServers
2047
+ });
2048
+ }
2049
+ );
2050
+ const tags = tableMeta.tags?.length ? tableMeta.tags.join(", ") : "None";
2051
+ const description = tableMeta.description || "No description provided.";
2052
+ return `Reference Item (Table):
2053
+ DB Key: ${dbKey}
2054
+ Title: ${title}
2055
+ Description: ${description}
2056
+ Tags: ${tags}
2057
+ Content (Markdown Table):
2058
+
2059
+ ${tableMd}
2060
+ ---
2061
+
2062
+ `;
2063
+ };
2064
+ var fetchSlateReference = async (dbKey, refContent, dispatch, options) => {
2065
+ if (!refContent?.slateData) return null;
2066
+ const title = refContent.title || `Untitled (${dbKey})`;
2067
+ let contentString;
2068
+ let contentType;
2069
+ const inlineMentionMeta = options.inlineMentionMeta ?? options.format === "simplified_markdown";
2070
+ switch (options.format) {
2071
+ case "text":
2072
+ contentType = "Plain Text";
2073
+ contentString = slateToText(refContent.slateData);
2074
+ break;
2075
+ case "simplified_markdown":
2076
+ contentType = "Simplified Markdown";
2077
+ if (inlineMentionMeta) {
2078
+ const metaMap = await buildMentionMetaMap(refContent.slateData, dispatch);
2079
+ contentString = slateToSimplifiedMarkdown(refContent.slateData, {
2080
+ mentionResolver: (node) => buildInlineMention(node, metaMap)
2081
+ });
2082
+ } else {
2083
+ contentString = slateToSimplifiedMarkdown(refContent.slateData);
2084
+ }
2085
+ break;
2086
+ case "json":
2087
+ default:
2088
+ contentType = "Slate JSON";
2089
+ contentString = JSON.stringify(refContent.slateData, null, 2);
2090
+ break;
2091
+ }
2092
+ if (!contentString || typeof contentString === "string" && !contentString.trim() || contentString === "[]") {
2093
+ return null;
2094
+ }
2095
+ const tags = (refContent.tags || []).length > 0 ? refContent.tags.join(", ") : "None";
2096
+ const createdAt = refContent.created || "Unknown Creation Date";
2097
+ const updatedAt = refContent.updated || "Unknown Update Date";
2098
+ return `Reference Item:
2099
+ DB Key: ${dbKey}
2100
+ Title: ${title}
2101
+ Content (${contentType}):
2102
+ ${contentString}
2103
+ Tags: ${tags}
2104
+ Created At: ${createdAt}
2105
+ Updated At: ${updatedAt}
2106
+ ---
2107
+
2108
+ `;
2109
+ };
2110
+ var fetchReferenceContents = async (references, dispatch, options = { format: "simplified_markdown" }) => {
2111
+ const result = /* @__PURE__ */ new Map();
2112
+ if (!references || references.length === 0) return result;
2113
+ const referencePromises = references.map(async (dbKey) => {
2114
+ try {
2115
+ const hasPreloaded = options.preloaded?.has(dbKey);
2116
+ const refContent = hasPreloaded ? options.preloaded?.get(dbKey) : await dispatch(read({
2117
+ dbKey
2118
+ })).unwrap();
2119
+ if (!refContent) return null;
2120
+ let formatted = null;
2121
+ if (refContent.type === "dialog" /* DIALOG */) {
2122
+ formatted = await fetchDialogReference(dbKey, refContent, dispatch);
2123
+ } else if (refContent.type === "table" /* TABLE */) {
2124
+ formatted = await fetchTableReference(dbKey, refContent, dispatch);
2125
+ } else {
2126
+ formatted = await fetchSlateReference(dbKey, refContent, dispatch, options);
2127
+ }
2128
+ if (formatted) return [dbKey, formatted];
2129
+ return null;
2130
+ } catch (error) {
2131
+ console.error(`Error fetching reference ${dbKey}:`, error);
2132
+ return null;
2133
+ }
2134
+ });
2135
+ const resolved = await Promise.all(referencePromises);
2136
+ resolved.forEach((item) => {
2137
+ if (item) result.set(item[0], item[1]);
2138
+ });
2139
+ return result;
2140
+ };
2141
+
2142
+ export {
2143
+ fetchReferenceContents,
2144
+ mergeReferences,
2145
+ resolveReferenceAssets,
2146
+ resolveToolsFromKeys,
2147
+ resolveClientWire,
2148
+ resolveAgentCallPlan,
2149
+ generateRequestBody,
2150
+ performServerProxyFetchWithRetry,
2151
+ performFetchRequest
2152
+ };