u-foo 4.0.3 → 4.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/README.md +239 -19
  2. package/README.zh-CN.md +3 -3
  3. package/bin/ucode.js +10 -2
  4. package/bin/ufoo.js +3 -0
  5. package/dist/tui/darwin-arm64/ufoo-tui +0 -0
  6. package/dist/tui/darwin-x64/ufoo-tui +0 -0
  7. package/dist/tui/linux-arm64/ufoo-tui +0 -0
  8. package/dist/tui/linux-x64/ufoo-tui +0 -0
  9. package/{OBSERVABILITY.md → docs/OBSERVABILITY.md} +3 -3
  10. package/docs/README.md +27 -0
  11. package/extensions/ufoo-browser/LICENSE +152 -0
  12. package/extensions/ufoo-browser/NOTICE +10 -0
  13. package/extensions/ufoo-browser/README.md +30 -0
  14. package/extensions/ufoo-browser/background.js +409 -0
  15. package/extensions/ufoo-browser/icons/icon-128.png +0 -0
  16. package/extensions/ufoo-browser/icons/icon-16.png +0 -0
  17. package/extensions/ufoo-browser/icons/icon-256.png +0 -0
  18. package/extensions/ufoo-browser/icons/icon-32.png +0 -0
  19. package/extensions/ufoo-browser/icons/icon-48.png +0 -0
  20. package/extensions/ufoo-browser/icons/logo.png +0 -0
  21. package/extensions/ufoo-browser/icons/toolbar-16.png +0 -0
  22. package/extensions/ufoo-browser/icons/toolbar-32.png +0 -0
  23. package/extensions/ufoo-browser/icons/toolbar-logo.png +0 -0
  24. package/extensions/ufoo-browser/manifest.json +30 -0
  25. package/extensions/ufoo-browser/popup.css +71 -0
  26. package/extensions/ufoo-browser/popup.html +44 -0
  27. package/extensions/ufoo-browser/popup.js +153 -0
  28. package/package.json +7 -5
  29. package/scripts/postinstall.js +6 -0
  30. package/src/agents/capabilities/browser/index.js +49 -0
  31. package/src/agents/capabilities/coding/backgroundHooks.js +94 -0
  32. package/src/agents/capabilities/coding/index.js +30 -1
  33. package/src/agents/capabilities/index.js +5 -2
  34. package/src/agents/capabilities/planning/index.js +44 -5
  35. package/src/agents/capabilities/turnRecall/index.js +341 -0
  36. package/src/agents/controller/controllerToolExecutor.js +2 -2
  37. package/src/agents/internal/internalRunner.js +30 -8
  38. package/src/agents/internal/taskControl.js +107 -0
  39. package/src/agents/profiles/coding.js +1 -1
  40. package/src/agents/profiles/main.js +1 -1
  41. package/src/agents/prompts/mainAgent.js +1 -0
  42. package/src/agents/prompts/native/toolDescriptions/bash.js +7 -1
  43. package/src/agents/providers/claudeSessionFiles.js +1 -1
  44. package/src/agents/providers/codexThreadProvider.js +6 -1
  45. package/src/agents/providers/credentials/agy.js +171 -0
  46. package/src/agents/providers/directAuthStatus.js +20 -2
  47. package/src/agents/providers/modelsCatalog.js +26 -5
  48. package/src/agents/providers/nativeTransport.js +145 -73
  49. package/src/agents/providers/providerId.js +17 -0
  50. package/src/agents/providers/runtimeConfig.js +67 -20
  51. package/src/agents/providers/transports/antigravityTransport.js +242 -0
  52. package/src/agents/providers/transports/index.js +1 -0
  53. package/src/agents/providers/transports/openaiChatTransport.js +3 -2
  54. package/src/agents/providers/transports/openaiResponsesTransport.js +2 -1
  55. package/src/agents/providers/transports/responsesProtocol.js +119 -18
  56. package/src/agents/providers/transports/transportContract.js +1 -0
  57. package/src/agents/providers/upstreamRuntime.js +3 -1
  58. package/src/agents/runtime/context/contextBudget.js +1 -19
  59. package/src/agents/runtime/context/contextWindow.js +5 -0
  60. package/src/agents/runtime/context/replayHistory.js +16 -10
  61. package/src/agents/runtime/context/runtimeStore.js +0 -1
  62. package/src/agents/runtime/context/sessionJournal.js +1 -1
  63. package/src/agents/runtime/context/slidingWindowManager.js +792 -0
  64. package/src/agents/runtime/context/topicSelector.js +338 -0
  65. package/src/agents/runtime/context/turnAnalyzer.js +767 -0
  66. package/src/agents/runtime/context/turnIndexStore.js +515 -0
  67. package/src/agents/runtime/core/agentLoop.js +140 -35
  68. package/src/agents/runtime/core/executionBudget.js +2 -1
  69. package/src/agents/runtime/core/toolErrorGuard.js +39 -0
  70. package/src/agents/runtime/createAgentRuntime.js +80 -7
  71. package/src/agents/runtime/index.js +5 -0
  72. package/src/agents/runtime/protocol/materialize.js +1 -1
  73. package/src/agents/runtime/tasks/hooks.js +137 -0
  74. package/src/app/chat/ChatController.js +8 -4
  75. package/src/app/chat/daemonMessageRouter.js +3 -1
  76. package/src/app/chat/inputSubmitHandler.js +2 -2
  77. package/src/app/chat/transport.js +1 -1
  78. package/src/app/cli/browserCommands.js +340 -0
  79. package/src/app/cli/busCoreCommands.js +63 -3
  80. package/src/app/cli/features/doctor.js +21 -0
  81. package/src/app/cli/metricsCommands.js +1 -1
  82. package/src/app/cli/run.js +81 -1
  83. package/src/app/cli/setupCommands.js +200 -0
  84. package/src/code/UcodeController.js +31 -1
  85. package/src/code/agent.js +76 -25
  86. package/src/code/busConsumer.js +13 -12
  87. package/src/code/commands.js +0 -1
  88. package/src/code/context/assembler.js +11 -88
  89. package/src/code/context/planGraphService.js +121 -6
  90. package/src/code/context/planProjection.js +10 -2
  91. package/src/code/context/reducers.js +172 -4
  92. package/src/code/context/stateCommit.js +0 -32
  93. package/src/code/context/transcript.js +7 -4
  94. package/src/code/internalThread.js +9 -1
  95. package/src/code/launcher/ucode.js +4 -2
  96. package/src/code/modelCommand.js +6 -5
  97. package/src/code/nativeRunner.js +232 -62
  98. package/src/code/repl.js +27 -1
  99. package/src/code/runtime/agentWakeup.js +20 -3
  100. package/src/code/runtime/backgroundWakeHost.js +45 -0
  101. package/src/code/runtime/taskFocusContext.js +7 -0
  102. package/src/code/runtime/taskLoop.js +24 -1
  103. package/src/code/sessionStore.js +14 -10
  104. package/src/code/taskDecomposer.js +16 -7
  105. package/src/code/tools/backgroundProcess.js +23 -0
  106. package/src/code/tools/bash.js +764 -12
  107. package/src/code/tools/executor.js +13 -4
  108. package/src/code/tools/planGraph.js +1 -0
  109. package/src/code/tools/specs.js +62 -4
  110. package/src/code/tools/taskRun.js +38 -0
  111. package/src/config.js +92 -6
  112. package/src/coordination/bus/index.js +2 -2
  113. package/src/coordination/bus/message.js +10 -1
  114. package/src/coordination/bus/nickname.js +3 -1
  115. package/src/coordination/bus/subscriber.js +25 -10
  116. package/src/coordination/bus/utils.js +4 -0
  117. package/src/coordination/bus/wakeEndpoint.js +198 -0
  118. package/src/coordination/history/agentPerformance.js +18 -18
  119. package/src/coordination/history/agentTrace.js +7 -3
  120. package/src/coordination/state/paths.js +4 -0
  121. package/src/coordination/state/workspaceAccess.js +3 -1
  122. package/src/orchestration/groups/modelConfig.js +66 -0
  123. package/src/orchestration/groups/validateTemplate.js +2 -0
  124. package/src/runtime/browser/broker.js +1027 -0
  125. package/src/runtime/browser/brokerClient.js +108 -0
  126. package/src/runtime/browser/componentInstaller.js +275 -0
  127. package/src/runtime/browser/installState.js +329 -0
  128. package/src/runtime/browser/manifest.js +145 -0
  129. package/src/runtime/browser/native-host-runner.js +198 -0
  130. package/src/runtime/browser/nativeHost.js +213 -0
  131. package/src/runtime/browser/nativeMessagingProtocol.js +50 -0
  132. package/src/runtime/browser/paths.js +134 -0
  133. package/src/runtime/browser/playwrightSession.js +614 -0
  134. package/src/runtime/daemon/agentHost.js +175 -28
  135. package/src/runtime/daemon/busBridge.js +2 -1
  136. package/src/runtime/daemon/deliveryScheduler.js +70 -2
  137. package/src/runtime/daemon/globalDaemon.js +20 -0
  138. package/src/runtime/daemon/groupOrchestrator.js +20 -1
  139. package/src/runtime/daemon/index.js +6 -4
  140. package/src/runtime/daemon/ops.js +14 -8
  141. package/src/tools/handlers/listAgents.js +1 -1
  142. package/src/tools/handlers/readBusSummary.js +1 -1
  143. package/src/tools/handlers/routeAgent.js +122 -5
  144. package/src/tools/schemaFixtures.js +1 -1
  145. package/src/ui/agentSurface.js +60 -6
  146. package/src/ui/format/index.js +34 -2
  147. package/src/ui/format/markdownRenderer.js +4 -2
  148. package/src/ui/rustChatHost.js +22 -7
  149. package/src/ui/rustMultiSession.js +14 -2
  150. package/src/ui/rustUcodeHost.js +249 -80
  151. package/src/ui/ucodeAgentSession.js +88 -0
  152. package/templates/groups/build-lane.json +57 -3
  153. package/templates/groups/build-ultra.json +114 -6
  154. package/templates/groups/design-system.json +57 -3
  155. package/templates/groups/product-discovery.json +57 -3
  156. package/templates/groups/ui-plan-review.json +57 -3
  157. package/templates/groups/ui-polish.json +57 -3
  158. package/templates/groups/verify-ship.json +57 -3
  159. package/src/agents/runtime/context/checkpointStore.js +0 -38
  160. package/src/agents/runtime/context/compaction.js +0 -151
@@ -18,6 +18,7 @@ const { resolveDefaultManualBootstrap } = require("../../agents/prompts/defaultB
18
18
  const { detectLaunchEnvironment } = require("../../agents/launch/launchEnvironment");
19
19
  const { isInternalAgentMeta, normalizeInternalAgentType } = require("../contracts/agentMode");
20
20
  const { loadRecoveryGroups, resolveRecoveryGroup, associateAgentWithGroup, recordGroupMemberResume } = require("./agentRecoveryGroups");
21
+ const { buildGroupModelArgs, buildGroupModelEnv } = require("../../orchestration/groups/modelConfig");
21
22
 
22
23
  function normalizeLaunchAgent(agent = "") {
23
24
  const value = String(agent || "").trim().toLowerCase();
@@ -498,23 +499,23 @@ function buildTitleCmd(title) {
498
499
  return `printf '\\033]0;%s\\007' ${shellEscape(title)}`;
499
500
  }
500
501
 
501
- function buildResumeCommand(projectRoot, agent, sessionId) {
502
+ function buildResumeCommand(projectRoot, agent, sessionId, modelSettings = {}) {
502
503
  const binary = toTerminalBinary(agent);
503
504
  if (!binary) {
504
505
  throw new Error(`unsupported agent for resume: ${agent}`);
505
506
  }
506
- const args = buildResumeArgs(agent, sessionId);
507
+ const args = [...buildGroupModelArgs(agent, modelSettings), ...buildResumeArgs(agent, sessionId)];
507
508
  const argText = args.length > 0 ? ` ${args.map(shellEscape).join(" ")}` : "";
508
509
  const skipSessionResolveEnv = "UFOO_SKIP_SESSION_RESOLVE=1 ";
509
510
  return `cd ${shellEscape(projectRoot)} && ${skipSessionResolveEnv}${binary}${argText}`;
510
511
  }
511
512
 
512
- async function tryReuseTerminal(projectRoot, subscriberId, meta, agent, sessionId) {
513
+ async function tryReuseTerminal(projectRoot, subscriberId, meta, agent, sessionId, modelSettings = {}) {
513
514
  if (!meta || !meta.tty) return false;
514
515
  const info = getTtyProcessInfo(meta.tty);
515
516
  if (!info.alive || info.hasAgent || !info.idle) return false;
516
517
  const titleCmd = buildTitleCmd(meta.nickname || "");
517
- const baseCmd = buildResumeCommand(projectRoot, agent, sessionId);
518
+ const baseCmd = buildResumeCommand(projectRoot, agent, sessionId, modelSettings);
518
519
  const command = titleCmd ? `${titleCmd} && ${baseCmd}` : baseCmd;
519
520
  try {
520
521
  const EventBus = require("../../coordination/bus");
@@ -1217,7 +1218,11 @@ function collectRecoverableAgents(projectRoot, target = "", options = {}) {
1217
1218
  continue;
1218
1219
  }
1219
1220
 
1220
- recoverableEntries.push({ id, meta, agent, association: associations.get(id) });
1221
+ const association = associations.get(id);
1222
+ const member = groups.find(group => group.group_id === association.group_id)?.members.find(row => row.subscriber_id === id);
1223
+ const modelSettings = member?.model_source
1224
+ ? { model: member.model, reasoning_effort: member.reasoning_effort, model_provider: member.model_provider } : {};
1225
+ recoverableEntries.push({ id, meta, agent, association, modelSettings });
1221
1226
  }
1222
1227
 
1223
1228
  return {
@@ -1260,7 +1265,7 @@ async function resumeAgents(projectRoot, target = "", processManager = null, opt
1260
1265
  for (const item of recoverableEntries) {
1261
1266
  const nickname = resolveDisplayNickname(projectRoot, item.meta);
1262
1267
  const sessionId = item.meta.provider_session_id;
1263
- const args = buildResumeArgs(item.agent, sessionId);
1268
+ const args = [...buildGroupModelArgs(item.agent, item.modelSettings), ...buildResumeArgs(item.agent, sessionId)];
1264
1269
  let reused = false;
1265
1270
  let resumedId = item.id;
1266
1271
  if (options.internalOnly || isInternalAgentMeta(item.meta) || mode === "internal") {
@@ -1274,7 +1279,8 @@ async function resumeAgents(projectRoot, target = "", processManager = null, opt
1274
1279
  1,
1275
1280
  nickname,
1276
1281
  processManager,
1277
- { UFOO_SKIP_SESSION_RESOLVE: "1", UFOO_SCOPED_NICKNAME: item.meta.scoped_nickname || "" },
1282
+ { UFOO_SKIP_SESSION_RESOLVE: "1", UFOO_SCOPED_NICKNAME: item.meta.scoped_nickname || "",
1283
+ ...buildGroupModelEnv(item.agent, item.modelSettings) },
1278
1284
  args,
1279
1285
  { replaceAgentId: item.id, providerSessionId: sessionId }
1280
1286
  );
@@ -1284,7 +1290,7 @@ async function resumeAgents(projectRoot, target = "", processManager = null, opt
1284
1290
  associateAgentWithGroup(projectRoot, resumedId, item.association);
1285
1291
  recordGroupMemberResume(projectRoot, item.association, item.id, resumedId);
1286
1292
  } else {
1287
- reused = await tryReuseTerminal(projectRoot, item.id, item.meta, item.agent, sessionId);
1293
+ reused = await tryReuseTerminal(projectRoot, item.id, item.meta, item.agent, sessionId, item.modelSettings);
1288
1294
  if (!reused) {
1289
1295
  const envPrefix = "UFOO_SKIP_SESSION_RESOLVE=1";
1290
1296
  if (mode === "tmux") {
@@ -4,7 +4,7 @@ const { isInternalAgentMeta } = require("../../runtime/contracts/agentMode");
4
4
  function listAgentsHandler(ctx = {}) {
5
5
  const status = buildStatus(ctx.projectRoot);
6
6
  const agents = (Array.isArray(status.active_meta) ? status.active_meta : [])
7
- .filter((agent) => !ctx.internalAgentsOnly || isInternalAgentMeta(agent));
7
+ .filter((agent) => !ctx.internalAgentsOnly || ctx.includeExternalAgents || isInternalAgentMeta(agent));
8
8
  return {
9
9
  count: agents.length,
10
10
  agents,
@@ -4,7 +4,7 @@ const { isInternalAgentMeta } = require("../../runtime/contracts/agentMode");
4
4
  function readBusSummaryHandler(ctx = {}) {
5
5
  const status = buildStatus(ctx.projectRoot);
6
6
  const activeAgents = (Array.isArray(status.active_meta) ? status.active_meta : [])
7
- .filter((agent) => !ctx.internalAgentsOnly || isInternalAgentMeta(agent));
7
+ .filter((agent) => !ctx.internalAgentsOnly || ctx.includeExternalAgents || isInternalAgentMeta(agent));
8
8
  const busyCount = activeAgents.filter((item) => {
9
9
  const state = String((item && item.activity_state) || "").trim().toLowerCase();
10
10
  return state === "working"
@@ -1,11 +1,107 @@
1
1
  "use strict";
2
2
 
3
3
  const fs = require("fs");
4
+ const path = require("path");
4
5
  const { getUfooPaths } = require("../../coordination/state/paths");
6
+ const { getReportPaths } = require("../../coordination/report/store");
5
7
  const { isMetaActive } = require("../../coordination/bus/utils");
6
8
  const { isInternalAgentMeta } = require("../../runtime/contracts/agentMode");
7
9
  const { buildToolError } = require("./common");
8
10
 
11
+ function extractRoutingTokens(text) {
12
+ const input = String(text || "").toLowerCase();
13
+ const tokens = new Set(input.match(/[a-z0-9_.-]{3,}/g) || []);
14
+ const paths = input.match(/[a-z0-9_.-]+(?:\/[a-z0-9_.-]+)+/g) || [];
15
+ for (const p of paths) {
16
+ tokens.add(p);
17
+ const base = path.posix.basename(p);
18
+ if (base) tokens.add(base);
19
+ }
20
+ const cjkRuns = input.match(/[\u4e00-\u9fff]+/g) || [];
21
+ for (const run of cjkRuns) {
22
+ if (run.length === 1) {
23
+ tokens.add(run);
24
+ continue;
25
+ }
26
+ for (let i = 0; i < run.length - 1; i += 1) {
27
+ tokens.add(run.slice(i, i + 2));
28
+ }
29
+ }
30
+ return tokens;
31
+ }
32
+
33
+ function readRecentReportsByAgent(projectRoot, maxLines = 100) {
34
+ const byAgent = new Map();
35
+ if (!projectRoot) return byAgent;
36
+ try {
37
+ const { reportsFile } = getReportPaths(projectRoot);
38
+ if (!fs.existsSync(reportsFile)) return byAgent;
39
+ const raw = fs.readFileSync(reportsFile, "utf8");
40
+ const lines = raw.split("\n").filter((line) => line.trim()).slice(-maxLines);
41
+ for (const line of lines) {
42
+ let row;
43
+ try { row = JSON.parse(line); } catch { continue; }
44
+ const agentId = String(row && (row.agent_id || row.agentId) || "").trim();
45
+ if (!agentId) continue;
46
+ if (!byAgent.has(agentId)) byAgent.set(agentId, []);
47
+ byAgent.get(agentId).push(row);
48
+ }
49
+ } catch {}
50
+ return byAgent;
51
+ }
52
+
53
+ function buildWorkerHistorySignals(ctx = {}) {
54
+ const signals = new Map();
55
+ const appendText = (agentId, chunk) => {
56
+ const id = String(agentId || "").trim();
57
+ if (!id) return;
58
+ if (!signals.has(id)) signals.set(id, { text: "", consecutiveErrors: 0 });
59
+ const entry = signals.get(id);
60
+ if (chunk) entry.text += `\n${String(chunk).toLowerCase()}`;
61
+ };
62
+
63
+ try {
64
+ const tasks = ctx.agentManagement && typeof ctx.agentManagement.snapshot === "function"
65
+ ? Object.values(ctx.agentManagement.snapshot().tasks || {})
66
+ : [];
67
+ for (const task of tasks) {
68
+ if (!task || typeof task !== "object") continue;
69
+ const workerId = task.agentId || task.target || task.workerId || "";
70
+ if (!workerId) continue;
71
+ appendText(workerId, [
72
+ task.objective,
73
+ task.topic,
74
+ task.summary,
75
+ ...(Array.isArray(task.modifiedFiles) ? task.modifiedFiles : []),
76
+ ...(Array.isArray(task.touchedFiles) ? task.touchedFiles : []),
77
+ ].filter(Boolean).join(" "));
78
+ }
79
+ } catch {}
80
+
81
+ const reportsByAgent = readRecentReportsByAgent(ctx.projectRoot, 100);
82
+ for (const [agentId, rows] of reportsByAgent.entries()) {
83
+ for (const row of rows) {
84
+ appendText(agentId, [
85
+ row.summary,
86
+ row.message,
87
+ row.error,
88
+ row.meta ? JSON.stringify(row.meta) : "",
89
+ ].filter(Boolean).join(" "));
90
+ }
91
+ let streak = 0;
92
+ for (let i = rows.length - 1; i >= 0; i -= 1) {
93
+ const row = rows[i];
94
+ if (row.phase === "start" || row.phase === "progress") continue;
95
+ if (row.ok === false || row.phase === "error") streak += 1;
96
+ else break;
97
+ }
98
+ if (!signals.has(agentId)) signals.set(agentId, { text: "", consecutiveErrors: streak });
99
+ else signals.get(agentId).consecutiveErrors = streak;
100
+ }
101
+
102
+ return signals;
103
+ }
104
+
9
105
  /** Read-only routing preview. Selection never launches or dispatches work. */
10
106
  function routeAgentHandler(ctx = {}, args = {}) {
11
107
  if (typeof args.request !== "string" || !args.request.trim()) throw buildToolError("invalid_arguments", "route_agent requires request");
@@ -13,23 +109,44 @@ function routeAgentHandler(ctx = {}, args = {}) {
13
109
  const bus = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, "utf8")) : { agents: {} };
14
110
  const hint = String(args.context_hint || "").toLowerCase();
15
111
  const text = `${args.request} ${hint}`.toLowerCase();
16
- const tokens = new Set(text.match(/[a-z0-9_-]{3,}/g) || []);
112
+ const tokens = extractRoutingTokens(text);
113
+ const historySignals = buildWorkerHistorySignals(ctx);
17
114
  const candidates = Object.entries(bus.agents || {}).filter(([id, meta]) => (
18
115
  id !== "ufoo-agent" && meta.agent_type !== "ufoo-agent" && isMetaActive(meta)
19
- && (!ctx.internalAgentsOnly || isInternalAgentMeta(meta))
116
+ && (!ctx.internalAgentsOnly || ctx.includeExternalAgents || isInternalAgentMeta(meta))
20
117
  )).map(([id, meta]) => {
21
118
  const nickname = String(meta.nickname || "");
22
119
  const role = String(meta.role || meta.solo_role || meta.prompt_profile || "").toLowerCase();
23
120
  const explicit = [id, nickname].some((name) => name && (hint === name.toLowerCase() || text.includes(`@${name.toLowerCase()}`)));
24
121
  const matches = [...tokens].filter((token) => role.includes(token)).length;
122
+ const workerHistory = historySignals.get(id) || { text: "", consecutiveErrors: 0 };
123
+ const historyMatches = workerHistory.text
124
+ ? [...tokens].filter((token) => workerHistory.text.includes(token)).length
125
+ : 0;
25
126
  const idle = ["idle", "waiting", ""].includes(meta.activity_state || "");
26
- return { id, nickname, explicit, matches, idle, score: (explicit ? 100 : 0) + matches * 10 + (idle ? 1 : 0) };
127
+ const errorPenalty = workerHistory.consecutiveErrors >= 2 ? 5 : 0;
128
+ const score = (explicit ? 100 : 0)
129
+ + matches * 10
130
+ + Math.min(32, historyMatches * 8)
131
+ + (idle ? 2 : 0)
132
+ - errorPenalty;
133
+ return { id, nickname, explicit, matches, historyMatches, idle, score };
27
134
  }).sort((a, b) => b.score - a.score || a.id.localeCompare(b.id));
28
135
  const selected = candidates[0];
29
136
  if (!selected) return { target: "", nickname: "", reason: "No active worker in this project; choose direct execution or launch explicitly.", confidence: 0 };
30
137
  return { target: selected.id, nickname: selected.nickname,
31
- reason: selected.explicit ? "Explicit worker reference" : selected.matches ? "Matching role/profile" : selected.idle ? "Available project worker" : "Active project worker; currently busy",
32
- confidence: selected.explicit ? 1 : selected.matches ? 0.8 : 0.4 };
138
+ reason: selected.explicit
139
+ ? "Explicit worker reference"
140
+ : selected.matches && selected.historyMatches
141
+ ? "Matching role and prior file/topic history"
142
+ : selected.historyMatches
143
+ ? "Prior file/topic experience in recent reports/tasks"
144
+ : selected.matches
145
+ ? "Matching role/profile"
146
+ : selected.idle
147
+ ? "Available project worker"
148
+ : "Active project worker; currently busy",
149
+ confidence: selected.explicit ? 1 : (selected.matches || selected.historyMatches) ? 0.85 : 0.4 };
33
150
  }
34
151
 
35
152
  module.exports = { routeAgentHandler };
@@ -604,7 +604,7 @@ const MANAGE_CRON_SCHEMA = Object.freeze({
604
604
 
605
605
  const READ_AGENT_TRACE_SCHEMA = Object.freeze({ name: "read_agent_trace", schema_version: SCHEMA_VERSION,
606
606
  tier: "tier0-read", allowed_tiers: CALLER_TIERS_READ_COORD,
607
- description: "Read a task timeline across main/worker model and tool events, reports, queue state and context compaction, with an observed performance summary. Default shows the latest events with concise summaries; details includes redacted parameters/results. This is observation only, not acceptance or delivery acknowledgement.",
607
+ description: "Read a task timeline across main/worker model and tool events, reports, queue state and context window/indexing, with an observed performance summary. Default shows the latest events with concise summaries; details includes redacted parameters/results. This is observation only, not acceptance or delivery acknowledgement.",
608
608
  input_schema: { type: "object", properties: {
609
609
  task_id: { type: "string", description: "Exact delegated task ID or parent taskRunId; includes related descendants." },
610
610
  agent_id: { type: "string", description: "Worker subscriber ID or registered nickname." }, session_id: { type: "string" },
@@ -26,6 +26,22 @@ function createAgentSurface(options = {}) {
26
26
  const background = new Map();
27
27
  let contextUsage = "";
28
28
  const tools = new Map();
29
+ const renderedEntries = new WeakMap();
30
+
31
+ function presentEntry(row) {
32
+ if (!["assistant", "thinking"].includes(row.kind) || /\x1b\[/.test(row.text)) return { ...row };
33
+ let cached = renderedEntries.get(row);
34
+ if (!cached || cached.source !== row.text) {
35
+ cached = { source: row.text, text: fmt.renderLogLinesWithMarkdownAnsi(row.text, { inCodeBlock: false }).join("\n") };
36
+ renderedEntries.set(row, cached);
37
+ }
38
+ return { ...row, text: cached.text };
39
+ }
40
+
41
+ function getEntry(id) {
42
+ const row = entries.find((row) => row.id === id);
43
+ return row ? presentEntry(row) : null;
44
+ }
29
45
 
30
46
  function bound() {
31
47
  for (const entry of entries) {
@@ -64,12 +80,30 @@ function createAgentSurface(options = {}) {
64
80
  busy = true;
65
81
  startedAt = Date.now();
66
82
  } else if (name === "stream.delta") {
67
- entry(payload.id || "stream", "assistant").text += String(payload.text || payload.delta || "");
83
+ const id = payload.id || "stream";
84
+ let row = entries.find((item) => item.id === id);
85
+ if (!row) {
86
+ row = { id, kind: "assistant", text: "", detail: "", speaker: "", expanded: false };
87
+ if (payload.aboveTools) {
88
+ let insertIdx = entries.length;
89
+ while (insertIdx > 0 && ["tool", "thinking"].includes(entries[insertIdx - 1].kind)) {
90
+ insertIdx -= 1;
91
+ }
92
+ entries.splice(insertIdx, 0, row);
93
+ } else {
94
+ entries.push(row);
95
+ }
96
+ }
97
+ const chunk = String(payload.text || payload.delta || "");
98
+ row.text = payload.reset ? chunk : row.text + chunk;
68
99
  busy = true;
69
100
  if (!startedAt) startedAt = Date.now();
70
101
  } else if (name === "thinking.start" || name === "thinking.delta") {
71
102
  const row = entry(payload.id || "thinking", "thinking");
72
- if (name === "thinking.delta") row.text += String(payload.text || "");
103
+ if (name === "thinking.delta") {
104
+ const chunk = String(payload.text || "");
105
+ row.text = payload.reset ? chunk : row.text + chunk;
106
+ }
73
107
  } else if (name === "stream.done") {
74
108
  busy = false;
75
109
  status = payload.reason === "error" ? "error" : "ready";
@@ -260,11 +294,31 @@ function createAgentSurface(options = {}) {
260
294
  const done = bg.filter((task) => task.status === "completed").length;
261
295
  const failed = bg.filter((task) => ["failed", "stopped", "killed"].includes(task.status)).length;
262
296
  const suffix = [running && `${running} running`, done && `${done} done`, failed && `${failed} failed`].filter(Boolean).join("/");
263
- const label = `${status}${!busy && status === "ready" && idlePlanHint ? ` · ${idlePlanHint}` : ""}${submitted.length > 1 || (submitted.length && runningTask) ? ` · queued ${submitted.length}` : ""}${suffix ? ` · BG ${suffix}` : ""}`;
264
- return { entries: entries.map((row) => ({ ...row })), status: label, busy, usage, plan: plan.slice(), revision, started_at: startedAt };
297
+ const label = `${status}${!busy && status === "ready" && idlePlanHint ? ` · ${idlePlanHint}` : ""}${submitted.length > 1 || (submitted.length && runningTask) ? ` · queued ${submitted.length} · Alt+Enter immediately` : ""}${suffix ? ` · BG ${suffix}` : ""}`;
298
+ return { entries: entries.map(presentEntry), status: label, busy, usage, plan: plan.slice(), revision, started_at: startedAt };
265
299
  }
266
300
 
267
- return { apply, accept, snapshot, toggleExpanded };
301
+ return { apply, accept, snapshot, getEntry, toggleExpanded };
302
+ }
303
+
304
+ // Keep source deltas in the surface; send the rendered entry as a replacement
305
+ // so delimiters split across chunks and multi-line tables can be re-evaluated.
306
+ function projectSurfaceEvent(surface, name, payload = {}) {
307
+ const delta = name === "stream.delta" || name === "thinking.delta";
308
+ const id = payload.id || (name === "thinking.delta" ? "thinking" : "stream");
309
+ const exists = delta && Boolean(surface.getEntry(id));
310
+ surface.apply(name, payload);
311
+ if (delta) {
312
+ const snapEntries = surface.snapshot().entries;
313
+ const isLast = snapEntries.length > 0 && snapEntries[snapEntries.length - 1].id === id;
314
+ if (!exists && !isLast) {
315
+ return { name: "transcript.reset", payload: { entries: snapEntries } };
316
+ }
317
+ const row = surface.getEntry(id);
318
+ return { name: exists ? "transcript.patch" : "transcript.append", payload: row };
319
+ }
320
+ if (name === "transcript.reset") return { name, payload: { ...payload, entries: surface.snapshot().entries } };
321
+ return { name, payload };
268
322
  }
269
323
 
270
- module.exports = { createAgentSurface };
324
+ module.exports = { createAgentSurface, projectSurfaceEvent };
@@ -37,6 +37,7 @@ const TOOL_LABELS = {
37
37
  edit: "Editing file",
38
38
  bash: "Running command",
39
39
  artifact_read: "Reading artifact",
40
+ recall_turn: "Recalling past turn",
40
41
  plan_graph: "Updating plan",
41
42
  task_run: "Managing task",
42
43
  ask_user: "Asking user",
@@ -738,7 +739,26 @@ function formatPendingElapsed(ms = 0) {
738
739
  function normalizeBashToolCommand(args = {}, payload = {}) {
739
740
  const argObj = args && typeof args === "object" ? args : {};
740
741
  const resObj = payload && typeof payload === "object" ? payload : {};
742
+ const action = String(argObj.action || resObj.action || "run").trim().toLowerCase() || "run";
743
+ const bgId = String(argObj.backgroundId || resObj.backgroundId || "").trim();
744
+ if (action === "list") {
745
+ const countPart = Number.isFinite(resObj.runningCount) && Number.isFinite(resObj.count)
746
+ ? `${resObj.runningCount}/${resObj.count} running`
747
+ : "";
748
+ return ["bg list", countPart].filter(Boolean).join(" · ");
749
+ }
750
+ if (action === "logs" || action === "status" || action === "stop") {
751
+ const statusPart = resObj.status ? String(resObj.status) : "";
752
+ const offsetPart = action === "logs" && Number.isFinite(argObj.offset) ? `@${argObj.offset}` : "";
753
+ return [`bg ${action}`, bgId, offsetPart, statusPart].filter(Boolean).join(" · ");
754
+ }
741
755
  const command = String(argObj.command || argObj.cmd || "").trim();
756
+ if (argObj.background || resObj.kind === "background_bash") {
757
+ const statusPart = resObj.status
758
+ ? String(resObj.status)
759
+ : (Number.isFinite(resObj.code) ? `exit ${resObj.code}` : "");
760
+ return ["bg", command, bgId, statusPart].filter(Boolean).join(" · ");
761
+ }
742
762
  const code = Number.isFinite(resObj.code) ? `exit ${resObj.code}` : "";
743
763
  return [command, code].filter(Boolean).join(" · ");
744
764
  }
@@ -778,6 +798,17 @@ function normalizeToolLogDetail(tool = "", args = {}, payload = {}) {
778
798
  return [artifactId, range].filter(Boolean).join(" · ");
779
799
  }
780
800
 
801
+ if (name === "recall_turn") {
802
+ const turnId = String(argObj.turn_id || argObj.turnId || resObj.turnId || "").trim();
803
+ const mode = String(argObj.mode || (turnId && !argObj.query ? "detail" : "search")).trim().toLowerCase();
804
+ if (mode === "detail") {
805
+ const pageBit = argObj.page != null ? `p${argObj.page}` : "";
806
+ return ["detail", turnId, pageBit].filter(Boolean).join(" · ");
807
+ }
808
+ const queryText = shortenPathDetail(String(argObj.query || argObj.topic || "").trim(), 48);
809
+ return ["search", queryText].filter(Boolean).join(" · ");
810
+ }
811
+
781
812
  const fallback = String(argObj.path || argObj.command || argObj.cmd || "").trim();
782
813
  return shortenPathDetail(fallback);
783
814
  }
@@ -1220,12 +1251,13 @@ function buildCompletions({
1220
1251
  }
1221
1252
 
1222
1253
  // Generic top-level argument lists (e.g. /resume <session-id>,
1223
- // /model <id> [thinking]). /model supports a secondary intensity menu.
1254
+ // /model <id> [thinking]). /model supports a secondary intensity menu
1255
+ // and opens its candidate list immediately when `/model` is typed.
1224
1256
  if (
1225
1257
  Array.isArray(argListForHead)
1226
1258
  && argListForHead.length > 0
1227
1259
  && !(headNode && headNode.children)
1228
- && (endsWithWhitespace || tail.length >= 1)
1260
+ && (endsWithWhitespace || tail.length >= 1 || headKey === "/model")
1229
1261
  ) {
1230
1262
  const secondaryList = argumentLists && typeof argumentLists === "object"
1231
1263
  ? argumentLists[`${headKey}/thinking`] || argumentLists[`${headKey}/think`]
@@ -222,8 +222,10 @@ function renderInlineMarkdown(input = "", adapters = createBlessedAdapters()) {
222
222
  let out = "";
223
223
  let i = 0;
224
224
  while (i < source.length) {
225
+ // Underscores inside identifiers/filenames are literal, as in GFM.
226
+ const canOpenUnderscore = i === 0 || !/[\p{L}\p{N}_]/u.test(source[i - 1]);
225
227
  // **bold** / __bold__
226
- if (source.startsWith("**", i) || source.startsWith("__", i)) {
228
+ if (source.startsWith("**", i) || source.startsWith("__", i) && canOpenUnderscore) {
227
229
  const mark = source.slice(i, i + 2);
228
230
  const close = source.indexOf(mark, i + 2);
229
231
  if (close !== -1) {
@@ -253,7 +255,7 @@ function renderInlineMarkdown(input = "", adapters = createBlessedAdapters()) {
253
255
  // *italic* / _italic_ (single delimiter; avoid ** / __)
254
256
  if (
255
257
  (source[i] === "*" && source[i + 1] !== "*")
256
- || (source[i] === "_" && source[i + 1] !== "_")
258
+ || (source[i] === "_" && source[i + 1] !== "_" && canOpenUnderscore)
257
259
  ) {
258
260
  const mark = source[i];
259
261
  const close = source.indexOf(mark, i + 1);
@@ -61,12 +61,13 @@ function parseWindowModeArgs(args = []) {
61
61
  return ["main", "side", "multi"].includes(text) ? text : "";
62
62
  }
63
63
 
64
- function resolveSubmittedInputTarget(payload, currentTarget, isInternalAgent) {
65
- const target = String(payload.target_agent || payload.targetAgent || "").trim();
66
- if ((payload.has_target && !target) || (target && !isInternalAgent(target))) {
67
- return { ok: false, error: "Unknown internal target" };
64
+ function resolveSubmittedInputTarget(payload, currentTarget, isKnownAgent) {
65
+ const explicit = String(payload.target_agent || payload.targetAgent || "").trim();
66
+ const target = explicit || (payload.input_target === "main" ? null : currentTarget);
67
+ if ((payload.has_target && !explicit) || (target && !isKnownAgent(target))) {
68
+ return { ok: false, error: "Unknown or inactive target" };
68
69
  }
69
- return { ok: true, target: target || (payload.input_target === "main" ? null : currentTarget) };
70
+ return { ok: true, target: target || null };
70
71
  }
71
72
 
72
73
  function stripTags(value) {
@@ -504,6 +505,9 @@ async function runChatRust(projectRoot, options = {}) {
504
505
  isInternalAgent(agentId) {
505
506
  return isInternalAgentMeta(controller.session.metaMap.get(String(agentId || "").trim()));
506
507
  },
508
+ isKnownAgent(agentId) {
509
+ return controller.session.agents.includes(String(agentId || "").trim());
510
+ },
507
511
  /** Activate an internal child in the one-child window mode. */
508
512
  startSide(agentId) {
509
513
  const id = String(agentId || "").trim();
@@ -922,7 +926,7 @@ async function runChatRust(projectRoot, options = {}) {
922
926
  }
923
927
  if (name === "agent.select") {
924
928
  const agentId = String(payload.agent_id || payload.agentId || "").trim();
925
- if (agentId && !hostApi.isInternalAgent(agentId)) return { ok: false, error: "Unknown internal agent" };
929
+ if (agentId && !hostApi.isKnownAgent(agentId)) return { ok: false, error: "Unknown or inactive agent" };
926
930
  if (agentId) {
927
931
  controller.session.targetAgent = agentId;
928
932
  const label = payload.label || agentId;
@@ -935,6 +939,12 @@ async function runChatRust(projectRoot, options = {}) {
935
939
  }
936
940
  if (name === "agent.open") {
937
941
  const agentId = String(payload.agent_id || payload.agentId || "").trim();
942
+ if (hostApi.isKnownAgent(agentId) && !hostApi.isInternalAgent(agentId)) {
943
+ multiSession?.handleFocus({ target: "chat" });
944
+ controller.session.targetAgent = agentId;
945
+ publish("prompt.set_prefix", { prefix: `›@${getAgentLabel(agentId)} ` });
946
+ return { ok: true, mode: "message", agent_id: agentId };
947
+ }
938
948
  return hostApi.activateInternalAgent(agentId) || { ok: true, agent_id: agentId };
939
949
  }
940
950
  if (name === "window.set" || name === "window.cycle") {
@@ -963,6 +973,7 @@ async function runChatRust(projectRoot, options = {}) {
963
973
  ? multiSession.handleScroll(payload)
964
974
  : { ok: false, error: "multi not active" };
965
975
  }
976
+ if (name === "multi.cancel") return multiSession?.handleCancel(payload) || { ok: false };
966
977
  if (name === "multi.expand") return multiSession?.handleExpand(payload) || { ok: false };
967
978
  if (name === "agent.close") {
968
979
  const agentId = String(payload.agent_id || payload.agentId || "").trim();
@@ -1062,7 +1073,7 @@ async function runChatRust(projectRoot, options = {}) {
1062
1073
  const text = String(payload.text || "");
1063
1074
  // The submitted identity wins over mutable footer/focus state. Never
1064
1075
  // send an unresolved explicit child target to the main agent.
1065
- const routing = resolveSubmittedInputTarget(payload, controller.session.targetAgent, hostApi.isInternalAgent);
1076
+ const routing = resolveSubmittedInputTarget(payload, controller.session.targetAgent, hostApi.isKnownAgent);
1066
1077
  if (!routing.ok) return routing;
1067
1078
  controller.session.targetAgent = routing.target;
1068
1079
  const childOrLayout = Boolean(routing.target)
@@ -1071,6 +1082,10 @@ async function runChatRust(projectRoot, options = {}) {
1071
1082
  // depend solely on tryActivate → focusMultiPane chain).
1072
1083
  if (!text.trim()) {
1073
1084
  const target = routing.target;
1085
+ if (target && !hostApi.isInternalAgent(target)) {
1086
+ publish("prompt.set_prefix", { prefix: `›@${getAgentLabel(target)} ` });
1087
+ return { ok: true, routed: "message", agent_id: target };
1088
+ }
1074
1089
  if (target && hostApi.isInternalAgent(target)
1075
1090
  && !(multiSession && multiSession.isMultiKind && multiSession.isMultiKind())) {
1076
1091
  const side = hostApi.startSide(target);
@@ -3,8 +3,8 @@
3
3
  /**
4
4
  * In-process split-pane session for the Rust TUI host.
5
5
  *
6
- * Both kinds use Tab to cycle focus and Esc / Ctrl+C to return focus to chat,
7
- * then close the split. Only Ctrl+C exits the application at the root.
6
+ * Both kinds let Esc return child input focus to the main pane. Ctrl+C cancels
7
+ * the focused child's current task; it never closes the worker or split.
8
8
  * Window modes are main, side and multi, including when no children exist.
9
9
  * They share draw and the multi.* pane wire:
10
10
  * - "multi" — all internal agents
@@ -61,6 +61,7 @@ function createRustMultiSession(options = {}) {
61
61
  getAgentMeta = () => ({}),
62
62
  resolvePaneOptions = () => ({ mode: "internal" }),
63
63
  onInternalSubmit = () => {},
64
+ onInternalCancel = (id) => require("../agents/internal/taskControl").cancelInternalTask(getProjectRoot(), id),
64
65
  publish = () => {},
65
66
  publishLossy = null,
66
67
  getLabel = (id) => id,
@@ -569,6 +570,16 @@ function createRustMultiSession(options = {}) {
569
570
  return { ok: true };
570
571
  }
571
572
 
573
+ async function handleCancel(payload = {}) {
574
+ if (!active || !paneManager) return { ok: false, error: "multi not active" };
575
+ if (payload.session_id && payload.session_id !== sessionId) return { ok: false, error: "stale session_id" };
576
+ const id = String(payload.agent_id || "");
577
+ if (!paneManager.getPane(id) || !listInternalAgentIds().includes(id)) return { ok: false, error: "Unknown internal agent" };
578
+ const result = await onInternalCancel(id);
579
+ if (!result?.ok) acceptEvent(id, { type: "text_delta", delta: `\n${result?.error || "Cancellation failed"}\n` });
580
+ return result;
581
+ }
582
+
572
583
  function handleScroll(payload = {}) {
573
584
  if (!active || !paneManager) return { ok: false, error: "multi not active" };
574
585
  if (payload.session_id && payload.session_id !== sessionId) return { ok: false, error: "stale session_id" };
@@ -685,6 +696,7 @@ function createRustMultiSession(options = {}) {
685
696
  getSnapshot,
686
697
  handleViewport,
687
698
  handleRaw,
699
+ handleCancel,
688
700
  handleScroll,
689
701
  handleFocus,
690
702
  focusAgent,