nolo-cli 0.8.0-alpha.2 → 0.8.0-alpha.21

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