u-foo 4.0.5 → 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 (149) hide show
  1. package/README.md +224 -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 +5 -3
  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 +36 -20
  49. package/src/agents/providers/providerId.js +17 -0
  50. package/src/agents/providers/runtimeConfig.js +26 -19
  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 -2
  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 +95 -32
  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/features/doctor.js +21 -0
  80. package/src/app/cli/metricsCommands.js +1 -1
  81. package/src/app/cli/run.js +80 -1
  82. package/src/app/cli/setupCommands.js +200 -0
  83. package/src/code/UcodeController.js +31 -1
  84. package/src/code/agent.js +41 -7
  85. package/src/code/busConsumer.js +13 -12
  86. package/src/code/commands.js +0 -1
  87. package/src/code/context/assembler.js +11 -88
  88. package/src/code/context/planGraphService.js +83 -9
  89. package/src/code/context/planProjection.js +10 -2
  90. package/src/code/context/reducers.js +172 -4
  91. package/src/code/context/stateCommit.js +0 -32
  92. package/src/code/context/transcript.js +7 -4
  93. package/src/code/internalThread.js +9 -1
  94. package/src/code/launcher/ucode.js +4 -2
  95. package/src/code/nativeRunner.js +221 -10
  96. package/src/code/repl.js +27 -1
  97. package/src/code/runtime/agentWakeup.js +20 -3
  98. package/src/code/runtime/backgroundWakeHost.js +45 -0
  99. package/src/code/runtime/taskFocusContext.js +7 -0
  100. package/src/code/runtime/taskLoop.js +24 -1
  101. package/src/code/sessionStore.js +14 -10
  102. package/src/code/taskDecomposer.js +13 -7
  103. package/src/code/tools/backgroundProcess.js +23 -0
  104. package/src/code/tools/bash.js +764 -12
  105. package/src/code/tools/executor.js +12 -4
  106. package/src/code/tools/specs.js +60 -3
  107. package/src/code/tools/taskRun.js +38 -0
  108. package/src/config.js +92 -6
  109. package/src/coordination/bus/subscriber.js +1 -1
  110. package/src/coordination/history/agentPerformance.js +18 -18
  111. package/src/coordination/history/agentTrace.js +7 -3
  112. package/src/coordination/state/workspaceAccess.js +3 -1
  113. package/src/orchestration/groups/modelConfig.js +66 -0
  114. package/src/orchestration/groups/validateTemplate.js +2 -0
  115. package/src/runtime/browser/broker.js +1027 -0
  116. package/src/runtime/browser/brokerClient.js +108 -0
  117. package/src/runtime/browser/componentInstaller.js +275 -0
  118. package/src/runtime/browser/installState.js +329 -0
  119. package/src/runtime/browser/manifest.js +145 -0
  120. package/src/runtime/browser/native-host-runner.js +198 -0
  121. package/src/runtime/browser/nativeHost.js +213 -0
  122. package/src/runtime/browser/nativeMessagingProtocol.js +50 -0
  123. package/src/runtime/browser/paths.js +134 -0
  124. package/src/runtime/browser/playwrightSession.js +614 -0
  125. package/src/runtime/daemon/agentHost.js +175 -30
  126. package/src/runtime/daemon/busBridge.js +2 -1
  127. package/src/runtime/daemon/globalDaemon.js +20 -0
  128. package/src/runtime/daemon/groupOrchestrator.js +20 -1
  129. package/src/runtime/daemon/index.js +5 -4
  130. package/src/runtime/daemon/ops.js +14 -8
  131. package/src/tools/handlers/listAgents.js +1 -1
  132. package/src/tools/handlers/readBusSummary.js +1 -1
  133. package/src/tools/handlers/routeAgent.js +122 -5
  134. package/src/tools/schemaFixtures.js +1 -1
  135. package/src/ui/agentSurface.js +26 -3
  136. package/src/ui/format/index.js +34 -2
  137. package/src/ui/rustChatHost.js +22 -7
  138. package/src/ui/rustMultiSession.js +14 -2
  139. package/src/ui/rustUcodeHost.js +246 -77
  140. package/src/ui/ucodeAgentSession.js +88 -0
  141. package/templates/groups/build-lane.json +57 -3
  142. package/templates/groups/build-ultra.json +114 -6
  143. package/templates/groups/design-system.json +57 -3
  144. package/templates/groups/product-discovery.json +57 -3
  145. package/templates/groups/ui-plan-review.json +57 -3
  146. package/templates/groups/ui-polish.json +57 -3
  147. package/templates/groups/verify-ship.json +57 -3
  148. package/src/agents/runtime/context/checkpointStore.js +0 -52
  149. package/src/agents/runtime/context/compaction.js +0 -171
@@ -19,6 +19,7 @@ const { createEnvelope, encodeMessage } = require("../runtime/contracts/uiProtoc
19
19
  const fmt = require("./format");
20
20
  const { createAgentSurface, projectSurfaceEvent } = require("./agentSurface");
21
21
  const { buildPlanSetPayload, statusForAgentPhase } = require("./agentPresentation");
22
+ const { countRunningBackgroundProcesses } = require("../code/tools/bash");
22
23
  const PACKAGE_VERSION = require("../../package.json").version;
23
24
 
24
25
  function stripTags(value) {
@@ -30,6 +31,7 @@ function buildUcodeAgentsSnapshot(workspaceRoot, selfSubscriberId = "") {
30
31
  fmt.loadActiveAgents(workspaceRoot),
31
32
  selfSubscriberId
32
33
  );
34
+ const metadata = require("../coordination/state/agentsStore").loadAgentsData(require("../coordination/state/paths").getUfooPaths(workspaceRoot).agentsFile).agents || {};
33
35
  const agents = list.map((agent) => {
34
36
  const id = String((agent && (agent.fullId || agent.id)) || "").trim();
35
37
  const label = String(
@@ -38,6 +40,7 @@ function buildUcodeAgentsSnapshot(workspaceRoot, selfSubscriberId = "") {
38
40
  return {
39
41
  id,
40
42
  label,
43
+ internal: require("../runtime/contracts/agentMode").isInternalAgentMeta(metadata[id]),
41
44
  activity_state: String((agent && agent.status) || ""),
42
45
  };
43
46
  }).filter((agent) => agent.id);
@@ -158,6 +161,95 @@ function createLeadingWhitespaceNormalizer() {
158
161
  };
159
162
  }
160
163
 
164
+ /**
165
+ * Keep a single assistant bubble and a single accumulating tool group per user
166
+ * prompt. When a new model step emits commentary after tool calls or thinking,
167
+ * replace the bubble text in-place so only the latest message is shown above
168
+ * the accumulating tool tree.
169
+ */
170
+ function createSegmentedStreamSession({
171
+ baseId = "stream",
172
+ publish,
173
+ tools = null,
174
+ thinking = null,
175
+ onToolEntry = null,
176
+ } = {}) {
177
+ const currentId = String(baseId || "stream");
178
+ let replaceOnNextDelta = false;
179
+ let hasStreamedAnyText = false;
180
+ let responseStarted = false;
181
+ const thinkingLog = createThinkingLogPublisher(publish, thinking, currentId);
182
+ let normalizeStreamDelta = createLeadingWhitespaceNormalizer();
183
+
184
+ if (tools && typeof tools.beginScope === "function") tools.beginScope();
185
+ if (thinking && typeof thinking.reset === "function") thinking.reset();
186
+ publish("stream.start", { id: currentId });
187
+
188
+ function beginResponse() {
189
+ if (responseStarted) return;
190
+ responseStarted = true;
191
+ thinkingLog.stop();
192
+ publish("status.set", { text: "Generating response…", busy: true });
193
+ }
194
+
195
+ function onTextPhase(event = {}) {
196
+ if (String(event.text || "").trim()) {
197
+ beginResponse();
198
+ }
199
+ }
200
+
201
+ function onDelta(delta) {
202
+ if (replaceOnNextDelta) {
203
+ const freshNormalizer = createLeadingWhitespaceNormalizer();
204
+ const visibleDelta = freshNormalizer(delta);
205
+ if (!visibleDelta) return;
206
+ normalizeStreamDelta = freshNormalizer;
207
+ replaceOnNextDelta = false;
208
+ hasStreamedAnyText = true;
209
+ beginResponse();
210
+ publish("stream.delta", { id: currentId, text: visibleDelta, reset: true, aboveTools: true });
211
+ return;
212
+ }
213
+ const visibleDelta = normalizeStreamDelta(delta);
214
+ if (!visibleDelta) return;
215
+ hasStreamedAnyText = true;
216
+ beginResponse();
217
+ publish("stream.delta", { id: currentId, text: visibleDelta, aboveTools: true });
218
+ }
219
+
220
+ function onThinkingDelta(delta) {
221
+ if (hasStreamedAnyText) {
222
+ replaceOnNextDelta = true;
223
+ }
224
+ if (!responseStarted) thinkingLog.onThinkingDelta(delta);
225
+ }
226
+
227
+ function onToolLog(entry) {
228
+ if (!entry || typeof entry !== "object") return;
229
+ thinkingLog.stop();
230
+ if (hasStreamedAnyText) {
231
+ replaceOnNextDelta = true;
232
+ }
233
+ if (typeof onToolEntry === "function") onToolEntry(entry);
234
+ }
235
+
236
+ function finish() {
237
+ if (tools && typeof tools.flush === "function") tools.flush();
238
+ thinkingLog.stop();
239
+ publish("stream.done", { id: currentId });
240
+ }
241
+
242
+ return {
243
+ get currentId() { return currentId; },
244
+ beginResponse,
245
+ onTextPhase,
246
+ onDelta,
247
+ onThinkingDelta,
248
+ onToolLog,
249
+ finish,
250
+ };
251
+ }
252
+
161
253
  function appendNaturalLanguageResult(nlResult, formatNlResult, appendLog) {
162
254
  if (typeof formatNlResult !== "function" || typeof appendLog !== "function" || !nlResult) {
163
255
  return false;
@@ -199,8 +291,6 @@ async function runUcodeRust(props = {}) {
199
291
  let autoBusError = "";
200
292
  let closing = false;
201
293
  let pendingAttachments = [];
202
- let selectedAgentId = "";
203
- let selectedAgentLabel = "";
204
294
  let markdownState = { inCodeBlock: false };
205
295
  let remoteModels = [];
206
296
  let remoteModelsCacheKey = "";
@@ -227,6 +317,12 @@ async function runUcodeRust(props = {}) {
227
317
  }));
228
318
  }
229
319
 
320
+ const agentSession = require("./ucodeAgentSession").createUcodeAgentSession({
321
+ projectRoot: workspaceRoot,
322
+ getSubscriber: () => String(props.autoBus?.subscriberId || process.env.UFOO_SUBSCRIBER_ID || "").trim(),
323
+ publish,
324
+ });
325
+
230
326
  function publishAgents() {
231
327
  const selfSubscriberId = String(
232
328
  (props.autoBus && props.autoBus.subscriberId)
@@ -235,6 +331,7 @@ async function runUcodeRust(props = {}) {
235
331
  ).trim();
236
332
  const snapshot = buildUcodeAgentsSnapshot(workspaceRoot, selfSubscriberId);
237
333
  publish("agents.snapshot", snapshot);
334
+ agentSession.refresh();
238
335
  return snapshot;
239
336
  }
240
337
 
@@ -274,7 +371,7 @@ async function runUcodeRust(props = {}) {
274
371
  const thinking = createThinkingStatusPublisher(publish);
275
372
 
276
373
  function getBackgroundSuffix() {
277
- let running = 0;
374
+ let running = countRunningBackgroundProcesses({ workspaceRoot });
278
375
  let done = 0;
279
376
  let failed = 0;
280
377
  for (const task of backgroundTasks.values()) {
@@ -330,6 +427,7 @@ async function runUcodeRust(props = {}) {
330
427
  if (normalized) tools.pushTool(normalized);
331
428
  if (
332
429
  entry.tool === "plan_graph"
430
+ || entry.tool === "task_run"
333
431
  || entry.phase === "end"
334
432
  || entry.phase === "result"
335
433
  ) {
@@ -508,6 +606,7 @@ async function runUcodeRust(props = {}) {
508
606
  attachment_count: pendingAttachments.length,
509
607
  usage: String((meter && meter.label) || view.usage || ""),
510
608
  task_queue: controller.getQueueSnapshot(),
609
+ window: agentSession.getSnapshot(),
511
610
  };
512
611
  }
513
612
 
@@ -527,6 +626,13 @@ async function runUcodeRust(props = {}) {
527
626
  id: String((pending && pending.id) || "ask"),
528
627
  kind: String((pending && pending.kind) || "ask_user"),
529
628
  prompt: String((pending && pending.prompt) || "Input required"),
629
+ options: Array.isArray(pending && pending.options)
630
+ ? pending.options.map((opt) => ({
631
+ key: String((opt && opt.key) || ""),
632
+ label: String((opt && opt.label) || ""),
633
+ }))
634
+ : [],
635
+ allow_free_chat: pending ? pending.allowFreeChat !== false : true,
530
636
  lines: Array.isArray(lines) ? lines.map((line) => stripTags(line)) : [],
531
637
  });
532
638
  publish("status.set", { text: "waiting for reply…", busy: false });
@@ -541,36 +647,21 @@ async function runUcodeRust(props = {}) {
541
647
  const submit = typeof props.submitUserInteractionAnswer === "function"
542
648
  ? props.submitUserInteractionAnswer
543
649
  : require("../code/protocol").submitUserInteractionAnswer;
544
- const streamId = `resume-${Date.now()}`;
545
- tools.beginScope();
546
- thinking.reset();
547
- publish("stream.start", { id: streamId });
548
- const thinkingLog = createThinkingLogPublisher(publish, thinking, streamId);
549
- const normalizeStreamDelta = createLeadingWhitespaceNormalizer();
550
- let responseStarted = false;
551
- const beginResponse = () => {
552
- if (responseStarted) return;
553
- responseStarted = true;
554
- thinkingLog.stop();
555
- publish("status.set", { text: "Generating response…", busy: true });
556
- };
650
+ const streamSession = createSegmentedStreamSession({
651
+ baseId: `resume-${Date.now()}`,
652
+ publish,
653
+ tools,
654
+ thinking,
655
+ onToolEntry: ingestToolLog,
656
+ });
557
657
  try {
558
658
  const result = await submit(answerText, props.state, {
559
659
  signal: abort.signal,
560
- onDelta: (delta) => {
561
- const visibleDelta = normalizeStreamDelta(delta);
562
- if (!visibleDelta) return;
563
- beginResponse();
564
- publish("stream.delta", { id: streamId, text: visibleDelta });
565
- },
566
- onThinkingDelta: (delta) => {
567
- if (!responseStarted) thinkingLog.onThinkingDelta(delta);
568
- },
569
- onToolLog: ingestToolLog,
660
+ onDelta: streamSession.onDelta,
661
+ onThinkingDelta: streamSession.onThinkingDelta,
662
+ onToolLog: streamSession.onToolLog,
570
663
  });
571
- tools.flush();
572
- thinkingLog.stop();
573
- publish("stream.done", { id: streamId });
664
+ streamSession.finish();
574
665
  if (!result || result.ok === false) {
575
666
  appendLog(`Error: ${(result && result.error) || "resume failed"}`, "error");
576
667
  } else if (result.shouldEchoSummary) {
@@ -586,9 +677,7 @@ async function runUcodeRust(props = {}) {
586
677
  controller.resumeQueue();
587
678
  return { ok: true, waiting: false };
588
679
  } catch (err) {
589
- tools.flush();
590
- thinkingLog.stop();
591
- publish("stream.done", { id: streamId });
680
+ streamSession.finish();
592
681
  if (abort.signal.aborted) {
593
682
  appendLog("Task cancelled.", "system");
594
683
  return { ok: false, cancelled: true };
@@ -606,48 +695,38 @@ async function runUcodeRust(props = {}) {
606
695
  async function runNaturalLanguage(text, meta = {}) {
607
696
  const label = String(meta.label || text || "prompt").trim().replace(/\s+/g, " ");
608
697
  return controller.runExclusive(async (abort) => {
698
+ if (meta.runtimeEvent) {
699
+ const { hasPendingUserInteraction } = require("../code/context/userInteraction");
700
+ if (hasPendingUserInteraction(props.state.executionState) || !meta.claim()) return false;
701
+ }
609
702
  if (typeof props.runNaturalLanguageTask !== "function") {
610
703
  appendLog("runNaturalLanguageTask unavailable", "error");
611
704
  return { ok: false };
612
705
  }
613
- const streamId = `nl-${Date.now()}`;
614
- tools.beginScope();
615
- thinking.reset();
616
- publish("stream.start", { id: streamId });
617
- const thinkingLog = createThinkingLogPublisher(publish, thinking, streamId);
618
- const normalizeStreamDelta = createLeadingWhitespaceNormalizer();
619
- let responseStarted = false;
620
- const beginResponse = () => {
621
- if (responseStarted) return;
622
- responseStarted = true;
623
- thinkingLog.stop();
624
- publish("status.set", { text: "Generating response…", busy: true });
625
- };
706
+ const streamSession = createSegmentedStreamSession({
707
+ baseId: `nl-${Date.now()}`,
708
+ publish,
709
+ tools,
710
+ thinking,
711
+ onToolEntry: ingestToolLog,
712
+ });
626
713
  try {
627
714
  const nlResult = await props.runNaturalLanguageTask(text, props.state, {
715
+ ...(meta.runtimeEvent ? { runtimeContext: { requestKind: "system_wake", parentTaskRunId: meta.runtimeEvent.ownerTaskRunId } } : {}),
628
716
  signal: abort.signal,
629
- onDelta: (delta) => {
630
- const visibleDelta = normalizeStreamDelta(delta);
631
- if (!visibleDelta) return;
632
- beginResponse();
633
- publish("stream.delta", { id: streamId, text: visibleDelta });
634
- },
635
- onThinkingDelta: (delta) => {
636
- if (!responseStarted) thinkingLog.onThinkingDelta(delta);
637
- },
638
- onToolLog: ingestToolLog,
717
+ onDelta: streamSession.onDelta,
718
+ onThinkingDelta: streamSession.onThinkingDelta,
719
+ onToolLog: streamSession.onToolLog,
639
720
  onPhase: (event) => {
640
721
  if (!event || typeof event !== "object") return;
641
- if (event.type === "text_delta") beginResponse();
722
+ if (event.type === "text_delta") streamSession.onTextPhase(event);
642
723
  else {
643
724
  const text = statusForAgentPhase(event);
644
725
  if (text) publish("status.set", { text, busy: true });
645
726
  }
646
727
  },
647
728
  });
648
- tools.flush();
649
- thinkingLog.stop();
650
- publish("stream.done", { id: streamId });
729
+ streamSession.finish();
651
730
  appendNaturalLanguageResult(nlResult, props.formatNlResult, appendLog);
652
731
  persistIfNeeded();
653
732
  publishPlan();
@@ -659,9 +738,7 @@ async function runUcodeRust(props = {}) {
659
738
  controller.resumeQueue();
660
739
  return { ok: true, waiting: false, result: nlResult };
661
740
  } catch (err) {
662
- tools.flush();
663
- thinkingLog.stop();
664
- publish("stream.done", { id: streamId });
741
+ streamSession.finish();
665
742
  if (abort.signal.aborted) {
666
743
  appendLog("Task cancelled.", "system");
667
744
  return { ok: false, cancelled: true };
@@ -672,6 +749,7 @@ async function runUcodeRust(props = {}) {
672
749
  }, {
673
750
  kind: String(meta.kind || "prompt").trim() || "prompt",
674
751
  label: label.length > 80 ? `${label.slice(0, 77)}…` : label,
752
+ promptText: String(text || ""),
675
753
  });
676
754
  }
677
755
 
@@ -750,7 +828,7 @@ async function runUcodeRust(props = {}) {
750
828
  const host = createUiHostServer({
751
829
  socketPath: uiSocketPath,
752
830
  authToken: uiAuthToken,
753
- capabilities: ["ucode", "scrollback", "prompt", "interaction", "auto-bus"],
831
+ capabilities: ["ucode", "scrollback", "prompt", "interaction", "auto-bus", "window-modes-v1"],
754
832
  onClientReady(socket) {
755
833
  const snap = createEnvelope({
756
834
  kind: "snapshot",
@@ -760,8 +838,10 @@ async function runUcodeRust(props = {}) {
760
838
  payload: buildSnapshot(),
761
839
  });
762
840
  socket.write(encodeMessage(snap));
841
+ agentSession.publishFrames();
763
842
  publishPendingInteraction();
764
843
  publishPlan();
844
+ ensureRemoteModels().catch(() => {});
765
845
  if (!clientReady) {
766
846
  clientReady = true;
767
847
  if (typeof props.onReady === "function") props.onReady();
@@ -784,6 +864,9 @@ async function runUcodeRust(props = {}) {
784
864
  }
785
865
  if (name === "completion.request") {
786
866
  const text = String(payload.text || "");
867
+ if (/^\s*\/m/i.test(text)) {
868
+ ensureRemoteModels().catch(() => {});
869
+ }
787
870
  if (/^\s*\/model(\s|$)/i.test(text)) {
788
871
  await ensureRemoteModels();
789
872
  }
@@ -805,28 +888,64 @@ async function runUcodeRust(props = {}) {
805
888
  }
806
889
  if (name === "ui.resync.request") {
807
890
  publish("app.snapshot", buildSnapshot());
891
+ agentSession.publishFrames();
808
892
  publishAgents();
809
893
  publishPlan();
810
894
  return { ok: true };
811
895
  }
812
- if (name === "agent.select") {
813
- selectedAgentId = String(payload.agent_id || payload.agentId || "").trim();
814
- selectedAgentLabel = String(payload.label || selectedAgentId).trim();
815
- publish("prompt.set_prefix", {
816
- prefix: selectedAgentId
817
- ? `›@${selectedAgentLabel || selectedAgentId} `
818
- : "› ",
819
- });
820
- publish("status.set", {
821
- text: selectedAgentId
822
- ? `target @${selectedAgentLabel || selectedAgentId}`
823
- : "ready",
824
- });
825
- return { ok: true, agent_id: selectedAgentId };
896
+ const agentCommand = await agentSession.handleCommand(name, payload);
897
+ if (agentCommand) {
898
+ if (name === "agent.close") {
899
+ if (agentCommand.ok) publishAgents();
900
+ else appendLog(agentCommand.error || "Agent close failed", "error");
901
+ }
902
+ return agentCommand;
826
903
  }
827
904
  if (name === "input.paste") {
828
905
  return handlePasteCommand(payload);
829
906
  }
907
+ if (name === "queue.inject") {
908
+ const rawText = String(payload.text || "");
909
+ const { modelText, logText, attachments } = composeSubmitText(rawText);
910
+ if (modelText || attachments.length > 0) {
911
+ clearAttachments();
912
+ appendLog(`› ${logText || rawText}`, "user");
913
+ }
914
+ const drained = typeof controller.drainQueuedPrompts === "function"
915
+ ? controller.drainQueuedPrompts()
916
+ : [];
917
+ const texts = drained
918
+ .map((item) => String((item && item.text) || "").trim())
919
+ .filter(Boolean);
920
+ if (modelText) texts.push(modelText);
921
+ if (texts.length === 0) {
922
+ return { ok: true, injected: 0 };
923
+ }
924
+ if (controller.isBusy()) {
925
+ const { enqueueUserPrompt } = require("../code/context/userNudge");
926
+ const { emptyExecutionState } = require("../code/context/executionSegment");
927
+ if (props.state) {
928
+ if (!props.state.executionState || typeof props.state.executionState !== "object") {
929
+ props.state.executionState = emptyExecutionState();
930
+ }
931
+ for (const itemText of texts) {
932
+ enqueueUserPrompt(props.state.executionState, itemText);
933
+ }
934
+ }
935
+ publishStatus("injected into current turn…", true);
936
+ return { ok: true, injected: texts.length };
937
+ }
938
+ publishStatus("working…", true);
939
+ const combined = texts.join("\n\n");
940
+ const result = await runNaturalLanguage(combined);
941
+ if (result && result.waiting) {
942
+ return { ok: true, routed: "ucode", waiting: true, injected: texts.length };
943
+ }
944
+ if (!controller.isBusy()) {
945
+ publishStatus("ready", false);
946
+ }
947
+ return { ok: true, routed: "ucode", injected: texts.length };
948
+ }
830
949
  if (name === "interaction.respond") {
831
950
  if (payload.cancelled) {
832
951
  appendLog("interaction cancelled", "system");
@@ -836,6 +955,13 @@ async function runUcodeRust(props = {}) {
836
955
  return { ok: true, cancelled: true };
837
956
  }
838
957
  publish("interaction.clear", {});
958
+ const replyText = String(payload.text || "").trim();
959
+ const replyLabel = String(payload.label || "").trim();
960
+ if (replyLabel && replyText && replyLabel !== replyText) {
961
+ appendLog(`› [${replyText}] ${replyLabel}`, "user");
962
+ } else if (replyText) {
963
+ appendLog(`› ${replyText}`, "user");
964
+ }
839
965
  publish("status.set", { text: "applying reply…", busy: true });
840
966
  const resume = resumeInteraction(String(payload.text || ""), { priority: true });
841
967
  controller.resumeQueue();
@@ -848,6 +974,15 @@ async function runUcodeRust(props = {}) {
848
974
  if (name === "input.submit") {
849
975
  const rawText = String(payload.text || "");
850
976
  const { modelText, logText, attachments } = composeSubmitText(rawText);
977
+ const agentResult = await agentSession.submit({ ...payload, text: modelText });
978
+ if (agentResult) {
979
+ if (agentResult.ok && agentResult.routed === "agent") {
980
+ clearAttachments();
981
+ appendLog(`› @${agentResult.agent_id} ${logText || rawText}`, "user");
982
+ }
983
+ if (!agentResult.ok) appendLog(agentResult.error, "error");
984
+ return agentResult;
985
+ }
851
986
  if (!modelText && attachments.length === 0) return { ok: true, empty: true };
852
987
  clearAttachments();
853
988
 
@@ -866,6 +1001,27 @@ async function runUcodeRust(props = {}) {
866
1001
  // fall through
867
1002
  }
868
1003
 
1004
+ const trimmedSubmit = String(rawText || "").trim();
1005
+ if (attachments.length === 0 && /^\/model$/i.test(trimmedSubmit)) {
1006
+ await ensureRemoteModels();
1007
+ const selfSubscriberId = String(
1008
+ (props.autoBus && props.autoBus.subscriberId)
1009
+ || process.env.UFOO_SUBSCRIBER_ID
1010
+ || ""
1011
+ ).trim();
1012
+ const items = await buildUcodeCompletionItems({
1013
+ text: "/model ",
1014
+ workspaceRoot,
1015
+ state: props.state || {},
1016
+ selfSubscriberId,
1017
+ remoteModels,
1018
+ limit: Math.max(20, remoteModels.length + 1),
1019
+ });
1020
+ publish("completions.set", { items });
1021
+ publishStatus("ready", false);
1022
+ return { ok: true, routed: "completions" };
1023
+ }
1024
+
869
1025
  appendLog(`› ${logText || rawText}`, "user");
870
1026
  publishStatus("working…", true);
871
1027
 
@@ -1057,6 +1213,16 @@ async function runUcodeRust(props = {}) {
1057
1213
  hostRef = host;
1058
1214
  await host.listen();
1059
1215
  controller.start();
1216
+ const wakeHost = props.state && require("../code/runtime/backgroundWakeHost").createUcodeWakeHost({
1217
+ state: props.state,
1218
+ canDeliver: () => !closing && !controller.isBusy() && !controller.getQueueSnapshot().paused,
1219
+ deliver: async (event, claim, text) => {
1220
+ const result = await runNaturalLanguage(text, { kind: "runtime-wake", label: event.type, runtimeEvent: event, claim });
1221
+ return result !== null && result !== false;
1222
+ },
1223
+ onError: error => appendLog(`Background notification: ${error.message}`, "error"),
1224
+ });
1225
+ wakeHost?.start();
1060
1226
  publishAgents();
1061
1227
  ensureRemoteModels().catch(() => {});
1062
1228
  agentsTimer = setInterval(publishAgents, 3000);
@@ -1092,6 +1258,7 @@ async function runUcodeRust(props = {}) {
1092
1258
  });
1093
1259
 
1094
1260
  closing = true;
1261
+ wakeHost?.close();
1095
1262
  if (autoBusTimer) {
1096
1263
  clearInterval(autoBusTimer);
1097
1264
  autoBusTimer = null;
@@ -1101,6 +1268,7 @@ async function runUcodeRust(props = {}) {
1101
1268
  agentsTimer = null;
1102
1269
  }
1103
1270
  thinking.reset();
1271
+ agentSession.stop();
1104
1272
  controller.stop();
1105
1273
  await host.close();
1106
1274
  return exitCode;
@@ -1113,6 +1281,7 @@ module.exports = {
1113
1281
  splitUcodeBannerRow,
1114
1282
  createThinkingLogPublisher,
1115
1283
  createLeadingWhitespaceNormalizer,
1284
+ createSegmentedStreamSession,
1116
1285
  appendNaturalLanguageResult,
1117
1286
  buildUcodeAgentsSnapshot,
1118
1287
  buildUcodeCompletionItems,
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+
3
+ const { createRustMultiSession } = require("./rustMultiSession");
4
+ const { loadAgentsData } = require("../coordination/state/agentsStore");
5
+ const { getUfooPaths } = require("../coordination/state/paths");
6
+ const { isMetaActive } = require("../coordination/bus/utils");
7
+ const { isInternalAgentMeta } = require("../runtime/contracts/agentMode");
8
+ const { dispatchMessageHandler } = require("../tools/handlers/dispatchMessage");
9
+
10
+ function createUcodeAgentSession({ projectRoot, getSubscriber, publish, send = dispatchMessageHandler,
11
+ requestDaemon = require("../app/chat/transport").requestDaemon } = {}) {
12
+ let selected = "";
13
+ const meta = (id) => loadAgentsData(getUfooPaths(projectRoot).agentsFile).agents?.[id];
14
+ const active = (id) => id && id !== getSubscriber() && id !== "ufoo-agent" && isMetaActive(meta(id));
15
+ const label = (id) => { const row = meta(id); return row?.display_nickname || row?.nickname || id; };
16
+ async function sendMessage(id, text) {
17
+ if (!active(id)) return { ok: false, error: "Unknown or inactive target" };
18
+ const result = await send({ projectRoot, subscriber: getSubscriber() }, { target: id, message: text });
19
+ if (!result?.ok) throw new Error(result?.error || "Message delivery failed");
20
+ return result;
21
+ }
22
+ const multi = createRustMultiSession({ projectRoot,
23
+ getActiveAgents: () => Object.keys(loadAgentsData(getUfooPaths(projectRoot).agentsFile).agents || {}).filter(active),
24
+ getAgentMeta: meta, getLabel: label, publish,
25
+ resolvePaneOptions: id => ({ mode: "internal", initialEntries:
26
+ require("../app/chat/internalAgentLogHistory").loadInternalAgentTranscript(projectRoot, id, { maxEvents: 200, maxEntries: 200 }) || [] }),
27
+ onInternalSubmit: async (id, text) => {
28
+ const result = await sendMessage(id, text);
29
+ if (!result.ok) throw new Error(result.error);
30
+ return result;
31
+ },
32
+ });
33
+ function select(id) {
34
+ if (id && !active(id)) return { ok: false, error: "Unknown or inactive target" };
35
+ selected = id;
36
+ if (id) multi.handleFocus({ target: "chat" });
37
+ publish("prompt.set_prefix", { prefix: id ? `›@${label(id)} ` : "› " });
38
+ return { ok: true, agent_id: id, mode: "message" };
39
+ }
40
+ function open(id) {
41
+ if (!active(id)) return { ok: false, error: "Unknown or inactive target" };
42
+ if (!isInternalAgentMeta(meta(id))) return select(id);
43
+ const result = multi.start({ kind: "side", agentIds: [id], focus: { target: "agent", agent_id: id } });
44
+ if (result.ok) select("");
45
+ return result;
46
+ }
47
+ async function handleCommand(name, payload = {}) {
48
+ const id = String(payload.agent_id || payload.agentId || "").trim();
49
+ if (name === "agent.select") return select(id);
50
+ if (name === "agent.open") return open(id);
51
+ if (name === "agent.close") {
52
+ if (!active(id) || !isInternalAgentMeta(meta(id))) return { ok: false, error: "Unknown active internal agent" };
53
+ try {
54
+ const response = await requestDaemon(projectRoot, { type: "close_agent", agent_id: id }, {
55
+ retries: 1, timeoutMs: 10000, fullResponse: true,
56
+ });
57
+ const result = response?.opsResults?.find(row => row.action === "close");
58
+ if (!result || result.ok === false) return { ok: false, error: result?.error || response?.data?.reply || "Agent close was not confirmed" };
59
+ if (selected === id) select("");
60
+ multi.syncAgents();
61
+ return { ok: true, agent_id: id };
62
+ } catch (error) { return { ok: false, error: error.message || "Agent close failed" }; }
63
+ }
64
+ if (name === "window.set" || name === "window.cycle") {
65
+ if (payload.session_id && payload.session_id !== multi.getSessionId()) return { ok: false, error: "stale session_id" };
66
+ return multi.setLayout(name === "window.cycle" ? "cycle" : payload.mode);
67
+ }
68
+ const methods = { "multi.focus": "handleFocus", "multi.raw": "handleRaw", "multi.viewport": "handleViewport",
69
+ "multi.scroll": "handleScroll", "multi.expand": "handleExpand", "multi.cancel": "handleCancel" };
70
+ if (methods[name]) return multi[methods[name]](payload);
71
+ return null;
72
+ }
73
+ async function submit(payload = {}) {
74
+ const explicit = String(payload.target_agent || payload.targetAgent || "").trim();
75
+ const target = explicit || (payload.input_target === "main" ? "" : selected);
76
+ if (payload.has_target && !explicit) return { ok: false, error: "Unknown or inactive target" };
77
+ if (!target) return null;
78
+ if (!active(target)) return { ok: false, error: "Unknown or inactive target" };
79
+ const text = String(payload.text || "").trim();
80
+ if (!text) return open(target);
81
+ const result = await sendMessage(target, text);
82
+ return { ...result, routed: "agent", agent_id: target };
83
+ }
84
+ return { handleCommand, submit, getSnapshot: multi.getSnapshot, refresh: () => multi.syncAgents(),
85
+ publishFrames: multi.publishFrames, stop: () => multi.stop({ clearDrafts: true }) };
86
+ }
87
+
88
+ module.exports = { createUcodeAgentSession };