u-foo 4.0.0 → 4.0.1

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 (154) hide show
  1. package/OBSERVABILITY.md +65 -0
  2. package/README.md +88 -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/ufoo.js +3 -3
  7. package/dist/tui/darwin-arm64/ufoo-tui +0 -0
  8. package/dist/tui/darwin-x64/ufoo-tui +0 -0
  9. package/dist/tui/linux-arm64/ufoo-tui +0 -0
  10. package/dist/tui/linux-x64/ufoo-tui +0 -0
  11. package/package.json +6 -6
  12. package/src/agents/activity/activityDetector.js +1 -1
  13. package/src/agents/capabilities/agentManagement/service.js +40 -13
  14. package/src/agents/capabilities/coordination/index.js +1 -1
  15. package/src/agents/capabilities/taskReports/index.js +1 -1
  16. package/src/agents/controller/controllerToolExecutor.js +36 -20
  17. package/src/agents/controller/index.js +1 -6
  18. package/src/agents/internal/internalRunner.js +90 -56
  19. package/src/agents/launch/index.js +0 -1
  20. package/src/agents/launch/launcher.js +8 -8
  21. package/src/agents/launch/notifier.js +2 -2
  22. package/src/agents/launch/readyDetector.js +2 -2
  23. package/src/agents/profiles/main.js +1 -1
  24. package/src/agents/prompts/cooperation.js +14 -0
  25. package/src/agents/prompts/defaultBootstrap.js +1 -1
  26. package/src/agents/prompts/groupBootstrap.js +23 -7
  27. package/src/agents/prompts/mainAgent.js +11 -2
  28. package/src/agents/prompts/native/system.js +4 -1
  29. package/src/agents/prompts/native/ufoo.js +11 -3
  30. package/src/agents/prompts/promptProfiles.js +2 -0
  31. package/src/agents/prompts/reporting.js +16 -0
  32. package/src/agents/providers/claudeEventTranslator.js +3 -0
  33. package/src/agents/providers/claudeThreadProvider.js +3 -2
  34. package/src/agents/providers/clientIdentity.js +75 -0
  35. package/src/agents/providers/codexEventTranslator.js +23 -2
  36. package/src/agents/providers/codexThreadProvider.js +15 -6
  37. package/src/agents/providers/credentials/index.js +2 -0
  38. package/src/agents/providers/directAuthStatus.js +1 -1
  39. package/src/agents/providers/index.js +1 -1
  40. package/src/agents/providers/modelSettings.js +34 -0
  41. package/src/agents/providers/modelsCatalog.js +379 -0
  42. package/src/agents/providers/nativeTransport.js +50 -39
  43. package/src/agents/providers/runtimeConfig.js +10 -8
  44. package/src/agents/providers/thinkingLevels.js +10 -36
  45. package/src/agents/providers/transports/responsesProtocol.js +11 -6
  46. package/src/agents/providers/upstreamRuntime.js +135 -0
  47. package/src/agents/runtime/context/checkpointStore.js +38 -0
  48. package/src/agents/runtime/context/compaction.js +151 -0
  49. package/src/agents/runtime/context/contextBudget.js +93 -0
  50. package/src/agents/runtime/context/replayHistory.js +28 -0
  51. package/src/agents/runtime/context/runtimeStore.js +2 -1
  52. package/src/agents/runtime/core/agentLoop.js +99 -18
  53. package/src/agents/runtime/core/executionBudget.js +36 -0
  54. package/src/agents/runtime/createAgentRuntime.js +16 -4
  55. package/src/agents/runtime/prompts/responseLanguage.js +12 -0
  56. package/src/agents/runtime/protocol/runObservation.js +24 -0
  57. package/src/agents/runtime/protocol/traceContext.js +9 -0
  58. package/src/app/chat/ChatController.js +26 -53
  59. package/src/app/chat/agentDirectory.js +1 -16
  60. package/src/app/chat/bootstrap.js +1 -2
  61. package/src/app/chat/commandExecutor.js +93 -285
  62. package/src/app/chat/commands.js +32 -45
  63. package/src/app/chat/daemonMessageRouter.js +0 -45
  64. package/src/app/chat/historyStore.js +12 -48
  65. package/src/app/chat/inputSubmitHandler.js +7 -33
  66. package/src/app/chat/internalAgentLogHistory.js +19 -60
  67. package/src/app/chat/multiWindow/paneManager.js +10 -3
  68. package/src/app/chat/streamState.js +0 -4
  69. package/src/app/cli/features/init.js +5 -5
  70. package/src/app/cli/metricsCommands.js +68 -0
  71. package/src/app/cli/run.js +42 -3
  72. package/src/app/cli/traceCommands.js +36 -0
  73. package/src/code/agent.js +18 -13
  74. package/src/code/busConsumer.js +1 -3
  75. package/src/code/commands.js +1 -1
  76. package/src/code/context/assembler.js +7 -8
  77. package/src/code/context/stateCommit.js +2 -1
  78. package/src/code/internalThread.js +10 -3
  79. package/src/code/launcher/ucode.js +1 -1
  80. package/src/code/launcher/ucodeBootstrap.js +1 -1
  81. package/src/code/modelCommand.js +11 -35
  82. package/src/code/nativeRunner.js +55 -17
  83. package/src/code/providers/modelsCatalog.js +1 -317
  84. package/src/code/repl.js +2 -11
  85. package/src/code/sessionStore.js +3 -3
  86. package/src/code/taskDecomposer.js +18 -0
  87. package/src/code/toolBudget.js +1 -17
  88. package/src/config.js +22 -72
  89. package/src/coordination/bus/index.js +12 -3
  90. package/src/coordination/bus/inject.js +2 -2
  91. package/src/coordination/bus/message.js +15 -1
  92. package/src/coordination/bus/nickname.js +1 -1
  93. package/src/coordination/bus/subscriber.js +3 -2
  94. package/src/coordination/bus/utils.js +1 -1
  95. package/src/coordination/history/agentPerformance.js +279 -0
  96. package/src/coordination/history/agentTrace.js +249 -0
  97. package/src/coordination/state/workspaceAccess.js +1 -1
  98. package/src/orchestration/controller/index.js +1 -8
  99. package/src/orchestration/controller/launchRouting.js +1 -1
  100. package/src/orchestration/solo/commands.js +3 -1
  101. package/src/runtime/contracts/agentMode.js +11 -2
  102. package/src/runtime/contracts/uiProtocol.js +18 -19
  103. package/src/runtime/daemon/agentHost.js +57 -25
  104. package/src/runtime/daemon/agentRecoveryGroups.js +70 -0
  105. package/src/runtime/daemon/busBridge.js +1 -1
  106. package/src/runtime/daemon/controlPlaneService.js +1 -1
  107. package/src/runtime/daemon/groupOrchestrator.js +20 -5
  108. package/src/runtime/daemon/groupStatus.js +20 -0
  109. package/src/runtime/daemon/index.js +19 -44
  110. package/src/runtime/daemon/mcpServer.js +1 -1
  111. package/src/runtime/daemon/nicknameScope.js +1 -1
  112. package/src/runtime/daemon/ops.js +46 -23
  113. package/src/runtime/daemon/projectRuntimeGateway.js +2 -0
  114. package/src/runtime/daemon/promptRequest.js +92 -589
  115. package/src/runtime/daemon/status.js +5 -6
  116. package/src/tools/controllerSchemas.js +6 -2
  117. package/src/tools/handlers/tier2.js +4 -2
  118. package/src/tools/registry.js +4 -0
  119. package/src/tools/schemaFixtures.js +26 -2
  120. package/src/tools/tier0/readAgentMetrics.js +14 -0
  121. package/src/tools/tier0/readAgentTrace.js +12 -0
  122. package/src/ui/agentSettingsController.js +107 -0
  123. package/src/ui/agentSurface.js +1 -1
  124. package/src/ui/dashboardBridge.js +1 -1
  125. package/src/ui/format/banner.js +1 -4
  126. package/src/ui/format/index.js +14 -10
  127. package/src/ui/format/loopSummary.js +50 -0
  128. package/src/ui/format/markdownRenderer.js +3 -4
  129. package/src/ui/rustChatHost.js +191 -206
  130. package/src/ui/rustMultiSession.js +77 -36
  131. package/src/ui/rustUcodeHost.js +1 -1
  132. package/src/ui/settingsBridge.js +33 -16
  133. package/src/ui/toolMergeBridge.js +0 -4
  134. package/src/ui/uiHostServer.js +5 -8
  135. package/src/agents/controller/loopObservability.js +0 -200
  136. package/src/agents/controller/loopRuntime.js +0 -336
  137. package/src/agents/controller/ufooAgent.js +0 -830
  138. package/src/agents/launch/ptyRunner.js +0 -1135
  139. package/src/agents/providers/controllerJsonTransport.js +0 -28
  140. package/src/agents/providers/upstreamTransport.js +0 -698
  141. package/src/app/chat/agentBar.js +0 -135
  142. package/src/app/chat/agentSockets.js +0 -225
  143. package/src/app/chat/dashboardView.js +0 -405
  144. package/src/app/chat/rawKeyMap.js +0 -42
  145. package/src/app/chat/settingsController.js +0 -111
  146. package/src/coordination/history/controllerSummary.js +0 -23
  147. package/src/orchestration/controller/flags.js +0 -167
  148. package/src/orchestration/controller/gateRouter.js +0 -211
  149. package/src/orchestration/controller/routerFastPath.js +0 -22
  150. package/src/orchestration/controller/routerFinalize.js +0 -222
  151. package/src/orchestration/controller/shadowGuard.js +0 -280
  152. package/src/runtime/daemon/executionPaths.js +0 -30
  153. package/src/runtime/daemon/promptLoop.js +0 -136
  154. package/src/runtime/privacy/shadowDiff.js +0 -174
@@ -1,3 +1,6 @@
1
+ const { SETTINGS_MODEL_DEFAULTS } = require("../../config");
2
+ const { DEFAULT_THINKING_LEVEL } = require("../../agents/providers/thinkingLevels");
3
+
1
4
  const COMMAND_TREE = {
2
5
  "/bus": {
3
6
  desc: "Event bus operations",
@@ -35,13 +38,6 @@ const COMMAND_TREE = {
35
38
  stop: { desc: "Stop cron task by id or all" },
36
39
  },
37
40
  },
38
- "/mode": {
39
- desc: "Show internal dashboard launch mode",
40
- children: {
41
- show: { desc: "Show current launch mode", order: 1 },
42
- internal: { desc: "Launch as internal agent", order: 2 },
43
- },
44
- },
45
41
  "/provider": {
46
42
  desc: "Set ufoo-agent provider",
47
43
  children: {
@@ -50,6 +46,7 @@ const COMMAND_TREE = {
50
46
  claude: { desc: "Use Claude", order: 3 },
51
47
  agy: { desc: "Use Antigravity (agy)", order: 4 },
52
48
  kimi: { desc: "Use Kimi Code", order: 5 },
49
+ custom: { desc: "Configure a custom OpenAI API endpoint", order: 6 },
53
50
  },
54
51
  },
55
52
  "/clear": { desc: "Clear chat log on screen" },
@@ -65,12 +62,12 @@ const COMMAND_TREE = {
65
62
  },
66
63
  },
67
64
  "/init": { desc: "Initialize workspace" },
68
- "/multi": {
69
- desc: "Toggle all agent panes; /multi @agent opens one",
70
- optionalArguments: true,
65
+ "/window": {
66
+ desc: "Choose the main, side or multi window layout",
71
67
  children: {
72
- on: { desc: "Show all agent panes" },
73
- off: { desc: "Return to the main agent" },
68
+ main: { desc: "Show only the main agent", order: 1 },
69
+ side: { desc: "Show the main agent and the most recently activated child, or the first child", order: 2 },
70
+ multi: { desc: "Show the main agent and all internal children", order: 3 },
74
71
  },
75
72
  },
76
73
  "/mcp": {
@@ -81,20 +78,18 @@ const COMMAND_TREE = {
81
78
  help: { desc: "Show MCP setup hints", order: 3 },
82
79
  },
83
80
  },
84
- "/open": { desc: "Open project path in global mode" },
81
+ "/open": { desc: "Open project path in global mode", globalOnly: true },
85
82
  "/launch": {
86
83
  desc: "Launch new agent",
87
84
  children: {
88
85
  claude: { desc: "Launch Claude agent", order: 1 },
89
86
  codex: { desc: "Launch Codex agent", order: 2 },
90
- agy: { desc: "Launch Antigravity (agy) agent", order: 3 },
91
- grok: { desc: "Launch Grok Build agent", order: 4 },
92
87
  ucode: { desc: "Launch ucode core agent", order: 5 },
93
- kimi: { desc: "Launch Kimi Code agent", order: 6 },
94
88
  },
95
89
  },
96
90
  "/project": {
97
91
  desc: "Project switch operations (spike)",
92
+ globalOnly: true,
98
93
  children: {
99
94
  current: { desc: "Show current chat project" },
100
95
  list: { desc: "List running projects from registry" },
@@ -116,10 +111,8 @@ const COMMAND_TREE = {
116
111
  },
117
112
  },
118
113
  "/resume": {
119
- desc: "Resume agents (optional nickname) or list recoverable targets",
120
- children: {
121
- list: { desc: "List recoverable agents (optional target)" },
122
- },
114
+ desc: "Resume an internal agent session or a group",
115
+ hasArguments: true,
123
116
  },
124
117
  "/settings": {
125
118
  desc: "Settings operations",
@@ -129,29 +122,17 @@ const COMMAND_TREE = {
129
122
  order: 1,
130
123
  },
131
124
  agent: {
132
- desc: "Manage main ufoo-agent/router provider/model",
125
+ desc: "Manage ufoo main agent provider/model",
133
126
  order: 2,
134
127
  children: {
135
128
  show: { desc: "Show main agent provider/model", order: 1 },
136
129
  set: { desc: "Set provider=<codex|claude> model=<id>", order: 2 },
137
130
  clear: { desc: "Clear agent model or reset provider", order: 3 },
138
- codex: { desc: "Use Codex default model (gpt-5.5)", order: 4 },
139
- claude: { desc: "Use Claude default model (opus-4.7)", order: 5 },
140
- },
141
- },
142
- router: {
143
- desc: "Manage gate router mode/provider/model",
144
- order: 3,
145
- children: {
146
- show: { desc: "Show gate router mode/provider/model", order: 1 },
147
- set: { desc: "Set mode/provider/model", order: 2 },
148
- clear: { desc: "Clear gate router provider/model or reset mode", order: 3 },
149
- main: { desc: "Set router mode to main", order: 4 },
150
- loop: { desc: "Set router mode to loop", order: 5 },
151
- legacy: { desc: "Set router mode to legacy", order: 6 },
152
- shadow: { desc: "Set router mode to shadow", order: 7 },
153
- codex: { desc: "Use Codex gate model (gpt-5.3-codex-spark)", order: 8 },
154
- claude: { desc: "Use Claude gate model (sonnet-4.7)", order: 9 },
131
+ codex: { desc: `Use Codex default (${SETTINGS_MODEL_DEFAULTS.agent.codex} · ${DEFAULT_THINKING_LEVEL})`, order: 4 },
132
+ claude: { desc: `Use Claude default model (${SETTINGS_MODEL_DEFAULTS.agent.claude})`, order: 5 },
133
+ custom: { desc: "Configure custom API URL and key", order: 6 },
134
+ model: { desc: "Select a model for the current provider", hasArguments: true, order: 7 },
135
+ thinking: { desc: "Select thinking intensity", hasArguments: true, order: 8 },
155
136
  },
156
137
  },
157
138
  ucode: {
@@ -231,6 +212,16 @@ function buildCommandRegistry(tree) {
231
212
 
232
213
  const COMMAND_REGISTRY = buildCommandRegistry(COMMAND_TREE);
233
214
 
215
+ function getChatCommandCatalog({ globalMode = false } = {}) {
216
+ if (globalMode) {
217
+ return { commands: COMMAND_REGISTRY, commandTree: COMMAND_TREE };
218
+ }
219
+ const commandTree = Object.fromEntries(
220
+ Object.entries(COMMAND_TREE).filter(([, node]) => !node.globalOnly)
221
+ );
222
+ return { commands: buildCommandRegistry(commandTree), commandTree };
223
+ }
224
+
234
225
  function parseCommand(text) {
235
226
  if (!text.startsWith("/")) return null;
236
227
 
@@ -267,7 +258,7 @@ function normalizeAgentLabel(value = "") {
267
258
  if (raw === "agy" || raw === "antigravity" || raw === "uagy") return "agy";
268
259
  if (raw === "grok" || raw === "ugrok" || raw === "grok-build" || raw === "xai") return "grok";
269
260
  if (raw === "kimi" || raw === "kimi-cli" || raw === "kimi-code" || raw === "ukimi") return "kimi";
270
- if (raw === "ucode" || raw === "ufoo") return "ufoo";
261
+ if (raw === "ucode") return "ucode";
271
262
  return raw || "agent";
272
263
  }
273
264
 
@@ -345,11 +336,6 @@ function describeCommandForChat(text) {
345
336
  return "Managing cron tasks";
346
337
  }
347
338
 
348
- if (command === "mode") {
349
- if (!sub || sub === "show" || sub === "status") return "Showing launch mode";
350
- return `Setting launch mode to ${sub}`;
351
- }
352
-
353
339
  if (command === "provider") {
354
340
  if (!sub || sub === "show" || sub === "status") return "Showing agent provider";
355
341
  return `Setting agent provider to ${sub}`;
@@ -368,7 +354,7 @@ function describeCommandForChat(text) {
368
354
  if (command === "clear") return "Clearing the chat log";
369
355
  if (command === "multi") return "Toggling multi-pane view";
370
356
  if (command === "open") return `Opening project ${args[0] || ""}`.trim();
371
- if (command === "resume") return args[0] === "list" ? "Listing recoverable agents" : `Resuming ${args[0] || "agents"}`;
357
+ if (command === "resume") return args[0] ? `Resuming ${args[0]}` : "Choose an agent or group to resume";
372
358
  if (command === "init") return "Initializing ufoo workspace";
373
359
 
374
360
  return `Running /${command}`;
@@ -398,6 +384,7 @@ module.exports = {
398
384
  COMMAND_REGISTRY,
399
385
  sortCommands,
400
386
  buildCommandRegistry,
387
+ getChatCommandCatalog,
401
388
  parseCommand,
402
389
  describeCommandForChat,
403
390
  shouldEchoCommandInChat,
@@ -16,12 +16,6 @@ function createDaemonMessageRouter(options = {}) {
16
16
  getPending = () => null,
17
17
  setPending = () => {},
18
18
  resolveAgentDisplayName = (value) => value,
19
- getCurrentView = () => "main",
20
- isAgentViewUsesBus = () => false,
21
- getViewingAgent = () => "",
22
- isAgentEventForViewingAgent = (data, viewingAgent, publisher) =>
23
- Boolean(viewingAgent && (publisher === viewingAgent || data?.target === viewingAgent)),
24
- writeToAgentTerm = () => {},
25
19
  consumePendingDelivery = () => false,
26
20
  getPendingState = () => null,
27
21
  beginStream = () => null,
@@ -487,47 +481,8 @@ function createDaemonMessageRouter(options = {}) {
487
481
  if (data.silent && !streamPayload) return true;
488
482
  if (!displayMessage && !streamPayload) return true;
489
483
 
490
- const viewingAgent = getViewingAgent();
491
- const isOwnInternalPrompt =
492
- data.source === "chat-internal-agent-view" &&
493
- viewingAgent &&
494
- data.target === viewingAgent &&
495
- publisher !== viewingAgent;
496
- if (
497
- getCurrentView() === "agent" &&
498
- isAgentViewUsesBus() &&
499
- isOwnInternalPrompt
500
- ) {
501
- return true;
502
- }
503
- const isAgentViewTarget =
504
- getCurrentView() === "agent" &&
505
- isAgentViewUsesBus() &&
506
- viewingAgent &&
507
- isAgentEventForViewingAgent(data, viewingAgent, publisher);
508
-
509
484
  const displayName = resolveAgentDisplayName(publisher);
510
485
 
511
- if (isAgentViewTarget) {
512
- if (streamPayload) {
513
- const delta = typeof streamPayload.delta === "string"
514
- ? decodeEscapedNewlines(streamPayload.delta)
515
- : "";
516
- if (delta || streamPayload.done) {
517
- writeToAgentTerm(delta, {
518
- data,
519
- publisher,
520
- streamPayload,
521
- done: Boolean(streamPayload.done),
522
- reason: streamPayload.reason || "",
523
- });
524
- }
525
- } else if (displayMessage) {
526
- writeToAgentTerm(`${displayMessage}\r\n`);
527
- }
528
- return true;
529
- }
530
-
531
486
  if (data.event === "delivery" && consumePendingDelivery(publisher, displayName)) {
532
487
  // Delivery confirmations are already shown in the status bar — suppress from chat.
533
488
  requestStatus();
@@ -7,7 +7,6 @@
7
7
  const path = require("path");
8
8
  const fs = require("fs");
9
9
  const crypto = require("crypto");
10
- const { stripBlessedTags } = require("../../ui/chatLogModel");
11
10
 
12
11
  function projectRootToId(projectRoot) {
13
12
  try {
@@ -44,11 +43,6 @@ function chatHistoryFilePath(projectRoot, options = {}) {
44
43
  return path.join(getUfooPaths(projectRoot || process.cwd()).ufooDir, "chat", "history.jsonl");
45
44
  }
46
45
 
47
- function normalizeHistoryLogLines(text = "") {
48
- const clean = stripBlessedTags(text);
49
- return clean.split(/\r?\n/);
50
- }
51
-
52
46
  function loadChatHistory(projectRoot, cap = 200, options = {}) {
53
47
  const file = chatHistoryFilePath(projectRoot, options);
54
48
  try {
@@ -56,56 +50,26 @@ function loadChatHistory(projectRoot, cap = 200, options = {}) {
56
50
  const raw = fs.readFileSync(file, "utf8");
57
51
  const lines = raw.split(/\r?\n/).filter(Boolean);
58
52
  const out = [];
59
- const pushLine = (line = "", sourceType = "") => {
60
- const value = String(line || "");
61
- if (!value.trim()) {
62
- if (out.length > 0) {
63
- const last = out[out.length - 1];
64
- const lastText = typeof last === "object" ? last.text : last;
65
- if (lastText !== "") out.push({ text: "", sourceType: sourceType || "system" });
66
- }
67
- return;
68
- }
69
- out.push(sourceType ? { text: value, sourceType } : value);
70
- };
71
53
  for (const line of lines) {
72
54
  try {
73
55
  const entry = JSON.parse(line);
74
- if (!entry) continue;
75
- if (entry.type === "spacer") {
76
- pushLine("", "system");
77
- continue;
78
- }
79
- const text = String(entry.text || "");
80
- if (!text) continue;
81
- const sourceType = String(entry.type || "");
82
- const stripped = text.replace(/\{[^{}]+\}/g, "");
83
- for (const renderedLine of normalizeHistoryLogLines(stripped)) {
84
- pushLine(renderedLine, sourceType);
85
- }
56
+ if (!entry || typeof entry !== "object") continue;
57
+ const sourceType = String(entry.type || entry.kind || "system");
58
+ const text = sourceType === "spacer" ? "" : String(entry.text || "").replace(/\r\n?/g, "\n");
59
+ if (!text && sourceType !== "spacer") continue;
60
+ if (!text.trim() && (!out.length || !out[out.length - 1].text.trim())) continue;
61
+ // A transcript block is the persistence unit. Splitting it into lines
62
+ // loses tool/thinking folds, speakers, paragraphs and fenced code.
63
+ out.push({ ...entry, text, sourceType,
64
+ meta: entry.meta && typeof entry.meta === "object" ? entry.meta : {},
65
+ });
86
66
  } catch {
87
67
  // ignore malformed lines
88
68
  }
89
69
  }
90
- while (out.length > 0) {
91
- const first = out[0];
92
- const firstText = typeof first === "object" ? first.text : first;
93
- if (firstText !== "") break;
94
- out.shift();
95
- }
96
- while (out.length > 0) {
97
- const last = out[out.length - 1];
98
- const lastText = typeof last === "object" ? last.text : last;
99
- if (lastText !== "") break;
100
- out.pop();
101
- }
70
+ while (out.length > 0 && !out[out.length - 1].text.trim()) out.pop();
102
71
  const capped = out.slice(-cap);
103
- while (capped.length > 0) {
104
- const first = capped[0];
105
- const firstText = typeof first === "object" ? first.text : first;
106
- if (firstText !== "") break;
107
- capped.shift();
108
- }
72
+ while (capped.length > 0 && !capped[0].text.trim()) capped.shift();
109
73
  return capped;
110
74
  } catch {
111
75
  return [];
@@ -18,10 +18,8 @@ function createInputSubmitHandler(options = {}) {
18
18
  markPendingDelivery = () => {},
19
19
  clearTargetAgent = () => {},
20
20
  setTargetAgent = () => {},
21
- enterAgentView = () => {},
22
- getAgentAdapter = () => null,
23
- activateAgent = async () => {},
24
- // When /multi is on: focus the in-window TUI pane instead of OS activate.
21
+ activateInternalAgent = () => {},
22
+ // In the all-children layout, focus an existing in-window TUI pane.
25
23
  // Return true if handled.
26
24
  focusMultiPane = null,
27
25
  commitInputHistory = () => {},
@@ -51,38 +49,14 @@ function createInputSubmitHandler(options = {}) {
51
49
  return true;
52
50
  }
53
51
  } catch {
54
- // Fall through to OS activate / internal view.
52
+ // Try the host's internal side pane.
55
53
  }
56
54
  }
57
55
 
58
- const adapter = getAgentAdapter(agentId);
59
- const capabilities = adapter && adapter.capabilities ? adapter.capabilities : null;
60
- const supportsActivate = Boolean(capabilities && capabilities.supportsActivate);
61
- const supportsInternalQueue = Boolean(capabilities && capabilities.supportsInternalQueueLoop);
62
-
63
- if (supportsActivate) {
64
- clearTargetAgent();
65
- try {
66
- // Always use the host-wired activator. Bare adapterRouter adapters
67
- // expose activate() that no-ops unless activateTerminal/activateTmux
68
- // were injected — which chat hosts do not do.
69
- const pendingActivation = activateAgent(agentId);
70
- if (pendingActivation && typeof pendingActivation.catch === "function") {
71
- pendingActivation.catch(() => {});
72
- }
73
- } catch {
74
- // Best-effort activation.
75
- }
76
- return true;
77
- }
78
-
79
- if (supportsInternalQueue) {
80
- clearTargetAgent();
81
- enterAgentView(agentId, { useBus: true });
82
- return true;
83
- }
84
-
85
- return false;
56
+ const result = await activateInternalAgent(agentId);
57
+ if (!result || result.ok === false) return false;
58
+ clearTargetAgent();
59
+ return true;
86
60
  }
87
61
 
88
62
  async function handleSubmit(value) {
@@ -82,60 +82,10 @@ function parseStreamMessage(raw = "") {
82
82
  }
83
83
  }
84
84
 
85
- function appendPrefixedText(lines, prefix, text) {
86
- const clean = normalizeText(text);
87
- if (!clean) return;
88
- const parts = clean.split("\n");
89
- parts.forEach((part, index) => {
90
- if (index === parts.length - 1 && part === "") return;
91
- lines.push(`${index === 0 ? prefix : " "}${part}`);
92
- });
93
- }
94
-
95
- function appendUserText(lines, text, state) {
96
- appendPrefixedText(lines, "> ", text);
97
- state.replyActive = false;
98
- }
99
-
100
- function ensureAgentReplyPrefix(lines, prefix = "• ") {
101
- if (lines.length === 0) {
102
- lines.push(prefix);
103
- return;
104
- }
105
- if (lines[lines.length - 1] === "") {
106
- lines[lines.length - 1] = prefix;
107
- return;
108
- }
109
- lines.push(prefix);
110
- }
111
-
112
- function appendAgentStreamText(lines, text, state) {
113
- const clean = normalizeText(text);
114
- if (!clean) return;
115
- for (const char of clean) {
116
- if (char === "\n") {
117
- lines.push("");
118
- continue;
119
- }
120
- if (!state.replyActive) {
121
- ensureAgentReplyPrefix(lines, "• ");
122
- state.replyActive = true;
123
- } else if (lines.length === 0 || lines[lines.length - 1] === "") {
124
- ensureAgentReplyPrefix(lines, " ");
125
- }
126
- lines[lines.length - 1] += char;
127
- }
128
- }
129
-
130
- function appendAgentMessage(lines, text, state) {
131
- appendPrefixedText(lines, "• ", text);
132
- state.replyActive = false;
133
- }
134
-
135
- function loadInternalAgentLogHistory(projectRoot, agentId, options = {}) {
85
+ function loadInternalAgentTranscript(projectRoot, agentId, options = {}) {
136
86
  const paths = getUfooPaths(projectRoot || process.cwd());
137
87
  const maxEvents = Number.isFinite(options.maxEvents) ? Math.max(1, options.maxEvents) : 400;
138
- const maxLines = Number.isFinite(options.maxLines) ? Math.max(1, options.maxLines) : 1000;
88
+ const maxEntries = Number.isFinite(options.maxEntries) ? Math.max(1, options.maxEntries) : 1000;
139
89
  let agents = {};
140
90
  try {
141
91
  const bus = JSON.parse(fs.readFileSync(paths.agentsFile, "utf8"));
@@ -164,8 +114,15 @@ function loadInternalAgentLogHistory(projectRoot, agentId, options = {}) {
164
114
  reversedEvents.push(...readMatchingEventsFromFileReverse(file, aliases, remaining));
165
115
  }
166
116
 
167
- const lines = [];
168
- const state = { replyActive: false };
117
+ const entries = [];
118
+ let streamEntry = null;
119
+ function append(kind, text, seq) {
120
+ const clean = normalizeText(text);
121
+ if (!clean) return null;
122
+ const entry = { id: `history-${seq || entries.length + 1}`, kind, text: clean };
123
+ entries.push(entry);
124
+ return entry;
125
+ }
169
126
  for (const evt of reversedEvents.reverse()) {
170
127
  const data = eventData(evt);
171
128
  const rawMessage = typeof data.message === "string" ? data.message : "";
@@ -177,24 +134,26 @@ function loadInternalAgentLogHistory(projectRoot, agentId, options = {}) {
177
134
 
178
135
  if (streamDelta !== null) {
179
136
  if (isFromAgent && streamDelta) {
180
- appendAgentStreamText(lines, streamDelta, state);
137
+ if (streamEntry) streamEntry.text += streamDelta;
138
+ else streamEntry = append("assistant", streamDelta, evt.seq);
181
139
  } else if (isFromAgent) {
182
- state.replyActive = false;
140
+ streamEntry = null;
183
141
  }
184
142
  continue;
185
143
  }
186
144
 
187
145
  if (isFromAgent) {
188
- appendAgentMessage(lines, rawMessage, state);
146
+ append("assistant", rawMessage, evt.seq);
189
147
  } else if (isToAgent) {
190
- appendUserText(lines, rawMessage, state);
148
+ append("user", rawMessage, evt.seq);
191
149
  }
150
+ streamEntry = null;
192
151
  }
193
152
 
194
- return lines.slice(-maxLines);
153
+ return entries.slice(-maxEntries);
195
154
  }
196
155
 
197
156
  module.exports = {
198
- loadInternalAgentLogHistory,
157
+ loadInternalAgentTranscript,
199
158
  buildAgentAliases,
200
159
  };
@@ -25,12 +25,16 @@ function createPaneManager(options = {}) {
25
25
  scrollOffset: Number(options.scrollOffset) || 0,
26
26
  internalInput: String(options.initialInput || ""),
27
27
  internalCursor: Math.max(0, Math.min(String(options.initialInput || "").length, Number(options.initialCursor) || 0)),
28
+ inputRevision: Number(options.inputRevision) || 0,
28
29
  };
29
30
  panes.set(agentId, pane);
30
31
  const initialOutput = Array.isArray(options.initialLines)
31
32
  ? options.initialLines.join("\r\n")
32
33
  : String(options.initialOutput || "");
33
- if (initialOutput && !options.surface) surface.apply("transcript.append", { kind: "system", text: initialOutput });
34
+ if (!options.surface) {
35
+ if (Array.isArray(options.initialEntries)) surface.apply("transcript.reset", { entries: options.initialEntries });
36
+ else if (initialOutput) surface.apply("transcript.append", { kind: "system", text: initialOutput });
37
+ }
34
38
  onPaneOutput(pane.agentId);
35
39
  if (!focusedAgent) focusedAgent = agentId;
36
40
  }
@@ -77,14 +81,17 @@ function createPaneManager(options = {}) {
77
81
  if (!raw) return;
78
82
  if (raw === "\r") {
79
83
  const message = String(pane.internalInput || "").trim();
84
+ const submittedRevision = pane.inputRevision;
80
85
  pane.internalInput = "";
81
86
  pane.internalCursor = 0;
82
87
  if (message) {
83
88
  pane.surface.apply("transcript.append", { kind: "user", text: message });
84
- if (!/^\/multi(?:\s|$)/.test(message)) pane.surface.accept({ type: "task_submitted", message });
89
+ if (!/^\/window(?:\s|$)/.test(message)) pane.surface.accept({ type: "task_submitted", message });
85
90
  const failed = (error) => {
86
91
  pane.surface.accept({ type: "submission_failed", message, error: `Message delivery failed: ${error?.message || error}` });
87
- if (!pane.internalInput) { pane.internalInput = message; pane.internalCursor = message.length; }
92
+ if (!pane.internalInput && pane.inputRevision === submittedRevision) {
93
+ pane.internalInput = message; pane.internalCursor = message.length;
94
+ }
88
95
  onPaneOutput(pane.agentId);
89
96
  };
90
97
  try {
@@ -171,12 +171,8 @@ function createChatStreamState({
171
171
  };
172
172
  }
173
173
 
174
- /** @deprecated Prefer createChatStreamState. */
175
- const createInkStreamState = createChatStreamState;
176
-
177
174
  module.exports = {
178
175
  STREAM_FLUSH_INTERVAL_MS,
179
176
  createThrottledSender,
180
177
  createChatStreamState,
181
- createInkStreamState,
182
178
  };
@@ -18,19 +18,19 @@ class UfooInit {
18
18
  .map((item) => item.trim())
19
19
  .filter(Boolean);
20
20
  const project = options.project || process.cwd();
21
- const controllerMode = options.controllerMode === true;
21
+ const globalController = options.globalController === true;
22
22
 
23
23
  console.log("=== ufoo init ===");
24
24
  console.log(`Project directory: ${project}`);
25
25
  console.log(`Targets: ${targets.join(", ")}`);
26
26
  console.log();
27
27
 
28
- if (!controllerMode) {
28
+ if (!globalController) {
29
29
  this.ensureAgentsFiles(project);
30
30
  }
31
31
 
32
32
  // 初始化核心
33
- this.initCore(project, { controllerMode });
33
+ this.initCore(project, { globalController });
34
34
 
35
35
  // Initialize selected workspace features.
36
36
  for (const target of targets) {
@@ -77,7 +77,7 @@ class UfooInit {
77
77
  */
78
78
  initCore(project, options = {}) {
79
79
  console.log("[core] Initializing .ufoo core...");
80
- const controllerMode = options.controllerMode === true;
80
+ const globalController = options.globalController === true;
81
81
 
82
82
  const ufooDir = path.join(project, ".ufoo");
83
83
  if (!fs.existsSync(ufooDir)) {
@@ -92,7 +92,7 @@ class UfooInit {
92
92
  const docsLink = path.join(ufooDir, "docs");
93
93
  const projectDocs = path.join(project, "docs");
94
94
 
95
- if (!controllerMode && fs.existsSync(projectDocs)) {
95
+ if (!globalController && fs.existsSync(projectDocs)) {
96
96
  const linkStat = this.safeLstat(docsLink);
97
97
  if (linkStat) {
98
98
  fs.unlinkSync(docsLink);
@@ -0,0 +1,68 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const { readAgentPerformance } = require("../../coordination/history/agentTrace");
5
+
6
+ const ratio = (n, d) => n != null && d ? n / d : null;
7
+ const display = value => value == null ? "unknown" : Number(value).toFixed(1);
8
+ const duration = value => value == null ? "unknown" : `${display(value)}ms`;
9
+ const percentage = value => value == null ? "unknown" : `${display(value * 100)}%`;
10
+
11
+ function comparePerformance(current, baseline) {
12
+ if (baseline?.version !== 1 || !baseline.summary?.latency || !baseline.summary?.usage || !Number.isFinite(baseline.summary.runs)) {
13
+ throw new Error("baseline must be a ufoo metrics --json report (version 1)");
14
+ }
15
+ const values = report => ({
16
+ completedOfFinished: report.summary.completedOfFinished,
17
+ modelCallsPerRun: ratio(report.summary.counts.modelCalls || 0, report.summary.runs),
18
+ toolErrorsPerRun: ratio(report.summary.counts.toolErrors || 0, report.summary.runs),
19
+ elapsedP50Ms: report.summary.latency.elapsedMs?.p50 ?? null,
20
+ elapsedP95Ms: report.summary.latency.elapsedMs?.p95 ?? null,
21
+ firstTextP50Ms: report.summary.latency.firstTextMs?.p50 ?? null,
22
+ inputTokensPerObservedRun: report.coverage?.runsWithCompleteUsage === report.summary.runs ? ratio(report.summary.usage.input?.sum, report.summary.usage.input?.samples) : null,
23
+ outputTokensPerObservedRun: report.coverage?.runsWithCompleteUsage === report.summary.runs ? ratio(report.summary.usage.output?.sum, report.summary.usage.output?.samples) : null,
24
+ cacheHitRate: report.coverage?.runsWithCompleteCache === report.summary.runs ? report.summary.cache?.hitRate ?? null : null,
25
+ acceptedOfReviewed: report.delegations?.acceptedOfReviewed ?? null,
26
+ });
27
+ const before = values(baseline), after = values(current);
28
+ const metrics = Object.fromEntries(Object.keys(after).map(key => {
29
+ const a = before[key], b = after[key];
30
+ return [key, { before: a, after: b, delta: a == null || b == null ? null : b - a,
31
+ changeRatio: a == null || b == null || a === 0 ? null : (b - a) / Math.abs(a) }];
32
+ }));
33
+ return { baselineRuns: baseline.summary.runs, currentRuns: current.summary.runs,
34
+ incomplete: Boolean(current.incomplete || baseline.incomplete), metrics,
35
+ note: "Observed samples may contain different tasks; these deltas are not a causal or quality verdict." };
36
+ }
37
+
38
+ function runMetricsCommand(taskId, options = {}) {
39
+ const report = readAgentPerformance(options.project || process.cwd(), { task_id: options.task || taskId || "",
40
+ agent_id: options.agent, session_id: options.session, since: options.since, until: options.until,
41
+ provider: options.provider, model: options.model, limit: options.limit });
42
+ if (options.baseline) {
43
+ if (fs.statSync(options.baseline).size > 16 * 1024 * 1024) throw new Error("baseline exceeds 16 MiB");
44
+ report.comparison = comparePerformance(report, JSON.parse(fs.readFileSync(options.baseline, "utf8")));
45
+ }
46
+ if (options.json) console.log(JSON.stringify(report, null, 2));
47
+ else {
48
+ const summary = report.summary;
49
+ console.log(`Agent performance: ${summary.runs} observed runs${report.incomplete ? " (partial evidence)" : ""}`);
50
+ console.log(`Execution: ${summary.outcomes.completed} completed, ${summary.outcomes.failed} failed, ${summary.outcomes.cancelled} cancelled; completed/finished ${percentage(summary.completedOfFinished)}`);
51
+ console.log(`Latency: p50 ${duration(summary.latency.elapsedMs.p50)}, p95 ${duration(summary.latency.elapsedMs.p95)}; first text p50 ${duration(summary.latency.firstTextMs.p50)} (${summary.latency.firstTextMs.samples} samples)`);
52
+ console.log(`Models: ${summary.counts.modelCalls || 0} API attempts, ${summary.counts.sdkTurns || 0} SDK turns, ${summary.counts.modelFailures || 0} failures, ${summary.counts.modelRetries || 0} retries`);
53
+ console.log(`Usage: input ${display(summary.usage.input.sum)}, output ${display(summary.usage.output.sum)}; compaction input ${display(summary.compactionUsage.input.sum)}, output ${display(summary.compactionUsage.output.sum)}`);
54
+ console.log(`Cache: ${percentage(summary.cache.hitRate)} hit; read ${display(summary.cache.cachedTokens)}/${display(summary.cache.promptTokens)} prompt tokens, written ${display(summary.usage.cacheCreation.sum)} (${summary.cache.samples}/${summary.cache.usageSamples} usage samples)`);
55
+ console.log(`Tools: ${summary.counts.toolCalls || 0} executed, ${summary.counts.toolErrors || 0} errors, ${summary.counts.toolRejections || 0} rejected, ${summary.counts.repeatedToolCalls || 0} repeated arguments`);
56
+ console.log(`Delegation: ${report.delegations.accepted} accepted, ${report.delegations.rejected} rejected, ${report.delegations.awaitingAcceptance} awaiting acceptance`);
57
+ for (const cohort of report.cohorts) console.log(` ${cohort.provider}/${cohort.model} ${cohort.thinkingLevel} ${cohort.executionKind} ${cohort.requestKind} v${cohort.runtimeVersion} engine=${cohort.engineFingerprint.slice(0, 8)}: ${cohort.runs} runs, p50 ${duration(cohort.latency.elapsedMs.p50)}, cache ${percentage(cohort.cache.hitRate)}`);
58
+ if (report.comparison) {
59
+ for (const [name, value] of Object.entries(report.comparison.metrics)) console.log(` ${name}: ${display(value.before)} -> ${display(value.after)} (delta ${display(value.delta)})`);
60
+ console.log(report.comparison.note);
61
+ }
62
+ if (report.warnings.length) console.log(`Warnings: ${report.warnings.map(w => w.code).join(", ")}; --json includes source details`);
63
+ console.log(`Configuration coverage: ${report.coverage.runsWithConfiguration}/${summary.runs}; complete usage coverage: ${report.coverage.runsWithCompleteUsage}/${summary.runs}; complete cache coverage: ${report.coverage.runsWithCompleteCache}/${summary.runs}`);
64
+ }
65
+ return report;
66
+ }
67
+
68
+ module.exports = { runMetricsCommand, comparePerformance };