u-foo 4.0.10 → 4.1.2

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 (71) hide show
  1. package/OPTIONAL_SKILLS/ufoo-bus-poll/SKILL.md +27 -0
  2. package/README.md +279 -789
  3. package/README.zh-CN.md +290 -439
  4. package/SKILLS/ufoo/SKILL.md +7 -0
  5. package/bin/ufoo.js +36 -3
  6. package/dist/tui/darwin-arm64/ufoo-tui +0 -0
  7. package/docs/OBSERVABILITY.md +4 -2
  8. package/docs/README.md +1 -0
  9. package/package.json +6 -2
  10. package/scripts/pack-desktop.js +174 -0
  11. package/src/agents/capabilities/coding/index.js +26 -3
  12. package/src/agents/capabilities/index.js +2 -1
  13. package/src/agents/capabilities/mac/index.js +145 -0
  14. package/src/agents/capabilities/planning/index.js +1 -1
  15. package/src/agents/capabilities/turnRecall/index.js +5 -16
  16. package/src/agents/profiles/coding.js +1 -1
  17. package/src/agents/profiles/main.js +1 -1
  18. package/src/agents/providers/nativeTransport.js +105 -116
  19. package/src/agents/providers/runtimeConfig.js +15 -4
  20. package/src/agents/providers/transports/anthropicCache.js +78 -0
  21. package/src/agents/providers/transports/antigravityTransport.js +3 -2
  22. package/src/agents/providers/transports/openaiResponsesTransport.js +7 -12
  23. package/src/agents/providers/transports/requestCacheObservation.js +61 -0
  24. package/src/agents/providers/transports/responsesProtocol.js +54 -46
  25. package/src/agents/providers/upstreamRuntime.js +2 -2
  26. package/src/agents/runtime/context/contextWindow.js +10 -0
  27. package/src/agents/runtime/context/slidingWindowManager.js +97 -41
  28. package/src/agents/runtime/context/topicSelector.js +4 -2
  29. package/src/agents/runtime/context/turnAnalyzer.js +17 -29
  30. package/src/agents/runtime/core/agentLoop.js +23 -7
  31. package/src/agents/runtime/createAgentRuntime.js +1 -1
  32. package/src/agents/runtime/protocol/auxiliaryModelRequest.js +28 -0
  33. package/src/app/chat/ChatController.js +1 -0
  34. package/src/app/chat/commandExecutor.js +25 -0
  35. package/src/app/chat/commands.js +2 -0
  36. package/src/app/chat/daemonMessageRouter.js +30 -3
  37. package/src/app/cli/appCommands.js +107 -0
  38. package/src/app/cli/features/skills.js +2 -0
  39. package/src/app/cli/macCommands.js +321 -0
  40. package/src/app/cli/metricsCommands.js +6 -1
  41. package/src/app/cli/run.js +26 -0
  42. package/src/app/cli/setupCommands.js +1 -0
  43. package/src/code/agent.js +1 -0
  44. package/src/code/context/assembler.js +8 -6
  45. package/src/code/context/promptLayers.js +3 -1
  46. package/src/code/context/stateCommit.js +2 -2
  47. package/src/code/context/transcript.js +11 -5
  48. package/src/code/nativeRunner.js +25 -5
  49. package/src/code/skills/loader.js +10 -2
  50. package/src/code/skills/render.js +8 -1
  51. package/src/config.js +42 -0
  52. package/src/coordination/bus/activate.js +44 -19
  53. package/src/coordination/history/agentPerformance.js +88 -11
  54. package/src/coordination/history/agentTrace.js +2 -0
  55. package/src/coordination/history/modelInputCost.js +52 -0
  56. package/src/runtime/contracts/uiProtocol.js +26 -0
  57. package/src/runtime/daemon/agentHost.js +35 -12
  58. package/src/runtime/daemon/mcpStdioProxy.js +3 -2
  59. package/src/runtime/mac/helperClient.js +279 -0
  60. package/src/runtime/mac/helperCompiler.js +235 -0
  61. package/src/runtime/mac/macSession.js +866 -0
  62. package/src/runtime/mac/native/ufoo_mac_helper.swift +2493 -0
  63. package/src/runtime/mac/paths.js +63 -0
  64. package/src/ui/agentSettingsController.js +12 -5
  65. package/src/ui/cliHandoff.js +484 -0
  66. package/src/ui/desktopArchive.js +41 -0
  67. package/src/ui/desktopUiHost.js +1601 -0
  68. package/src/ui/desktopUiHostCli.js +66 -0
  69. package/src/ui/format/index.js +17 -0
  70. package/src/ui/rustChatHost.js +45 -6
  71. package/src/ui/workspaceInspector.js +621 -0
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+
3
+ const { createHash } = require("crypto");
4
+
5
+ const MAX_SESSIONS = 200;
6
+ const previousRequests = new Map();
7
+ const digest = (value) => createHash("sha256").update(value).digest("hex");
8
+
9
+ function sectionsOf(payload) {
10
+ const body = payload.request || payload;
11
+ return [
12
+ ["settings", [{ model: payload.model, tool_choice: body.tool_choice || body.toolConfig,
13
+ thinking: body.thinking || body.reasoning || body.reasoning_effort || body.generationConfig?.thinkingConfig,
14
+ effort: body.output_config?.effort }]],
15
+ ["tools", body.tools || []],
16
+ ["system", Array.isArray(body.system) ? body.system : body.systemInstruction?.parts || (body.instructions ? [body.instructions] : [])],
17
+ ["messages", body.messages || body.input || body.contents || []],
18
+ ];
19
+ }
20
+
21
+ function prefixContent(value) {
22
+ if (Array.isArray(value)) return value.map(prefixContent);
23
+ if (!value || typeof value !== "object") return value;
24
+ const { cache_control: _cache, prompt_cache_breakpoint: _breakpoint, ...content } = value;
25
+ if (Array.isArray(content.content)) content.content = prefixContent(content.content);
26
+ return content;
27
+ }
28
+
29
+ function observeWireRequest({ payload, url, transport, sessionId, requestProfile, requestScope, requestPurpose, credentials, strategyVersion = 1, startedAt }) {
30
+ const key = `${requestScope}\0${requestPurpose}\0${url}\0${transport}\0${sessionId}\0${payload.model}\0${requestProfile}\0${digest(credentials)}`;
31
+ const previous = sessionId ? previousRequests.get(key) : null;
32
+ const parts = sectionsOf(payload).flatMap(([section, values]) => values.map((value, index) => {
33
+ const content = section === "messages" && transport === "anthropic-messages" && typeof value.content === "string"
34
+ ? { ...value, content: [{ type: "text", text: value.content }] } : value;
35
+ const text = JSON.stringify(prefixContent(content));
36
+ return { section, index, digest: digest(text), estimatedTokens: Math.ceil(Buffer.byteLength(text) / 4) };
37
+ }));
38
+ let common = 0;
39
+ while (previous && common < Math.min(previous.parts.length, parts.length)) {
40
+ const a = previous.parts[common], b = parts[common];
41
+ if (a.section !== b.section || a.index !== b.index || a.digest !== b.digest) break;
42
+ common += 1;
43
+ }
44
+ const earliestChange = previous && (parts[common] || previous.parts[common]);
45
+ if (sessionId) {
46
+ previousRequests.delete(key);
47
+ previousRequests.set(key, { startedAt, parts });
48
+ if (previousRequests.size > MAX_SESSIONS) previousRequests.delete(previousRequests.keys().next().value);
49
+ }
50
+ return {
51
+ channel: requestProfile || transport,
52
+ strategyVersion,
53
+ startIntervalMs: previous ? Math.max(0, startedAt - previous.startedAt) : null,
54
+ earliestChange: earliestChange ? { section: earliestChange.section, index: earliestChange.index,
55
+ previousDigest: previous.parts[common]?.digest || null, digest: parts[common]?.digest || null } : null,
56
+ prefixDigest: digest(parts.map(part => `${part.section}:${part.digest}`).join("\n")),
57
+ commonPrefixEstimatedTokens: previous ? parts.slice(0, common).reduce((sum, part) => sum + part.estimatedTokens, 0) : null,
58
+ };
59
+ }
60
+
61
+ module.exports = { observeWireRequest };
@@ -1,8 +1,7 @@
1
1
  "use strict";
2
2
 
3
3
  const DEFAULT_RESPONSES_MAX_OUTPUT_TOKENS = 32768;
4
- const RESPONSES_REASONING_ITEMS = Symbol("ufoo.responsesReasoningItems");
5
- const RESPONSES_OUTPUT_ITEMS = Symbol("ufoo.responsesOutputItems");
4
+ const RESPONSES_CONTINUATION_VERSION = 1;
6
5
 
7
6
  function cloneJsonValue(value) {
8
7
  try {
@@ -57,45 +56,26 @@ function orderedOutputItemsFromResponse(response = null) {
57
56
  return items;
58
57
  }
59
58
 
60
- function attachResponsesReasoningItems(message = null, response = null) {
59
+ function attachResponsesReasoningItems(message, response, { model, channel, endpointKey } = {}) {
61
60
  if (!message || typeof message !== "object") return message;
62
- const items = reasoningItemsFromResponse(response);
63
- if (items.length > 0) {
64
- Object.defineProperty(message, RESPONSES_REASONING_ITEMS, {
65
- value: items,
66
- enumerable: false,
67
- configurable: false,
68
- writable: false,
69
- });
70
- }
71
- const ordered = orderedOutputItemsFromResponse(response);
72
- if (ordered.length > 0) {
73
- Object.defineProperty(message, RESPONSES_OUTPUT_ITEMS, {
74
- value: ordered,
75
- enumerable: false,
76
- configurable: false,
77
- writable: false,
78
- });
61
+ const items = orderedOutputItemsFromResponse(response);
62
+ if (items.length) {
63
+ message.responsesContinuation = { version: RESPONSES_CONTINUATION_VERSION, model, channel, endpointKey, items };
79
64
  }
80
65
  return message;
81
66
  }
82
67
 
83
- function getResponsesReasoningItems(message = null) {
84
- const items = message && typeof message === "object"
85
- ? message[RESPONSES_REASONING_ITEMS]
86
- : null;
87
- return (Array.isArray(items) ? items : [])
88
- .map(cloneJsonValue)
89
- .filter(Boolean);
68
+ function getResponsesReasoningItems(message) {
69
+ return reasoningItemsFromResponse({ output: getResponsesOutputItems(message) });
90
70
  }
91
71
 
92
- function getResponsesOutputItems(message = null) {
93
- const items = message && typeof message === "object"
94
- ? message[RESPONSES_OUTPUT_ITEMS]
95
- : null;
96
- return (Array.isArray(items) ? items : [])
97
- .map(cloneJsonValue)
98
- .filter(Boolean);
72
+ function getResponsesOutputItems(message, { model, channel, endpointKey } = {}) {
73
+ const continuation = message?.responsesContinuation;
74
+ if (continuation?.version !== RESPONSES_CONTINUATION_VERSION
75
+ || (model && continuation.model && model !== continuation.model)
76
+ || (channel && continuation.channel && channel !== continuation.channel)
77
+ || (endpointKey && continuation.endpointKey && endpointKey !== continuation.endpointKey)) return [];
78
+ return (Array.isArray(continuation.items) ? continuation.items : []).map(cloneJsonValue).filter(Boolean);
99
79
  }
100
80
 
101
81
  function resolveResponsesUrl(baseUrl = "") {
@@ -175,7 +155,7 @@ function normalizeContentParts(content, role = "user") {
175
155
  return parts;
176
156
  }
177
157
 
178
- function messagesToResponsesInput(messages = []) {
158
+ function messagesToResponsesInput(messages = [], request = {}) {
179
159
  const input = [];
180
160
  for (const message of Array.isArray(messages) ? messages : []) {
181
161
  if (!message || typeof message !== "object") continue;
@@ -193,14 +173,15 @@ function messagesToResponsesInput(messages = []) {
193
173
  continue;
194
174
  }
195
175
 
196
- if (role === "assistant" && Array.isArray(message.tool_calls)) {
176
+ const orderedItems = role === "assistant" ? getResponsesOutputItems(message, request) : [];
177
+ if (role === "assistant" && (Array.isArray(message.tool_calls) || orderedItems.length > 0)) {
197
178
  // With store=false and no previous_response_id, encrypted reasoning and
198
179
  // commentary message items must be replayed in their original order
199
180
  // before the corresponding function calls so function_call stays paired
200
181
  // with function_call_output.
201
182
  const normalizedCalls = [];
202
183
  const callsById = new Map();
203
- for (const call of message.tool_calls) {
184
+ for (const call of message.tool_calls || []) {
204
185
  if (!call || typeof call !== "object") continue;
205
186
  const fn = call.function && typeof call.function === "object" ? call.function : call;
206
187
  const callId = String(call.id || call.call_id || "").trim();
@@ -216,7 +197,6 @@ function messagesToResponsesInput(messages = []) {
216
197
  callsById.set(callId, callItem);
217
198
  }
218
199
 
219
- const orderedItems = getResponsesOutputItems(message);
220
200
  const fallbackText = normalizeContentParts(message.content, "assistant");
221
201
 
222
202
  if (orderedItems.length > 0) {
@@ -233,7 +213,9 @@ function messagesToResponsesInput(messages = []) {
233
213
  if (item.type === "message") {
234
214
  const msgParts = normalizeContentParts(item.content, "assistant");
235
215
  if (msgParts.length > 0) {
236
- turnBuffer.push({ type: "message", role: "assistant", content: msgParts });
216
+ turnBuffer.push({ type: "message", role: "assistant", content: msgParts,
217
+ ...(["commentary", "final_answer"].includes(item.phase) ? { phase: item.phase } : {}),
218
+ });
237
219
  emittedMessageText = true;
238
220
  }
239
221
  continue;
@@ -262,7 +244,6 @@ function messagesToResponsesInput(messages = []) {
262
244
  }
263
245
  input.push(...turnBuffer);
264
246
  } else {
265
- input.push(...getResponsesReasoningItems(message));
266
247
  if (fallbackText.length > 0) {
267
248
  input.push({ type: "message", role: "assistant", content: fallbackText });
268
249
  }
@@ -313,16 +294,20 @@ function toolsToResponsesTools(tools = []) {
313
294
  function buildResponsesPayload({
314
295
  model = "",
315
296
  instructions = "",
297
+ systemBlocks = null,
316
298
  messages = [],
317
299
  tools = [],
318
300
  maxOutputTokens = DEFAULT_RESPONSES_MAX_OUTPUT_TOKENS,
319
301
  reasoningEffort = "",
320
302
  provider = "",
303
+ requestProfile = "",
304
+ endpointKey = "",
305
+ strategyVersion = 1,
321
306
  } = {}) {
322
307
  const payload = {
323
308
  model: String(model || "").trim(),
324
309
  instructions: String(instructions || ""),
325
- input: messagesToResponsesInput(messages),
310
+ input: messagesToResponsesInput(messages, { model, channel: requestProfile, endpointKey }),
326
311
  max_output_tokens: Math.max(1, Number(maxOutputTokens) || DEFAULT_RESPONSES_MAX_OUTPUT_TOKENS),
327
312
  stream: true,
328
313
  store: false,
@@ -336,6 +321,23 @@ function buildResponsesPayload({
336
321
  }
337
322
 
338
323
  const normalizedProvider = String(provider || "").trim().toLowerCase();
324
+ if (strategyVersion === 2 && /^gpt-6\.2-(?:sol|astra)(?:-\d{4}-\d\d-\d\d)?$/i.test(model) && payload.instructions) {
325
+ if (requestProfile === "openai-responses") {
326
+ payload.input.unshift({ type: "message", role: "developer", content: [{ type: "input_text", text: payload.instructions }] });
327
+ delete payload.instructions;
328
+ } else if (requestProfile === "codex-subscription" && Array.isArray(systemBlocks)
329
+ && systemBlocks.map(block => block.text).join("\n\n") === payload.instructions) {
330
+ // The subscription endpoint requires top-level instructions. Only move the
331
+ // leading stable layers, leaving all subsequent guidance in original order.
332
+ let count = 0;
333
+ while (count < systemBlocks.length && ["immutable", "sessionStable"].includes(systemBlocks[count].layer)) count++;
334
+ if (count) {
335
+ const text = systemBlocks.slice(0, count).map(block => block.text).join("\n\n");
336
+ payload.input.unshift({ type: "message", role: "developer", content: [{ type: "input_text", text }] });
337
+ payload.instructions = systemBlocks.slice(count).map(block => block.text).join("\n\n") || "Follow the developer instructions in the conversation.";
338
+ }
339
+ }
340
+ }
339
341
  if (normalizedProvider === "codex" || normalizedProvider === "openai"
340
342
  || normalizedProvider === "grok-build" || normalizedProvider === "xai") {
341
343
  payload.include = ["reasoning.encrypted_content"];
@@ -406,13 +408,19 @@ function responseUsage(response = null) {
406
408
  ? details
407
409
  : {};
408
410
  const cached = inputDetails.cached_tokens ?? usage.cached_input_tokens ?? usage.cache_read_input_tokens;
409
- if (![usage.input_tokens, usage.prompt_tokens, usage.output_tokens, usage.completion_tokens, cached]
411
+ const writes = inputDetails.cache_write_tokens ?? usage.cache_creation_input_tokens ?? usage.cache_creation_tokens;
412
+ const writeDetails = inputDetails.cache_write_tokens_details;
413
+ const count = value => value != null && Number.isFinite(Number(value)) && Number(value) >= 0 ? Number(value) : null;
414
+ const ttl30m = count(writeDetails?.ttl_30m_tokens);
415
+ const ttl12h = count(writeDetails?.ttl_12h_tokens);
416
+ if (![usage.input_tokens, usage.prompt_tokens, usage.output_tokens, usage.completion_tokens, cached, writes, ttl30m, ttl12h]
410
417
  .some(value => value != null && Number.isFinite(Number(value)))) return null;
411
418
  return {
412
- input: Number(usage.input_tokens || usage.prompt_tokens || 0) || 0,
413
- output: Number(usage.output_tokens || usage.completion_tokens || 0) || 0,
414
- cacheRead: cached != null && Number.isFinite(Number(cached)) ? Number(cached) : null,
415
- cacheCreation: Number(inputDetails.cache_write_tokens ?? usage.cache_creation_input_tokens ?? usage.cache_creation_tokens ?? 0) || 0,
419
+ input: count(usage.input_tokens ?? usage.prompt_tokens),
420
+ output: count(usage.output_tokens ?? usage.completion_tokens),
421
+ cacheRead: count(cached),
422
+ cacheCreation: count(writes),
423
+ ...((ttl30m !== null || ttl12h !== null) ? { cacheWriteByTtl: { "30m": ttl30m, "12h": ttl12h } } : {}),
416
424
  inputIncludesCache: true,
417
425
  };
418
426
  }
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
 
3
3
  const { loadConfig, defaultAgentModelForProvider, sameModelProvider } = require("../../config");
4
- const { resolveRuntimeConfig } = require("./runtimeConfig");
4
+ const { resolveRuntimeConfig, resolveResponsesRequestProfile } = require("./runtimeConfig");
5
5
  const { resolveClaudeUpstreamCredentials } = require("./credentials/claude");
6
6
  const { resolveCodexUpstreamCredentials } = require("./credentials/codex");
7
7
  const { resolveKimiUpstreamCredentials } = require("./credentials/kimi");
@@ -58,7 +58,7 @@ async function resolveUpstreamRuntime({
58
58
  return {
59
59
  provider: "codex",
60
60
  transport: "codex-responses",
61
- requestProfile: useCodexOAuth ? "codex-subscription" : "openai-responses",
61
+ requestProfile: resolveResponsesRequestProfile(baseUrl, credential.credentialKind),
62
62
  model: resolvedModel,
63
63
  baseUrl,
64
64
  credential,
@@ -37,6 +37,9 @@ function resolveModelContextLimit(model = "", options = {}) {
37
37
  const override = toTokenCount(options.limit || options.contextLimit);
38
38
  if (override > 0) return override;
39
39
 
40
+ const known = resolveModelInputLimits(model, options);
41
+ if (known) return known.contextWindow;
42
+
40
43
  const id = String(model || "").trim().toLowerCase();
41
44
  if (!id) return 200000;
42
45
 
@@ -56,6 +59,12 @@ function resolveModelContextLimit(model = "", options = {}) {
56
59
  return 200000;
57
60
  }
58
61
 
62
+ function resolveModelInputLimits(model, { url = "", transport = "" } = {}) {
63
+ if (transport !== "openai-responses" || !/^https:\/\/api\.openai\.com\/v1\/responses(?:$|[?#])/.test(url)) return null;
64
+ if (/^gpt-6\.2-(?:sol|astra)(?:-\d{4}-\d\d-\d\d)?$/i.test(model)) return { contextWindow: 1_050_000, maxInputTokens: 922_000 };
65
+ return null;
66
+ }
67
+
59
68
  function formatTokensK(tokens = 0) {
60
69
  const n = Math.max(0, Math.floor(Number(tokens) || 0));
61
70
  if (n < 1000) return String(n);
@@ -116,6 +125,7 @@ module.exports = {
116
125
  toTokenCount,
117
126
  contextTokensFromUsage,
118
127
  resolveModelContextLimit,
128
+ resolveModelInputLimits,
119
129
  formatTokensK,
120
130
  formatContextMeter,
121
131
  buildContextMeter,
@@ -1,12 +1,13 @@
1
1
  "use strict";
2
2
 
3
+ const { createHash } = require("crypto");
3
4
  const { estimateTextTokens, estimateMessagesTokens, historyUnits, userInstruction } = require("./contextBudget");
4
- const { resolveModelContextLimit } = require("./contextWindow");
5
+ const { resolveModelContextLimit, resolveModelInputLimits } = require("./contextWindow");
5
6
  const { createTopicSelector } = require("./topicSelector");
6
7
  const { normalizeTopic } = require("./turnIndexStore");
7
8
  const {
8
- stripTurnContextWrapper,
9
- stripTurnContextFromContent,
9
+ TURN_CONTEXT_SOURCE,
10
+ stripTurnContextFromMessage,
10
11
  extractTextFromMessage,
11
12
  } = require("./turnAnalyzer");
12
13
 
@@ -23,6 +24,7 @@ const DEFAULT_V2_POLICY = Object.freeze({
23
24
  minKeepTurns: 2,
24
25
  maxOutputTokens: 32768,
25
26
  triggerRatio: 0.85,
27
+ compactRatio: 0.60,
26
28
  maxTurnContextRatio: 0.25,
27
29
  maxToolResultCharsLevel1: 1200,
28
30
  maxToolResultCharsLevel3: 480,
@@ -38,26 +40,14 @@ function copyOwnSymbols(source, target) {
38
40
  }
39
41
 
40
42
  function cloneMessageClean(msg) {
41
- if (!msg || typeof msg !== "object") return msg;
42
- if (msg.role !== "user") return msg;
43
- if (typeof msg.content === "string") {
44
- const stripped = stripTurnContextWrapper(msg.content);
45
- if (stripped === msg.content) return msg;
46
- return copyOwnSymbols(msg, { ...msg, content: stripped });
47
- }
48
- if (Array.isArray(msg.content)) {
49
- const stripped = stripTurnContextFromContent(msg.content);
50
- const changed = stripped.length !== msg.content.length || stripped.some((part, idx) => part !== msg.content[idx]);
51
- if (!changed) return msg;
52
- return copyOwnSymbols(msg, { ...msg, content: stripped });
53
- }
54
- return msg;
43
+ return stripTurnContextFromMessage(msg);
55
44
  }
56
45
 
57
46
  function attachTurnContextToMessage(msg, turnContextXml) {
58
47
  if (!turnContextXml || !msg || typeof msg !== "object") return msg;
59
48
  const cleaned = cloneMessageClean(msg);
60
49
  const base = cleaned === msg ? copyOwnSymbols(msg, { ...msg }) : cleaned;
50
+ Object.defineProperty(base, TURN_CONTEXT_SOURCE, { value: { originalContent: base.content } });
61
51
  if (typeof base.content === "string") {
62
52
  base.content = base.content ? `${turnContextXml}\n\n${base.content}` : turnContextXml;
63
53
  return base;
@@ -386,14 +376,7 @@ function splitHistoryAndCurrentTurn(messages = [], explicitOffset) {
386
376
  currentTurnMessages: messages.slice(explicitOffset),
387
377
  };
388
378
  }
389
- const markedIndex = messages.findIndex((msg) => {
390
- if (!msg || msg.role !== "user") return false;
391
- if (typeof msg.content === "string") return /<turn_context(?:\s+[^>]*)?>/i.test(msg.content);
392
- if (Array.isArray(msg.content)) {
393
- return msg.content.some((p) => p && p.type === "text" && typeof p.text === "string" && /<turn_context(?:\s+[^>]*)?>/i.test(p.text));
394
- }
395
- return false;
396
- });
379
+ const markedIndex = messages.findLastIndex(msg => msg?.[TURN_CONTEXT_SOURCE]);
397
380
  if (markedIndex >= 0) {
398
381
  return {
399
382
  historyOffset: markedIndex,
@@ -423,6 +406,8 @@ function createSlidingWindowManager({
423
406
  topicSelector = null,
424
407
  } = {}) {
425
408
  const cfg = { ...DEFAULT_V2_POLICY, ...policy };
409
+ // Window files from before strategy pinning already belong to a legacy session.
410
+ const strategy = state => state ? (state.strategyVersion === 2 ? 2 : 1) : (cfg.cacheStrategy === "stable-prefix" ? 2 : 1);
426
411
 
427
412
  async function prepare({
428
413
  messages = [],
@@ -430,6 +415,9 @@ function createSlidingWindowManager({
430
415
  systemPrompt = "",
431
416
  systemBlocks = null,
432
417
  tools = [],
418
+ turnSupplement = "",
419
+ transport,
420
+ request,
433
421
  historyOffset: explicitHistoryOffset,
434
422
  requestKind = "user",
435
423
  turnId = "",
@@ -457,14 +445,30 @@ function createSlidingWindowManager({
457
445
 
458
446
  let indexedTurns = [];
459
447
  let windowState = null;
460
- if (turnIndexStore && !isolated) {
461
- try { indexedTurns = turnIndexStore.listTurns(); } catch { indexedTurns = []; }
448
+ if (turnIndexStore) {
449
+ if (!isolated) {
450
+ try { indexedTurns = turnIndexStore.listTurns(); } catch { indexedTurns = []; }
451
+ }
462
452
  try { windowState = turnIndexStore.loadWindowState(); } catch { windowState = null; }
463
453
  }
464
454
 
465
- const units = partitionHistoricalMessages(historicalMessages, indexedTurns);
455
+ const strategyVersion = strategy(windowState);
456
+ if (isolated) windowState = null;
457
+ const stablePrefix = strategyVersion === 2;
458
+ const projectionScope = createHash("sha256").update(JSON.stringify([model, request?.url, request?.requestProfile, transport?.name])).digest("hex");
459
+ if (windowState?.scope && windowState.scope !== projectionScope) windowState = null;
460
+ const supplements = new Map((stablePrefix && windowState?.supplements || []).map(entry => [entry.offset, entry]));
461
+ const sourceDigest = message => createHash("sha256").update(JSON.stringify(message?.content ?? null)).digest("hex");
462
+
463
+ const historicToolLimits = new Map((stablePrefix && windowState?.toolLimits || []).map(entry => [entry.offset, entry.limits]));
464
+ const units = partitionHistoricalMessages(historicalMessages, indexedTurns).map(unit => {
465
+ const limits = historicToolLimits.get(unit.start);
466
+ return limits ? { ...unit, messages: unit.messages.map((message, index) => limits[index] ? truncateToolResultsInMessage(message, limits[index]) : message) } : unit;
467
+ });
466
468
  const limitOption = cfg.contextWindowTokens || cfg.limitTokens || Number(process.env.UFOO_CONTEXT_LIMIT_TOKENS) || 0;
467
- const modelLimit = resolveModelContextLimit(model, { limit: limitOption });
469
+ const constraints = { url: request?.url, transport: transport?.name || transport?.id };
470
+ const modelLimits = resolveModelInputLimits(model, constraints);
471
+ const modelLimit = Math.min(modelLimits?.contextWindow || Infinity, resolveModelContextLimit(model, { ...constraints, limit: limitOption }));
468
472
  const outputOverride = Number(process.env.UFOO_UCODE_MAX_TOKENS);
469
473
  const configuredOutput = Number.isFinite(outputOverride) && outputOverride > 0
470
474
  ? Math.floor(outputOverride)
@@ -473,9 +477,12 @@ function createSlidingWindowManager({
473
477
  1,
474
478
  Math.min(modelLimit - 1, cfg.outputReserveTokens ?? Math.min(configuredOutput, Math.floor(modelLimit * 0.2))),
475
479
  );
476
- const rawMaxInputTokens = Math.max(512, Math.floor((modelLimit - reserveOutput) * cfg.triggerRatio));
480
+ const explicitInputLimit = Number(cfg.maxInputTokens);
481
+ const hardInputLimit = Math.min(modelLimit - reserveOutput, modelLimits?.maxInputTokens || Infinity,
482
+ explicitInputLimit > 0 ? Math.floor(explicitInputLimit) : Infinity);
483
+ const rawMaxInputTokens = Math.min(hardInputLimit, Math.max(1, Math.floor(hardInputLimit * cfg.triggerRatio)));
477
484
 
478
- const sysTokens = systemBlocks
485
+ const sysTokens = constraints.transport === "openai-chat" ? 0 : systemBlocks?.length
479
486
  ? estimateTextTokens(JSON.stringify(systemBlocks))
480
487
  : estimateTextTokens(systemPrompt);
481
488
  const inlineSysTokens = pinnedSystemMessages.length ? estimateMessagesTokens(pinnedSystemMessages) : 0;
@@ -503,16 +510,16 @@ function createSlidingWindowManager({
503
510
  const initialHistoryBudget = Math.max(0, maxInputTokens - fixedOverhead - Math.ceil(inlineSysTokens * scaleFactor) - currentTurnTokens);
504
511
 
505
512
  // Level 0 initial window selection.
506
- let windowSelection = selectWindowUnits({
513
+ const windowSelection = selectWindowUnits({
507
514
  units,
508
515
  policy: cfg,
509
516
  windowState,
510
517
  availableHistoryBudget: initialHistoryBudget,
511
518
  });
512
519
  const sameTurnState = windowState?.cachedTurnContext?.turnId === effectiveTurnId ? windowState : null;
513
- let keptUnits = windowSelection.keptUnits;
520
+ let keptUnits = stablePrefix ? units.filter(unit => unit.start >= (windowState?.firstRetainedOffset || 0)) : windowSelection.keptUnits;
514
521
  // Once evicted in this logical turn, never restore a prefix on a later tool round.
515
- if (sameTurnState?.evictionLevel > 0 && Array.isArray(sameTurnState.keptTurnIds)) {
522
+ if (!stablePrefix && sameTurnState?.evictionLevel > 0 && Array.isArray(sameTurnState.keptTurnIds)) {
516
523
  const retained = new Set(sameTurnState.keptTurnIds);
517
524
  keptUnits = units.filter((unit) => retained.has(unit.turnId)).map((unit) => ({
518
525
  ...unit,
@@ -547,6 +554,7 @@ function createSlidingWindowManager({
547
554
  if (topicSelector && typeof topicSelector.select === "function") {
548
555
  selectionResult = await topicSelector.select({
549
556
  currentQuery: currentQueryText,
557
+ turnId,
550
558
  requestKind,
551
559
  resume,
552
560
  allTurns: indexedTurns.filter((t) => (t.historyOffset || 0) < adjustedHistoryOffset),
@@ -610,10 +618,15 @@ function createSlidingWindowManager({
610
618
  }
611
619
  };
612
620
 
621
+ let supplementalData = stablePrefix ? (canReuseCachedContext ? sameTurnState.cachedTurnContext.supplement || "" : turnSupplement) : "";
622
+ const combineSupplement = (xml) => [xml, supplementalData].filter(Boolean).join("\n\n");
613
623
  const assembleCandidate = (candidateUnits, candidateCurrent, xml) => {
614
624
  const histMsgs = [...pinnedSystemMessages];
615
625
  for (const unit of candidateUnits) {
616
- for (const msg of unit.messages) histMsgs.push(msg);
626
+ const [first, ...rest] = unit.messages;
627
+ const prior = supplements.get(unit.start);
628
+ histMsgs.push(prior && sourceDigest(first) === prior.sourceDigest ? attachTurnContextToMessage(first, prior.content) : first);
629
+ for (const message of rest) histMsgs.push(message);
617
630
  }
618
631
  if (histMsgs.length > pinnedSystemMessages.length && candidateCurrent.length > 0 && (xml || candidateCurrent.length > 1)) {
619
632
  const boundaryIdx = histMsgs.length - 1;
@@ -626,8 +639,8 @@ function createSlidingWindowManager({
626
639
  histMsgs[boundaryIdx] = boundaryMsg;
627
640
  }
628
641
  const curMsgs = candidateCurrent.slice();
629
- if (xml && curMsgs.length) {
630
- curMsgs[0] = attachTurnContextToMessage(curMsgs[0], xml);
642
+ if (combineSupplement(xml) && curMsgs[0]?.role === "user") {
643
+ curMsgs[0] = attachTurnContextToMessage(curMsgs[0], combineSupplement(xml));
631
644
  }
632
645
  const all = [...histMsgs, ...curMsgs];
633
646
  return {
@@ -643,7 +656,23 @@ function createSlidingWindowManager({
643
656
  const prevForcedLevel = force && windowState ? Number(windowState.evictionLevel || 0) : 0;
644
657
 
645
658
  // Deterministic Eviction Ladder when overflow detected or forced retry.
646
- if (force || assembled.estimatedTokens > maxInputTokens) {
659
+ if (stablePrefix && (force || initialTokens >= maxInputTokens)) {
660
+ const target = Math.max(1, Math.floor(hardInputLimit * cfg.compactRatio));
661
+ let remaining = initialTokens;
662
+ let trimmed = 0;
663
+ while (trimmed < keptUnits.length && remaining > target) {
664
+ const unit = keptUnits[trimmed];
665
+ const prior = supplements.get(unit.start);
666
+ remaining -= estTokens(unit.messages) + (prior ? estText(prior.content) : 0);
667
+ trimmed += 1;
668
+ }
669
+ if (trimmed) {
670
+ keptUnits = keptUnits.slice(trimmed);
671
+ evictionLevel = Math.max(evictionLevel, 1);
672
+ await refreshTurnContext(true);
673
+ assembled = assembleCandidate(keptUnits, workingCurrent, turnContextXml);
674
+ }
675
+ } else if (force || assembled.estimatedTokens > maxInputTokens) {
647
676
  // Level 1: Drop to minKeepTurns (2) user turns, drop system wakes in L1, truncate large older tool outputs in L1.
648
677
  evictionLevel = Math.max(evictionLevel, 1);
649
678
  const shrunkSelection = selectWindowUnits({
@@ -680,7 +709,8 @@ function createSlidingWindowManager({
680
709
  }
681
710
 
682
711
  const level2DidNotShrink = force && assembled.estimatedTokens >= Math.floor(initialTokens * 0.9);
683
- if (assembled.estimatedTokens > maxInputTokens || (force && (prevForcedLevel >= 2 || level2DidNotShrink))) {
712
+ const currentTurnLimit = stablePrefix ? hardInputLimit : maxInputTokens;
713
+ if (assembled.estimatedTokens > currentTurnLimit || (force && (prevForcedLevel >= 2 || level2DidNotShrink))) {
684
714
  // Level 3: Emergency compression of intermediate tool outputs inside currentTurnMessages (preserve round 0 user + latest round + thinking signatures).
685
715
  evictionLevel = 3;
686
716
  keptUnits = [];
@@ -707,9 +737,14 @@ function createSlidingWindowManager({
707
737
  }
708
738
  }
709
739
 
740
+ if (supplementalData && assembled.estimatedTokens > hardInputLimit) {
741
+ supplementalData = "";
742
+ assembled = assembleCandidate(keptUnits, workingCurrent, turnContextXml);
743
+ }
710
744
  const didShrink = assembled.estimatedTokens < initialTokens
711
745
  || keptUnits.length < initialKeptCount;
712
- if (assembled.estimatedTokens > maxInputTokens || (force && !didShrink)) {
746
+ const compressionReason = force ? "provider_overflow" : didShrink ? "input_budget" : null;
747
+ if (assembled.estimatedTokens > hardInputLimit || (force && !didShrink)) {
713
748
  throw Object.assign(
714
749
  new Error("context exceeds the configured input budget; original history retained"),
715
750
  { code: "context_budget_exceeded" },
@@ -732,6 +767,20 @@ function createSlidingWindowManager({
732
767
  if (turnIndexStore && !isolated) {
733
768
  try {
734
769
  turnIndexStore.saveWindowState({
770
+ version: 2,
771
+ strategyVersion,
772
+ scope: projectionScope,
773
+ firstRetainedOffset: keptUnits[0]?.start ?? adjustedHistoryOffset,
774
+ supplements: stablePrefix ? [
775
+ ...keptUnits.map(unit => supplements.get(unit.start)).filter(Boolean),
776
+ ...(currentFirstMsg?.role === "user" && combineSupplement(turnContextXml) ? [{
777
+ offset: adjustedHistoryOffset, sourceDigest: sourceDigest(currentFirstMsg), content: combineSupplement(turnContextXml),
778
+ }] : []),
779
+ ] : [],
780
+ toolLimits: stablePrefix ? [
781
+ ...keptUnits.filter(unit => historicToolLimits.has(unit.start)).map(unit => ({ offset: unit.start, limits: historicToolLimits.get(unit.start) })),
782
+ ...(Object.keys(currentToolLimits).length ? [{ offset: adjustedHistoryOffset, limits: currentToolLimits }] : []),
783
+ ] : [],
735
784
  anchorTurnId: finalAnchorTurnId,
736
785
  evictionLevel,
737
786
  currentToolLimits,
@@ -740,6 +789,7 @@ function createSlidingWindowManager({
740
789
  turnId: effectiveTurnId,
741
790
  anchorTurnId: finalAnchorTurnId,
742
791
  xml: turnContextXml,
792
+ supplement: supplementalData,
743
793
  mode: selectionResult.mode,
744
794
  activeTopics: selectionResult.activeTopics || [],
745
795
  selectedTurnIds: (selectionResult.selectedTurns || []).map((t) => t.turnId),
@@ -771,6 +821,10 @@ function createSlidingWindowManager({
771
821
  maxOutputTokens: reserveOutput,
772
822
  meta: {
773
823
  evictionLevel,
824
+ compressionReason,
825
+ strategyVersion,
826
+ contextWindow: modelLimit,
827
+ hardInputLimit,
774
828
  rawTurnCount: keptUnits.length,
775
829
  offWindowCount: offWindowTurns.length,
776
830
  selectionMode: selectionResult.mode,
@@ -779,7 +833,9 @@ function createSlidingWindowManager({
779
833
  };
780
834
  }
781
835
 
782
- return Object.freeze({ prepare });
836
+ return Object.freeze({ prepare, strategyVersion() {
837
+ try { return strategy(turnIndexStore?.loadWindowState()); } catch { return strategy(null); }
838
+ } });
783
839
  }
784
840
 
785
841
  module.exports = {
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
 
3
3
  const { normalizeTopic, tokenizeForSearch } = require("./turnIndexStore");
4
- const { stripTurnContextWrapper, parseJsonObjectLenient } = require("./turnAnalyzer");
4
+ const { parseJsonObjectLenient } = require("./turnAnalyzer");
5
5
 
6
6
  const TEMPORAL_ANCHORS = [
7
7
  /刚才|刚刚|上一步|上一个|上一轮|前面|之前那个|刚才那个|上面那个/,
@@ -33,6 +33,7 @@ function createTopicSelector({
33
33
  } = {}) {
34
34
  async function select({
35
35
  currentQuery = "",
36
+ turnId = "",
36
37
  requestKind = "user",
37
38
  resume = false,
38
39
  allTurns = [],
@@ -42,7 +43,7 @@ function createTopicSelector({
42
43
  signal = null,
43
44
  } = {}) {
44
45
  const startMs = Date.now();
45
- const cleanedQuery = stripTurnContextWrapper(String(currentQuery || "")).trim();
46
+ const cleanedQuery = String(currentQuery || "").trim();
46
47
  const turns = Array.isArray(allTurns) ? allTurns.slice().sort((a, b) => (a.turnIndex || 0) - (b.turnIndex || 0)) : [];
47
48
  const inWindow = new Set(windowTurnIds || []);
48
49
  const offWindowTurns = turns.filter((t) => t && !inWindow.has(t.turnId));
@@ -257,6 +258,7 @@ function createTopicSelector({
257
258
  }));
258
259
  const raw = await runAuxModel({
259
260
  purpose: "topic_select",
261
+ turnId,
260
262
  currentQuery: cleanedQuery,
261
263
  activeTopics,
262
264
  candidates: candidateTurns,