u-foo 4.0.0 → 4.0.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 (158) hide show
  1. package/OBSERVABILITY.md +65 -0
  2. package/README.md +90 -30
  3. package/README.zh-CN.md +76 -26
  4. package/SKILLS/ufoo/SKILL.md +25 -1
  5. package/SKILLS/ufoo-bus/SKILL.md +25 -2
  6. package/bin/ucode.js +4 -0
  7. package/bin/ufoo.js +3 -3
  8. package/dist/tui/darwin-arm64/ufoo-tui +0 -0
  9. package/dist/tui/darwin-x64/ufoo-tui +0 -0
  10. package/dist/tui/linux-arm64/ufoo-tui +0 -0
  11. package/dist/tui/linux-x64/ufoo-tui +0 -0
  12. package/package.json +6 -6
  13. package/src/agents/activity/activityDetector.js +1 -1
  14. package/src/agents/capabilities/agentManagement/service.js +40 -13
  15. package/src/agents/capabilities/coordination/index.js +1 -1
  16. package/src/agents/capabilities/taskReports/index.js +1 -1
  17. package/src/agents/controller/controllerToolExecutor.js +36 -20
  18. package/src/agents/controller/index.js +1 -6
  19. package/src/agents/internal/internalRunner.js +90 -56
  20. package/src/agents/launch/index.js +0 -1
  21. package/src/agents/launch/launcher.js +38 -29
  22. package/src/agents/launch/launcherReadiness.js +35 -0
  23. package/src/agents/launch/notifier.js +2 -2
  24. package/src/agents/launch/ptyWrapper.js +5 -2
  25. package/src/agents/launch/readyDetector.js +2 -2
  26. package/src/agents/profiles/main.js +1 -1
  27. package/src/agents/prompts/cooperation.js +14 -0
  28. package/src/agents/prompts/defaultBootstrap.js +1 -1
  29. package/src/agents/prompts/groupBootstrap.js +23 -7
  30. package/src/agents/prompts/mainAgent.js +11 -2
  31. package/src/agents/prompts/native/system.js +4 -1
  32. package/src/agents/prompts/native/ufoo.js +11 -3
  33. package/src/agents/prompts/promptProfiles.js +2 -0
  34. package/src/agents/prompts/reporting.js +16 -0
  35. package/src/agents/providers/claudeEventTranslator.js +3 -0
  36. package/src/agents/providers/claudeThreadProvider.js +3 -2
  37. package/src/agents/providers/clientIdentity.js +75 -0
  38. package/src/agents/providers/codexEventTranslator.js +23 -2
  39. package/src/agents/providers/codexThreadProvider.js +15 -6
  40. package/src/agents/providers/credentials/index.js +2 -0
  41. package/src/agents/providers/directAuthStatus.js +1 -1
  42. package/src/agents/providers/index.js +1 -1
  43. package/src/agents/providers/modelSettings.js +34 -0
  44. package/src/agents/providers/modelsCatalog.js +379 -0
  45. package/src/agents/providers/nativeTransport.js +58 -40
  46. package/src/agents/providers/runtimeConfig.js +10 -8
  47. package/src/agents/providers/thinkingLevels.js +10 -36
  48. package/src/agents/providers/transports/responsesProtocol.js +11 -6
  49. package/src/agents/providers/upstreamRuntime.js +135 -0
  50. package/src/agents/runtime/context/checkpointStore.js +38 -0
  51. package/src/agents/runtime/context/compaction.js +151 -0
  52. package/src/agents/runtime/context/contextBudget.js +93 -0
  53. package/src/agents/runtime/context/replayHistory.js +28 -0
  54. package/src/agents/runtime/context/runtimeStore.js +2 -1
  55. package/src/agents/runtime/core/agentLoop.js +99 -18
  56. package/src/agents/runtime/core/executionBudget.js +36 -0
  57. package/src/agents/runtime/createAgentRuntime.js +16 -4
  58. package/src/agents/runtime/prompts/responseLanguage.js +12 -0
  59. package/src/agents/runtime/protocol/runObservation.js +24 -0
  60. package/src/agents/runtime/protocol/traceContext.js +9 -0
  61. package/src/app/chat/ChatController.js +26 -53
  62. package/src/app/chat/agentDirectory.js +1 -16
  63. package/src/app/chat/bootstrap.js +1 -2
  64. package/src/app/chat/commandExecutor.js +93 -285
  65. package/src/app/chat/commands.js +32 -45
  66. package/src/app/chat/daemonMessageRouter.js +0 -45
  67. package/src/app/chat/historyStore.js +12 -48
  68. package/src/app/chat/inputSubmitHandler.js +7 -33
  69. package/src/app/chat/internalAgentLogHistory.js +19 -60
  70. package/src/app/chat/multiWindow/paneManager.js +10 -3
  71. package/src/app/chat/streamState.js +0 -4
  72. package/src/app/cli/features/init.js +5 -5
  73. package/src/app/cli/metricsCommands.js +68 -0
  74. package/src/app/cli/run.js +42 -3
  75. package/src/app/cli/traceCommands.js +36 -0
  76. package/src/code/agent.js +18 -13
  77. package/src/code/busConsumer.js +1 -3
  78. package/src/code/commands.js +1 -1
  79. package/src/code/context/assembler.js +7 -8
  80. package/src/code/context/stateCommit.js +2 -1
  81. package/src/code/internalThread.js +10 -3
  82. package/src/code/launcher/ucode.js +1 -1
  83. package/src/code/launcher/ucodeBootstrap.js +1 -1
  84. package/src/code/modelCommand.js +11 -35
  85. package/src/code/nativeRunner.js +55 -17
  86. package/src/code/providers/modelsCatalog.js +1 -317
  87. package/src/code/repl.js +4 -11
  88. package/src/code/sessionStore.js +3 -3
  89. package/src/code/taskDecomposer.js +18 -0
  90. package/src/code/toolBudget.js +1 -17
  91. package/src/config.js +22 -72
  92. package/src/coordination/bus/index.js +12 -3
  93. package/src/coordination/bus/inject.js +2 -2
  94. package/src/coordination/bus/message.js +15 -1
  95. package/src/coordination/bus/nickname.js +1 -1
  96. package/src/coordination/bus/subscriber.js +3 -2
  97. package/src/coordination/bus/utils.js +1 -1
  98. package/src/coordination/history/agentPerformance.js +279 -0
  99. package/src/coordination/history/agentTrace.js +249 -0
  100. package/src/coordination/state/workspaceAccess.js +1 -1
  101. package/src/orchestration/controller/index.js +1 -8
  102. package/src/orchestration/controller/launchRouting.js +1 -1
  103. package/src/orchestration/solo/commands.js +3 -1
  104. package/src/runtime/contracts/agentMode.js +11 -2
  105. package/src/runtime/contracts/uiProtocol.js +18 -19
  106. package/src/runtime/daemon/agentHost.js +57 -25
  107. package/src/runtime/daemon/agentRecoveryGroups.js +70 -0
  108. package/src/runtime/daemon/busBridge.js +1 -1
  109. package/src/runtime/daemon/controlPlaneService.js +1 -1
  110. package/src/runtime/daemon/groupOrchestrator.js +20 -5
  111. package/src/runtime/daemon/groupStatus.js +20 -0
  112. package/src/runtime/daemon/index.js +19 -44
  113. package/src/runtime/daemon/mcpHttpServer.js +39 -10
  114. package/src/runtime/daemon/mcpServer.js +1 -1
  115. package/src/runtime/daemon/nicknameScope.js +1 -1
  116. package/src/runtime/daemon/ops.js +46 -23
  117. package/src/runtime/daemon/projectRuntimeGateway.js +2 -0
  118. package/src/runtime/daemon/promptRequest.js +92 -589
  119. package/src/runtime/daemon/status.js +5 -6
  120. package/src/tools/controllerSchemas.js +6 -2
  121. package/src/tools/handlers/tier2.js +4 -2
  122. package/src/tools/registry.js +4 -0
  123. package/src/tools/schemaFixtures.js +26 -2
  124. package/src/tools/tier0/readAgentMetrics.js +14 -0
  125. package/src/tools/tier0/readAgentTrace.js +12 -0
  126. package/src/ui/agentSettingsController.js +107 -0
  127. package/src/ui/agentSurface.js +1 -1
  128. package/src/ui/dashboardBridge.js +1 -1
  129. package/src/ui/format/banner.js +1 -4
  130. package/src/ui/format/index.js +14 -10
  131. package/src/ui/format/loopSummary.js +50 -0
  132. package/src/ui/format/markdownRenderer.js +3 -4
  133. package/src/ui/rustChatHost.js +191 -206
  134. package/src/ui/rustMultiSession.js +77 -36
  135. package/src/ui/rustUcodeHost.js +6 -1
  136. package/src/ui/settingsBridge.js +33 -16
  137. package/src/ui/toolMergeBridge.js +0 -4
  138. package/src/ui/uiHostServer.js +5 -8
  139. package/src/agents/controller/loopObservability.js +0 -200
  140. package/src/agents/controller/loopRuntime.js +0 -336
  141. package/src/agents/controller/ufooAgent.js +0 -830
  142. package/src/agents/launch/ptyRunner.js +0 -1135
  143. package/src/agents/providers/controllerJsonTransport.js +0 -28
  144. package/src/agents/providers/upstreamTransport.js +0 -698
  145. package/src/app/chat/agentBar.js +0 -135
  146. package/src/app/chat/agentSockets.js +0 -225
  147. package/src/app/chat/dashboardView.js +0 -405
  148. package/src/app/chat/rawKeyMap.js +0 -42
  149. package/src/app/chat/settingsController.js +0 -111
  150. package/src/coordination/history/controllerSummary.js +0 -23
  151. package/src/orchestration/controller/flags.js +0 -167
  152. package/src/orchestration/controller/gateRouter.js +0 -211
  153. package/src/orchestration/controller/routerFastPath.js +0 -22
  154. package/src/orchestration/controller/routerFinalize.js +0 -222
  155. package/src/orchestration/controller/shadowGuard.js +0 -280
  156. package/src/runtime/daemon/executionPaths.js +0 -30
  157. package/src/runtime/daemon/promptLoop.js +0 -136
  158. package/src/runtime/privacy/shadowDiff.js +0 -174
@@ -771,7 +771,7 @@ async function runCli(argv) {
771
771
  normalizedAgent = "grok";
772
772
  } else if (agentLower === "ukimi" || agentLower === "kimi" || agentLower === "kimi-cli" || agentLower === "kimi-code") {
773
773
  normalizedAgent = "kimi";
774
- } else if (agentLower === "ucode" || agentLower === "ufoo-code" || agentLower === "ufoo") {
774
+ } else if (agentLower === "ucode") {
775
775
  normalizedAgent = "ucode";
776
776
  } else {
777
777
  console.error(`Unknown agent type: ${agent}`);
@@ -845,7 +845,7 @@ async function runCli(argv) {
845
845
  }
846
846
  const resp = await sendDaemonRequest(projectRoot, {
847
847
  type: "launch_agent",
848
- agent: agent === "ucode" ? "ufoo" : agent,
848
+ agent,
849
849
  nickname: String(opts.nickname || "").trim(),
850
850
  prompt_profile: promptProfile,
851
851
  count: 1,
@@ -1702,6 +1702,35 @@ async function runCli(argv) {
1702
1702
  }
1703
1703
  });
1704
1704
 
1705
+ program.command("trace").description("Inspect agent task, tool, report, queue and compaction events")
1706
+ .argument("[task-id]", "Delegated task ID or parent taskRunId")
1707
+ .option("--task <id>", "Filter task")
1708
+ .option("--agent <id>", "Filter subscriber ID or nickname")
1709
+ .option("--session <id>", "Filter runtime session")
1710
+ .option("--project <path>", "Project root (defaults to cwd)")
1711
+ .option("--since <time>", "ISO timestamp lower bound")
1712
+ .option("--limit <n>", "Maximum events (default: 200, follow: 2000)")
1713
+ .option("--offset <n>", "Oldest-first pagination offset; default shows newest events")
1714
+ .option("--details", "Include redacted arguments and results")
1715
+ .option("--json", "JSON output; with --follow emits JSONL")
1716
+ .option("--follow", "Observe new local events without model calls")
1717
+ .action((taskId, opts) => require("./traceCommands").runTraceCommand(taskId, opts));
1718
+
1719
+ program.command("metrics").description("Summarize observed agent performance without model calls")
1720
+ .argument("[task-id]", "Delegated task ID or parent taskRunId")
1721
+ .option("--task <id>", "Filter task")
1722
+ .option("--agent <id>", "Filter subscriber ID or nickname")
1723
+ .option("--session <id>", "Filter runtime session")
1724
+ .option("--project <path>", "Project root (defaults to cwd)")
1725
+ .option("--since <time>", "Include runs starting at or after ISO timestamp")
1726
+ .option("--until <time>", "Include runs starting before ISO timestamp")
1727
+ .option("--provider <name>", "Filter observed model provider")
1728
+ .option("--model <name>", "Filter observed model")
1729
+ .option("--limit <n>", "Recent run records to return (default: 20; maximum: 100)")
1730
+ .option("--baseline <path>", "Compare with a saved metrics JSON report")
1731
+ .option("--json", "Export a performance report")
1732
+ .action((taskId, opts) => require("./metricsCommands").runMetricsCommand(taskId, opts));
1733
+
1705
1734
  const history = program.command("history").description("Agent input history timeline");
1706
1735
  history
1707
1736
  .command("build")
@@ -1802,6 +1831,7 @@ async function runCli(argv) {
1802
1831
  console.log(" ufoo bus <args...> (JS bus implementation)");
1803
1832
  console.log(" ufoo ctx <subcmd> ... (doctor|lint|decisions|sync)");
1804
1833
  console.log(" ufoo history <build|show|prompt> [limit]");
1834
+ console.log(" ufoo trace [task-id] [--agent <id>] [--project <dir>] [--json] [--follow] [--details]");
1805
1835
  console.log("");
1806
1836
  console.log("Notes:");
1807
1837
  console.log(" - For Codex notifications, use ufoo bus alert / ufoo bus listen");
@@ -1936,6 +1966,15 @@ async function runCli(argv) {
1936
1966
  })();
1937
1967
  return;
1938
1968
  }
1969
+ if (cmd === "trace") {
1970
+ const value = name => { const i = rest.indexOf(`--${name}`); return i < 0 ? undefined : rest[i + 1]; };
1971
+ const task = rest[0]?.startsWith("--") ? "" : rest[0];
1972
+ try { require("./traceCommands").runTraceCommand(task, {
1973
+ task: value("task"), agent: value("agent"), session: value("session"), project: value("project"), since: value("since"),
1974
+ limit: value("limit"), offset: value("offset"), json: rest.includes("--json"), follow: rest.includes("--follow"), details: rest.includes("--details"),
1975
+ }); } catch (error) { console.error(error.message); process.exitCode = 1; }
1976
+ return;
1977
+ }
1939
1978
  if (cmd === "report") {
1940
1979
  const action = String(rest[0] || "").toLowerCase();
1941
1980
  const normalized = normalizeReportPhase(action);
@@ -2345,7 +2384,7 @@ async function runCli(argv) {
2345
2384
  const agent = resolveSoloAgentType(config, agentInput);
2346
2385
  const resp = await sendDaemonRequest(projectRoot, {
2347
2386
  type: "launch_agent",
2348
- agent: agent === "ucode" ? "ufoo" : agent,
2387
+ agent,
2349
2388
  nickname,
2350
2389
  prompt_profile: profile,
2351
2390
  count: 1,
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ const { readAgentTrace } = require("../../coordination/history/agentTrace");
3
+ function runTraceCommand(taskId, options = {}) {
4
+ const query = { task_id: options.task || taskId || "", agent_id: options.agent, session_id: options.session, since: options.since,
5
+ limit: options.limit || (options.follow ? 2000 : 200), offset: options.offset, details: options.details === true };
6
+ const root = options.project || process.cwd();
7
+ const seen = new Set();
8
+ let state = "";
9
+ const emit = () => {
10
+ const result = readAgentTrace(root, query);
11
+ if (options.json && !options.follow) { console.log(JSON.stringify(result, null, 2)); return; }
12
+ const signature = JSON.stringify({ tasks: result.tasks.map(t => [t.taskId || t.id, t.status, t.reportPhase || t.report?.phase]),
13
+ counts: result.counts, outcomes: result.performance.summary.outcomes, queues: result.queues, warnings: result.warnings });
14
+ if (signature !== state) {
15
+ if (options.json) console.log(JSON.stringify({ type: "trace.state", projectRoot: result.projectRoot, tasks: result.tasks,
16
+ counts: result.counts, performance: result.performance, queues: result.queues, warnings: result.warnings }));
17
+ else console.log(`Trace: ${result.total} events; ${result.tasks.map(t => `${t.taskId || t.id}=${t.status}`).join(", ") || "no delegated tasks"}${result.incomplete ? " (partial sources; use --json for warnings)" : ""}`);
18
+ state = signature;
19
+ }
20
+ for (const e of result.events) {
21
+ if (seen.has(e.id)) continue;
22
+ seen.add(e.id);
23
+ console.log(options.json ? JSON.stringify(e) : `${e.time} ${e.agentId || "runtime"} ${e.type} ${e.toolName || ""} ${e.summary || ""}${e.durationMs === undefined ? "" : ` (${e.durationMs}ms)`}`);
24
+ if (!options.json && options.details && (e.args || e.result)) console.log(JSON.stringify({ args: e.args, result: e.result }));
25
+ }
26
+ // Bound a long-lived follower's memory; retain the most recent event IDs.
27
+ if (seen.size > 10000) for (const id of [...seen].slice(0, seen.size - 10000)) seen.delete(id);
28
+ };
29
+ emit();
30
+ if (!options.follow) return;
31
+ const timer = setInterval(() => { try { emit(); } catch (error) { console.error(error.message); } }, 1000);
32
+ const stop = () => { clearInterval(timer); process.removeListener("SIGINT", stop); process.removeListener("SIGTERM", stop); };
33
+ process.once("SIGINT", stop); process.once("SIGTERM", stop);
34
+ return stop;
35
+ }
36
+ module.exports = { runTraceCommand };
package/src/code/agent.js CHANGED
@@ -3,6 +3,7 @@ const path = require("path");
3
3
  const { randomUUID } = require("crypto");
4
4
  const { runToolCall } = require("./dispatch");
5
5
  const { runNativeAgentTask } = require("./nativeRunner");
6
+ const { resolveTaskTimeoutMs: resolveNlTaskTimeoutMs, DEFAULT_TASK_TIMEOUT_MS: DEFAULT_NL_TASK_TIMEOUT_MS } = require("../agents/runtime/core/executionBudget");
6
7
  const { runDecomposedTask } = require("./taskDecomposer");
7
8
  const { loadConfig, defaultAgentModelForProvider, sameModelProvider } = require("../config");
8
9
  const {
@@ -336,18 +337,6 @@ function computeExtendedTimeout(baseTimeoutMs) {
336
337
  return Math.min(43200000, Math.max(base * 2, base + 120000));
337
338
  }
338
339
 
339
- // Reasoning models routinely blew the old 10min budget across a multi-turn
340
- // tool loop. Total per-task budget defaults to 12h and can be raised per
341
- // call, via --timeout-ms, or via UFOO_UCODE_TASK_TIMEOUT_MS.
342
- const DEFAULT_NL_TASK_TIMEOUT_MS = 43200000;
343
-
344
- function resolveNlTaskTimeoutMs(value) {
345
- if (Number.isFinite(value) && value > 0) return Math.max(1000, Math.floor(value));
346
- const env = Number(process.env.UFOO_UCODE_TASK_TIMEOUT_MS);
347
- if (Number.isFinite(env) && env > 0) return Math.max(1000, Math.floor(env));
348
- return DEFAULT_NL_TASK_TIMEOUT_MS;
349
- }
350
-
351
340
  function enrichNativeError(errorMessage = "") {
352
341
  const text = String(errorMessage || "").trim();
353
342
  if (!text) return "nl task failed";
@@ -363,7 +352,7 @@ function enrichNativeError(errorMessage = "") {
363
352
  return `${text}. Network connection to provider failed. Check VPN/proxy/network and verify endpoint/key via /settings ucode show.`;
364
353
  }
365
354
  if (lower.includes("model is not configured")) {
366
- return `${text}. Configure ucode with /settings ucode set provider=<openai|anthropic> model=<id> key=<apiKey> [url=<baseUrl>]`;
355
+ return `${text}. Configure ucode with /settings ucode set provider=openai model=<id> key=<apiKey> [url=<baseUrl>]`;
367
356
  }
368
357
  if (lower.includes("baseurl is not configured")) {
369
358
  return `${text}. Configure endpoint with /settings ucode set url=<baseUrl> (and key/model if missing).`;
@@ -675,6 +664,9 @@ async function runNaturalLanguageTask(task = "", state = {}, options = {}) {
675
664
  onContextUsage: applyContextMeter,
676
665
  executionState: state.executionState || null,
677
666
  onArtifactPersisted: (persisted) => recordToolCallInSession(state, persisted, workspaceRoot),
667
+ contextPolicy: state.contextPolicy || {},
668
+ runtimeContext: options.runtimeContext || {},
669
+ onRuntimeEvent: options.onRuntimeEvent,
678
670
  onToolEvent: (event) => {
679
671
  toolEventsThisAttempt += 1;
680
672
  pushToolLog(event);
@@ -730,6 +722,13 @@ async function runNaturalLanguageTask(task = "", state = {}, options = {}) {
730
722
  sessionId: String(state.sessionId || ""),
731
723
  state,
732
724
  systemBlocks: assembled.systemBlocks || null,
725
+ runtimeContext: options.runtimeContext || {},
726
+ onRuntimeEvent: options.onRuntimeEvent,
727
+ onStreamDelta: onStream,
728
+ onThinkingDelta,
729
+ onPhase,
730
+ onContextUsage: applyContextMeter,
731
+ contextPolicy: state.contextPolicy || {},
733
732
  });
734
733
 
735
734
  if (decomposedResult.ok) {
@@ -849,6 +848,7 @@ async function runNaturalLanguageTask(task = "", state = {}, options = {}) {
849
848
  return {
850
849
  ok: true,
851
850
  summary: resolvedSummary || "Waiting for your reply",
851
+ finalText: typeof cliRes.finalText === "string" ? extractJsonSummary(cliRes.finalText) : undefined,
852
852
  artifacts: artifactIds,
853
853
  logs: logs.slice(),
854
854
  error: "",
@@ -864,6 +864,7 @@ async function runNaturalLanguageTask(task = "", state = {}, options = {}) {
864
864
  return {
865
865
  ok: true,
866
866
  summary: resolvedSummary,
867
+ finalText: typeof cliRes.finalText === "string" ? extractJsonSummary(cliRes.finalText) : undefined,
867
868
  artifacts: artifactIds,
868
869
  logs: logs.slice(),
869
870
  error: "",
@@ -1193,6 +1194,9 @@ async function resumeAfterUserInteraction(answerText = "", state = {}, options =
1193
1194
  },
1194
1195
  maxToolCalls: state.maxToolCalls,
1195
1196
  onStreamDelta: trackingOnDelta,
1197
+ contextPolicy: state.contextPolicy || {},
1198
+ runtimeContext: options.runtimeContext || {},
1199
+ onRuntimeEvent: options.onRuntimeEvent,
1196
1200
  onThinkingDelta: typeof options.onThinkingDelta === "function" ? options.onThinkingDelta : null,
1197
1201
  onPhase: typeof options.onPhase === "function" ? options.onPhase : null,
1198
1202
  onContextUsage: (meter) => {
@@ -1266,6 +1270,7 @@ async function resumeAfterUserInteraction(answerText = "", state = {}, options =
1266
1270
  return {
1267
1271
  ok: true,
1268
1272
  summary: String(cliRes.output || "").trim() || "continued",
1273
+ finalText: typeof cliRes.finalText === "string" ? extractJsonSummary(cliRes.finalText) : undefined,
1269
1274
  logs,
1270
1275
  waitingUserInteraction: false,
1271
1276
  streamed: Boolean(cliRes.streamed),
@@ -221,9 +221,7 @@ function extractTaskFromBusEvent(evt) {
221
221
  function shouldAutoConsumeBus(subscriberId = "") {
222
222
  const id = String(subscriberId || "").trim().toLowerCase();
223
223
  if (!id) return false;
224
- return id.startsWith("ufoo-code:")
225
- || id.startsWith("ucode:")
226
- || id.startsWith("ufoo:");
224
+ return id.startsWith("ucode:");
227
225
  }
228
226
 
229
227
  function extractBusMessageTask(contentRaw = "") {
@@ -72,7 +72,7 @@ function listUcodeCommandsForHelp() {
72
72
  " /ubus",
73
73
  " /status",
74
74
  " /queue [status|clear|cancel|stop]",
75
- " /model [model-id] [off|low|medium|high|max]",
75
+ " /model [model-id] [off|low|medium|high|xhigh|max]",
76
76
  " /plan [on|off|show|hide|focus|debug|clear]",
77
77
  " /skills [list]",
78
78
  " /skills show <name>",
@@ -34,6 +34,7 @@ const { renderExecutionSegmentContext } = require("./executionSegment");
34
34
  const { renderPlanModeContext } = require("./planMode");
35
35
  const { drainAgentMailboxForTurn } = require("../runtime/agentWakeup");
36
36
  const { stripVisionBase64, degradeVisionContent } = require("../providers/visionBlocks");
37
+ const { DEFAULT_CONTEXT_POLICY } = require("../../agents/runtime/context/compaction");
37
38
 
38
39
  const DEFAULT_TRANSCRIPT_WINDOW = 12;
39
40
  const DEFAULT_RECENT_TOOL_EVENTS = 4;
@@ -46,7 +47,7 @@ function resolveTranscriptWindow(env = process.env) {
46
47
 
47
48
  function defaultContextPolicy(env = process.env) {
48
49
  return {
49
- transcriptWindow: resolveTranscriptWindow(env),
50
+ ...DEFAULT_CONTEXT_POLICY,
50
51
  commitInterval: resolveCommitInterval(env),
51
52
  };
52
53
  }
@@ -389,14 +390,12 @@ function ensureTranscript(session = {}, workspaceRoot = process.cwd()) {
389
390
 
390
391
  function assembleModelContext(session = {}, request = {}, env = process.env) {
391
392
  const workspaceRoot = String(session.workspaceRoot || request.workspaceRoot || process.cwd());
392
- const policy = {
393
- ...defaultContextPolicy(env),
394
- ...(session.contextPolicy && typeof session.contextPolicy === "object" ? session.contextPolicy : {}),
395
- };
393
+ const policy = { ...defaultContextPolicy(env), ...(session.contextPolicy || {}) };
396
394
  session.workingSet = pruneWorkingSetByRetention(session.workingSet, session);
397
395
  const transcriptEvents = ensureTranscript(session, workspaceRoot);
398
- const windowSize = policy.transcriptWindow || DEFAULT_TRANSCRIPT_WINDOW;
399
- const summary = buildRollingSummary(transcriptEvents, session.summary, session);
396
+ // Semantic checkpointing lives in shared runtime, before each model call.
397
+ // Do not silently replace older conversation with a deterministic digest.
398
+ const summary = "";
400
399
 
401
400
  const layered = buildLayeredSystemPrompt({
402
401
  workspaceRoot,
@@ -428,7 +427,7 @@ function assembleModelContext(session = {}, request = {}, env = process.env) {
428
427
  sessionStableExtras: request.sessionStableExtras || "",
429
428
  });
430
429
 
431
- const recentMessages = buildRecentMessages(transcriptEvents, windowSize, session);
430
+ const recentMessages = sanitizeModelMessages(transcriptEventsToMessages(transcriptEvents, { preferArtifact: true }));
432
431
 
433
432
  return {
434
433
  systemPrompt: layered.flatText,
@@ -170,7 +170,8 @@ function renderStateEpoch(stateEpoch = null) {
170
170
  "State Snapshot:",
171
171
  `- Phase: ${snap.phase || "active"}`,
172
172
  snap.currentObjective ? `- Current objective: ${snap.currentObjective}` : "",
173
- snap.facts && snap.facts.length > 0 ? `- Facts: ${snap.facts.join("; ")}` : "",
173
+ snap.facts && snap.facts.length > 0 ? `- Recent facts: ${snap.facts.slice(-40).join("; ")}` : "",
174
+ snap.facts && snap.facts.length > 40 ? `- ${snap.facts.length - 40} older facts remain in durable state, conversation history and referenced artifacts.` : "",
174
175
  snap.hypotheses && snap.hypotheses.length > 0 ? `- Hypotheses: ${snap.hypotheses.join("; ")}` : "",
175
176
  snap.decisions && snap.decisions.length > 0 ? `- Decisions: ${snap.decisions.join("; ")}` : "",
176
177
  snap.openQuestions && snap.openQuestions.length > 0 ? `- Open questions: ${snap.openQuestions.join("; ")}` : "",
@@ -13,7 +13,10 @@ function createInternalCodingThread(options = {}) {
13
13
  context: agent.buildNlContext({ workspaceRoot, ...resolved }),
14
14
  nlMessages: [], sessionId: options.sessionId || `ucode-${randomUUID()}`,
15
15
  };
16
- if (options.sessionId) agent.resumeSessionState(state, options.sessionId, workspaceRoot);
16
+ if (options.sessionId) {
17
+ const restored = agent.resumeSessionState(state, options.sessionId, workspaceRoot);
18
+ if (restored?.ok === false) throw new Error(restored.error || `Could not resume session: ${options.sessionId}`);
19
+ }
17
20
  let abort = null;
18
21
 
19
22
  async function* runStreamed(input, runOptions = {}) {
@@ -33,6 +36,8 @@ function createInternalCodingThread(options = {}) {
33
36
  const publishPlan = () => push({ type: "plan", ...buildPlanSetPayload(state.executionState) });
34
37
  const callbacks = {
35
38
  signal: controller.signal,
39
+ runtimeContext: runOptions.runtimeContext || {},
40
+ onRuntimeEvent: event => push({ type: "runtime_event", event }),
36
41
  onDelta: (delta) => push({ type: "text_delta", delta }),
37
42
  onThinkingDelta: (delta) => push({ type: "thinking_delta", delta }),
38
43
  onPhase: (phase) => push({ type: "phase", phase }),
@@ -41,7 +46,7 @@ function createInternalCodingThread(options = {}) {
41
46
  const key = JSON.stringify([event.tool, event.args || {}, event.origin || null]);
42
47
  const stack = activeTools.get(key) || [];
43
48
  if (event.phase === "start") {
44
- const id = String(event.callId || event.toolCallId || event.id || `native-tool-${++toolSequence}`);
49
+ const id = String(event.callId || event.toolCallId || event.id || `native-tool-${randomUUID()}`);
45
50
  stack.push(id); activeTools.set(key, stack);
46
51
  push({ type: "tool_call", toolCallId: id, name: event.tool, args: event.args });
47
52
  } else if (event.phase === "end" || event.phase === "error") {
@@ -75,7 +80,9 @@ function createInternalCodingThread(options = {}) {
75
80
  if (!options.runTask) agent.persistSessionState(state);
76
81
  publishPlan();
77
82
  if (result?.contextMeter || state.contextMeter) push({ type: "context_usage", meter: result?.contextMeter || state.contextMeter });
78
- push({ type: "turn_completed", usage: result?.usage || result?.metrics || null });
83
+ const finalText = result?.finalText ?? result?.summary;
84
+ push({ type: "turn_completed", usage: result?.usage || result?.metrics || null,
85
+ ...(typeof finalText === "string" ? { finalText } : {}) });
79
86
  }).catch((error) => { failure = error; }).finally(() => {
80
87
  done = true;
81
88
  if (wake) { wake(); wake = null; }
@@ -140,7 +140,7 @@ function resolveUcodeLaunch({
140
140
  const effectiveModel = readLastArgValue(finalArgs, "--model");
141
141
 
142
142
  return {
143
- agentType: "ufoo-code",
143
+ agentType: "ucode",
144
144
  command,
145
145
  args: finalArgs,
146
146
  env: {
@@ -80,7 +80,7 @@ function mergeDefaultUfooProtocolPrompt(projectRoot = "", promptText = "") {
80
80
  const currentPrompt = String(promptText || "").trim();
81
81
  if (hasSharedUfooProtocolPrompt(currentPrompt)) return currentPrompt;
82
82
  const defaultPrompt = buildDefaultStartupBootstrapPrompt({
83
- agentType: "ufoo-code",
83
+ agentType: "ucode",
84
84
  projectRoot,
85
85
  }).trim();
86
86
  return [defaultPrompt, currentPrompt].filter(Boolean).join("\n\n");
@@ -13,17 +13,6 @@ const {
13
13
  DEFAULT_THINKING_LEVEL,
14
14
  } = require("./thinkingLevels");
15
15
 
16
- function fallbackModelSuggestions(provider = "") {
17
- const text = String(provider || "").trim().toLowerCase();
18
- if (text.includes("anthropic") || text.includes("claude")) {
19
- return ["claude-opus-4-5", "claude-sonnet-4-5", "claude-haiku-4-5"];
20
- }
21
- if (text.includes("kimi") || text.includes("moonshot")) {
22
- return ["k3", "kimi-k2.5", "moonshot-v1-128k"];
23
- }
24
- return ["gpt-5.4", "gpt-5.3", "o3", "o4-mini"];
25
- }
26
-
27
16
  function resolveModelRuntime(state = {}, options = {}) {
28
17
  // Lazy require: nativeRunner pulls agent/repl paths that can load modelCommand.
29
18
  const { resolveRuntimeConfig } = require("./nativeRunner");
@@ -46,17 +35,7 @@ function currentThinkingLevel(state = {}) {
46
35
  env: process.env,
47
36
  configLevel: fromState || configLevel,
48
37
  });
49
- if (resolved.level) return resolved.level;
50
- if (resolved.source === "env-budget") {
51
- // Approximate a named level for the secondary menu highlight.
52
- const budget = Number(resolved.budgetTokens) || 0;
53
- if (budget <= 0) return "off";
54
- if (budget <= 3000) return "low";
55
- if (budget <= 16000) return "medium";
56
- if (budget <= 40000) return "high";
57
- return "max";
58
- }
59
- return DEFAULT_THINKING_LEVEL;
38
+ return resolved.level || DEFAULT_THINKING_LEVEL;
60
39
  }
61
40
 
62
41
  function persistThinkingLevel(state = {}, level = "") {
@@ -110,7 +89,7 @@ async function applyUcodeModelCommand(state = {}, result = {}, options = {}) {
110
89
  `model: ${model}`,
111
90
  `provider: ${provider}`,
112
91
  `thinking: ${thinking}`,
113
- "usage: /model <model-id> [off|low|medium|high|max]",
92
+ "usage: /model <model-id> [off|low|medium|high|xhigh|max]",
114
93
  ];
115
94
  try {
116
95
  const listed = await listUcodeModels(state, options);
@@ -139,15 +118,15 @@ async function applyUcodeModelCommand(state = {}, result = {}, options = {}) {
139
118
  if (!next) {
140
119
  return {
141
120
  ok: false,
142
- error: "usage: /model [model-id] [off|low|medium|high|max]",
143
- output: "usage: /model [model-id] [off|low|medium|high|max]",
121
+ error: "usage: /model [model-id] [off|low|medium|high|xhigh|max]",
122
+ output: "usage: /model [model-id] [off|low|medium|high|xhigh|max]",
144
123
  };
145
124
  }
146
125
  if (thinkingRaw && !thinkingNext) {
147
126
  return {
148
127
  ok: false,
149
- error: `unknown thinking level "${thinkingRaw}" (use off|low|medium|high|max)`,
150
- output: `unknown thinking level "${thinkingRaw}" (use off|low|medium|high|max)`,
128
+ error: `unknown thinking level "${thinkingRaw}" (use off|low|medium|high|xhigh|max)`,
129
+ output: `unknown thinking level "${thinkingRaw}" (use off|low|medium|high|xhigh|max)`,
151
130
  };
152
131
  }
153
132
 
@@ -216,30 +195,28 @@ async function applyUcodeModelCommand(state = {}, result = {}, options = {}) {
216
195
  }
217
196
  return {
218
197
  ok: false,
219
- error: "usage: /model [model-id] [off|low|medium|high|max]",
220
- output: "usage: /model [model-id] [off|low|medium|high|max]",
198
+ error: "usage: /model [model-id] [off|low|medium|high|xhigh|max]",
199
+ output: "usage: /model [model-id] [off|low|medium|high|xhigh|max]",
221
200
  };
222
201
  }
223
202
 
224
203
  /**
225
204
  * Build /model completion rows. Prefer a live models-route catalog when
226
- * provided; otherwise fall back to a small hardcoded list.
205
+ * provided; otherwise retain only the current model for manual selection.
227
206
  * Models are marked hasChildren so the TUI opens a thinking-intensity
228
207
  * secondary menu after the id is chosen.
229
208
  */
230
209
  function suggestUcodeModels(state = {}, options = {}) {
231
210
  const current = String((state && state.model) || "").trim();
232
- const provider = String((state && state.provider) || "").trim().toLowerCase();
233
211
  const remote = Array.isArray(options.models)
234
212
  ? options.models.map((item) => String(item || "").trim()).filter(Boolean)
235
213
  : [];
236
- const defaults = remote.length > 0 ? remote : fallbackModelSuggestions(provider);
237
214
  const ids = [];
238
215
  if (current) ids.push(current);
239
- for (const id of defaults) {
216
+ for (const id of remote) {
240
217
  if (id && !ids.includes(id)) ids.push(id);
241
218
  }
242
- return ids.slice(0, 40).map((id) => ({
219
+ return ids.map((id) => ({
243
220
  id,
244
221
  desc: id === current
245
222
  ? "current · pick thinking next"
@@ -257,7 +234,6 @@ module.exports = {
257
234
  suggestUcodeModels,
258
235
  suggestUcodeThinkingLevels,
259
236
  listUcodeModels,
260
- fallbackModelSuggestions,
261
237
  currentThinkingLevel,
262
238
  persistThinkingLevel,
263
239
  };
@@ -5,7 +5,7 @@ const { loadConfig } = require("../config");
5
5
  const { resolveKimiUpstreamCredentials } = require("../agents/providers/credentials/kimi");
6
6
  const { resolveCodexUpstreamCredentials } = require("../agents/providers/credentials/codex");
7
7
  const { resolveRuntimeConfig, resolveTransport, resolveCompletionUrl, resolveResponsesUrl, resolveAnthropicMessagesUrl, DEFAULT_OPENAI_BASE_URL } = require("../agents/providers/runtimeConfig");
8
- const { getNativeTransport, createNativeSseDispatcher, resolveThinkingBudgetTokens, resolveReasoningEffort, normalizeTimeoutMs, createUsageTotals, cloneMessageList } = require("../agents/providers/nativeTransport");
8
+ const { getNativeTransport, createNativeSseDispatcher, resolveReasoningEffort, normalizeTimeoutMs, createUsageTotals, cloneMessageList } = require("../agents/providers/nativeTransport");
9
9
  const { createAgentRuntime } = require("../agents/runtime/createAgentRuntime");
10
10
  const { createCodingCapability } = require("../agents/capabilities/coding");
11
11
  const { createPlanningCapability } = require("../agents/capabilities/planning");
@@ -14,28 +14,21 @@ const codingProfile = require("../agents/profiles/coding");
14
14
  const { runCoreToolAsync } = require("./tools/executor");
15
15
  const { sanitizeModelMessages } = require("./context/assembler");
16
16
  const { retireMessageImages } = require("../agents/providers/transports/visionBlocks");
17
- const { resolveMaxToolCalls } = require("./toolBudget");
17
+ const { resolveToolBudget, DEFAULT_TASK_TIMEOUT_MS } = require("../agents/runtime/core/executionBudget");
18
18
  const { clearUserPrompts } = require("./context/userNudge");
19
19
  const { runProviderTurnGate, resolveCall, checkFaultPoint, materializeAnswerToolResult } = require("./protocol");
20
20
  const { appendUsageRecord } = require("./usageStore");
21
21
  const { buildCoreToolSpecs, buildAnthropicToolSpecs } = require("./tools/specs");
22
+ const { createContextManager } = require("../agents/runtime/context/compaction");
23
+ const { createCheckpointStore } = require("../agents/runtime/context/checkpointStore");
24
+ const { createRuntimeStore } = require("../agents/runtime/context/runtimeStore");
25
+ const { normalizeTraceContext } = require("../agents/runtime/protocol/traceContext");
26
+ const { redactSecrets } = require("../runtime/privacy/redactor");
22
27
 
23
- const DEFAULT_NATIVE_TIMEOUT_MS = 43200000;
24
- const DEFAULT_MAX_NATIVE_TOOL_ERRORS = 20;
28
+ const DEFAULT_NATIVE_TIMEOUT_MS = DEFAULT_TASK_TIMEOUT_MS;
25
29
  const DEFAULT_MAX_PLAN_AUTO_CONTINUES = 24;
26
- const normalizePositiveInt = (value, fallback) => {
27
- const parsed = Number.parseInt(String(value || ""), 10);
28
- return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : fallback;
29
- };
30
30
  const nowMs = () => Date.now();
31
31
 
32
- function resolveNativeToolBudget(maxToolCalls, env = process.env) {
33
- return {
34
- maxToolCalls: resolveMaxToolCalls(maxToolCalls, env),
35
- maxToolErrors: normalizePositiveInt(env.UFOO_UCODE_MAX_TOOL_ERRORS, DEFAULT_MAX_NATIVE_TOOL_ERRORS),
36
- };
37
- }
38
-
39
32
  function createGuards({ signal = null, timeoutMs = DEFAULT_NATIVE_TIMEOUT_MS } = {}) {
40
33
  const startedAt = nowMs();
41
34
  const budgetMs = normalizeTimeoutMs(timeoutMs);
@@ -72,7 +65,7 @@ async function runNativeLoop(options = {}) {
72
65
  maxAutoContinues: DEFAULT_MAX_PLAN_AUTO_CONTINUES,
73
66
  },
74
67
  });
75
- return runtime.run({ ...options, toolBudget: resolveNativeToolBudget(options.maxToolCalls) });
68
+ return runtime.run({ ...options, toolBudget: resolveToolBudget(options.maxToolCalls) });
76
69
  }
77
70
 
78
71
  function appendAnswerToolResult(messages = [], resume = null, answer = {}, options = {}) {
@@ -116,10 +109,40 @@ async function runNativeAgentTask({
116
109
  signal = null,
117
110
  executionState = null,
118
111
  resume = false,
112
+ contextPolicy = {},
113
+ runtimeContext = {},
114
+ onRuntimeEvent = null,
119
115
  } = {}) {
120
116
  const guards = createGuards({ signal, timeoutMs });
121
117
  const nextSessionId = String(sessionId || "").trim() || `native-${randomUUID()}`;
122
118
  const promptText = String(prompt || "").trim();
119
+ const ids = normalizeTraceContext(runtimeContext);
120
+ ids.taskRunId ||= `native-run-${randomUUID()}`;
121
+ ids.taskId ||= ids.taskRunId;
122
+ ids.traceId ||= ids.taskId;
123
+ ids.requestId ||= ids.taskRunId;
124
+ ids.attemptId ||= `attempt-${randomUUID()}`;
125
+ const observation = createRuntimeStore({ workspaceRoot, namespace: "ucode", sessionId: nextSessionId, redact: redactSecrets });
126
+ const observationWarnings = [];
127
+ const observe = async event => {
128
+ const value = { ...ids, agentId: process.env.UFOO_SUBSCRIBER_ID || "ucode", sessionId: nextSessionId, ...event };
129
+ let committed = value;
130
+ try {
131
+ const state = observation.append(value);
132
+ committed = observation.events({ after: state.sequence - 1 })[0];
133
+ } catch (error) {
134
+ if (!observationWarnings.length) {
135
+ observationWarnings.push({ code: "observation_unavailable", error: error.message });
136
+ console.error(`[ucode] observation unavailable: ${error.code || "write failed"}`);
137
+ if (onRuntimeEvent) {
138
+ try { await onRuntimeEvent(redactSecrets({ ...value, type: "observation.warning", warning: observationWarnings[0] })); } catch { /* observer failure is not task failure */ }
139
+ }
140
+ }
141
+ }
142
+ if (onRuntimeEvent) {
143
+ try { await onRuntimeEvent(redactSecrets(committed)); } catch { /* display observers do not own execution */ }
144
+ }
145
+ };
123
146
  // Track every text delta so the error path can return the partial output
124
147
  // the model already produced instead of discarding it.
125
148
  let partialOutput = "";
@@ -133,9 +156,12 @@ async function runNativeAgentTask({
133
156
  };
134
157
 
135
158
  try {
159
+ await observe({ type: "request.accepted", request: { ...ids, text: promptText } });
160
+ await observe({ type: "task.started" });
136
161
  guards.ensureActive();
137
162
 
138
163
  if (!resume && !promptText) {
164
+ await observe({ type: "task.failed", error: "empty task" });
139
165
  return {
140
166
  ok: false,
141
167
  error: "empty task",
@@ -200,6 +226,7 @@ async function runNativeAgentTask({
200
226
  }
201
227
 
202
228
  const transport = getNativeTransport(runtime.transport);
229
+ await observe({ type: "runtime.binding", binding: { provider: runtime.provider, model: runtime.model, transport: runtime.transport } });
203
230
 
204
231
  const runResult = await runNativeLoop({
205
232
  transport,
@@ -209,6 +236,7 @@ async function runNativeAgentTask({
209
236
  systemBlocks,
210
237
  historyMessages: messages,
211
238
  model: runtime.model,
239
+ requestKind: runtimeContext.requestKind || (runtimeContext.taskRunId ? "unknown" : "user"),
212
240
  baseUrl: runtime.baseUrl,
213
241
  apiKey: runtime.apiKey,
214
242
  provider: runtime.provider,
@@ -226,6 +254,11 @@ async function runNativeAgentTask({
226
254
  guards,
227
255
  executionState,
228
256
  resume: Boolean(resume),
257
+ contextManager: createContextManager({ policy: contextPolicy,
258
+ store: createCheckpointStore({ workspaceRoot, namespace: "ucode", sessionId: nextSessionId }) }),
259
+ ...ids,
260
+ agentId: process.env.UFOO_SUBSCRIBER_ID || "ucode",
261
+ onEvent: observe,
229
262
  });
230
263
 
231
264
  const outputText = String(runResult.text || "").trim() || (
@@ -252,12 +285,15 @@ async function runNativeAgentTask({
252
285
  cacheRead: usage.cacheRead,
253
286
  cacheCreation: usage.cacheCreation,
254
287
  });
288
+ await observe({ type: signal?.aborted || runResult.stopReason === "cancelled" ? "task.cancelled" : runResult.error || runResult.stopReason ? "task.failed" : runResult.waitingUserInteraction ? "task.paused" : "task.completed",
289
+ error: runResult.error || runResult.stopReason || "", result: { text: runResult.finalText || outputText, usage } });
255
290
 
256
291
  return {
257
292
  ok: !runResult.error,
258
293
  error: runResult.error || "",
259
294
  stopReason: runResult.stopReason || "",
260
295
  output: outputText,
296
+ finalText: runResult.finalText,
261
297
  messages: cloneMessageList(runResult.messages),
262
298
  turnItems: cloneMessageList(runResult.turnItems),
263
299
  sessionId: nextSessionId,
@@ -270,8 +306,10 @@ async function runNativeAgentTask({
270
306
  waitingUserInteraction: Boolean(runResult.waitingUserInteraction),
271
307
  interactionId: runResult.interactionId || "",
272
308
  protocolLedger: runResult.protocolLedger || null,
309
+ ...(observationWarnings.length ? { observationWarnings } : {}),
273
310
  };
274
311
  } catch (err) {
312
+ await observe({ type: signal?.aborted || err.code === "cancelled" ? "task.cancelled" : "task.failed", error: err.message || "native runner failed" });
275
313
  const message = err && err.message ? err.message : "native runner failed";
276
314
  if (executionState && typeof executionState === "object") {
277
315
  clearUserPrompts(executionState);
@@ -283,6 +321,7 @@ async function runNativeAgentTask({
283
321
  sessionId: nextSessionId,
284
322
  streamed: false,
285
323
  executionState: executionState || null,
324
+ ...(observationWarnings.length ? { observationWarnings } : {}),
286
325
  };
287
326
  }
288
327
  }
@@ -296,7 +335,6 @@ module.exports = {
296
335
  resolveResponsesUrl,
297
336
  resolveAnthropicMessagesUrl,
298
337
  resolveTransport,
299
- resolveThinkingBudgetTokens,
300
338
  resolveReasoningEffort,
301
339
  createNativeSseDispatcher,
302
340
  buildCoreToolSpecs,