u-foo 3.1.7 → 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 (266) hide show
  1. package/OBSERVABILITY.md +65 -0
  2. package/README.md +238 -21
  3. package/README.zh-CN.md +165 -20
  4. package/SKILLS/ufoo/SKILL.md +40 -4
  5. package/SKILLS/ufoo-bus/SKILL.md +46 -3
  6. package/bin/uclaude.js +4 -0
  7. package/bin/ucodex.js +4 -0
  8. package/bin/ufoo.js +6 -4
  9. package/dist/tui/darwin-arm64/ufoo-tui +0 -0
  10. package/dist/tui/darwin-x64/ufoo-tui +0 -0
  11. package/dist/tui/linux-arm64/ufoo-tui +0 -0
  12. package/dist/tui/linux-x64/ufoo-tui +0 -0
  13. package/package.json +14 -7
  14. package/scripts/postinstall-skills.js +53 -0
  15. package/scripts/postinstall.js +11 -16
  16. package/scripts/smoke-native-messages.js +214 -0
  17. package/src/agents/activity/activityDetector.js +1 -1
  18. package/src/agents/activity/activityStateWriter.js +37 -38
  19. package/src/agents/capabilities/agentManagement/index.js +4 -0
  20. package/src/agents/capabilities/agentManagement/service.js +140 -0
  21. package/src/agents/capabilities/agentRouting/index.js +4 -0
  22. package/src/agents/capabilities/coding/index.js +32 -0
  23. package/src/agents/capabilities/coordination/index.js +37 -0
  24. package/src/agents/capabilities/globalRouting/index.js +5 -0
  25. package/src/agents/capabilities/groups/index.js +3 -0
  26. package/src/agents/capabilities/index.js +25 -0
  27. package/src/agents/capabilities/planning/index.js +123 -0
  28. package/src/agents/capabilities/planning/main.js +28 -0
  29. package/src/agents/capabilities/projectDiscovery/index.js +3 -0
  30. package/src/agents/capabilities/scheduling/index.js +3 -0
  31. package/src/agents/capabilities/sharedMemory/index.js +4 -0
  32. package/src/agents/capabilities/skills/index.js +12 -0
  33. package/src/agents/capabilities/taskExecution/index.js +3 -0
  34. package/src/agents/capabilities/taskReports/index.js +6 -0
  35. package/src/agents/controller/controllerToolExecutor.js +40 -22
  36. package/src/agents/controller/index.js +1 -6
  37. package/src/agents/internal/internalRunner.js +181 -76
  38. package/src/agents/launch/index.js +0 -1
  39. package/src/agents/launch/launcher.js +96 -14
  40. package/src/agents/launch/nativeCapabilities.js +40 -0
  41. package/src/agents/launch/nativeMessages.js +362 -0
  42. package/src/agents/launch/notifier.js +15 -20
  43. package/src/agents/launch/readyDetector.js +28 -14
  44. package/src/agents/profiles/coding.js +6 -0
  45. package/src/agents/profiles/globalRouter.js +2 -0
  46. package/src/agents/profiles/main.js +5 -0
  47. package/src/agents/prompts/cooperation.js +14 -0
  48. package/src/agents/prompts/defaultBootstrap.js +1 -1
  49. package/src/agents/prompts/groupBootstrap.js +32 -6
  50. package/src/agents/prompts/mainAgent.js +48 -0
  51. package/src/agents/prompts/native/system.js +4 -1
  52. package/src/agents/prompts/native/tasks.js +2 -2
  53. package/src/agents/prompts/native/ufoo.js +14 -3
  54. package/src/agents/prompts/promptProfiles.js +2 -0
  55. package/src/agents/prompts/reporting.js +16 -0
  56. package/src/agents/providers/claudeEventTranslator.js +9 -1
  57. package/src/agents/providers/claudeThreadProvider.js +47 -4
  58. package/src/agents/providers/clientIdentity.js +75 -0
  59. package/src/agents/providers/codexEventTranslator.js +68 -7
  60. package/src/agents/providers/codexThreadProvider.js +18 -8
  61. package/src/agents/providers/credentials/claude.js +10 -3
  62. package/src/agents/providers/credentials/index.js +2 -0
  63. package/src/agents/providers/directAuthStatus.js +1 -1
  64. package/src/agents/providers/index.js +1 -1
  65. package/src/agents/providers/modelSettings.js +34 -0
  66. package/src/agents/providers/modelsCatalog.js +379 -0
  67. package/src/agents/providers/nativeTransport.js +1146 -0
  68. package/src/agents/providers/runtimeConfig.js +188 -0
  69. package/src/agents/providers/thinkingLevels.js +106 -0
  70. package/src/agents/providers/transports/anthropicMessagesTransport.js +121 -0
  71. package/src/agents/providers/transports/index.js +10 -0
  72. package/src/agents/providers/transports/openaiChatTransport.js +117 -0
  73. package/src/agents/providers/transports/openaiResponsesTransport.js +120 -0
  74. package/src/agents/providers/transports/responsesProtocol.js +504 -0
  75. package/src/agents/providers/transports/systemBlocks.js +16 -0
  76. package/src/agents/providers/transports/transportContract.js +50 -0
  77. package/src/agents/providers/transports/visionBlocks.js +151 -0
  78. package/src/agents/providers/upstreamRuntime.js +135 -0
  79. package/src/agents/runtime/composeCapabilities.js +89 -0
  80. package/src/agents/runtime/context/checkpointStore.js +38 -0
  81. package/src/agents/runtime/context/commandStore.js +43 -0
  82. package/src/agents/runtime/context/compaction.js +151 -0
  83. package/src/agents/runtime/context/contextBudget.js +93 -0
  84. package/src/agents/runtime/context/contextWindow.js +119 -0
  85. package/src/agents/runtime/context/fileLock.js +36 -0
  86. package/src/agents/runtime/context/replayHistory.js +28 -0
  87. package/src/agents/runtime/context/runtimeStore.js +127 -0
  88. package/src/agents/runtime/context/sessionJournal.js +360 -0
  89. package/src/agents/runtime/context/sessionStore.js +57 -0
  90. package/src/agents/runtime/core/agentLoop.js +351 -0
  91. package/src/agents/runtime/core/executionBudget.js +36 -0
  92. package/src/agents/runtime/core/stableJson.js +29 -0
  93. package/src/agents/runtime/core/toolLoopGuard.js +55 -0
  94. package/src/agents/runtime/createAgentRuntime.js +259 -0
  95. package/src/agents/runtime/index.js +14 -0
  96. package/src/agents/runtime/prompts/responseLanguage.js +12 -0
  97. package/src/agents/runtime/protocol/faultHarness.js +90 -0
  98. package/src/agents/runtime/protocol/materialize.js +107 -0
  99. package/src/agents/runtime/protocol/runObservation.js +24 -0
  100. package/src/agents/runtime/protocol/toolCallLedger.js +221 -0
  101. package/src/agents/runtime/protocol/traceContext.js +9 -0
  102. package/src/agents/runtime/tasks/resourceLease.js +66 -0
  103. package/src/agents/runtime/tasks/scheduler.js +73 -0
  104. package/src/agents/runtime/tools/registry.js +57 -0
  105. package/src/app/chat/ChatController.js +29 -45
  106. package/src/app/chat/agentDirectory.js +9 -18
  107. package/src/app/chat/bootstrap.js +1 -2
  108. package/src/app/chat/commandExecutor.js +111 -313
  109. package/src/app/chat/commands.js +39 -45
  110. package/src/app/chat/daemonConnection.js +58 -5
  111. package/src/app/chat/daemonMessageRouter.js +61 -48
  112. package/src/app/chat/historyStore.js +12 -48
  113. package/src/app/chat/inputSubmitHandler.js +21 -35
  114. package/src/app/chat/internalAgentLogHistory.js +19 -60
  115. package/src/app/chat/launchRequestContext.js +42 -0
  116. package/src/app/chat/multiWindow/paneManager.js +91 -164
  117. package/src/app/chat/streamState.js +3 -7
  118. package/src/app/chat/transport.js +1 -1
  119. package/src/app/cli/busCoreCommands.js +9 -0
  120. package/src/app/cli/features/doctor.js +33 -0
  121. package/src/app/cli/features/init.js +5 -5
  122. package/src/app/cli/features/skills.js +16 -4
  123. package/src/app/cli/metricsCommands.js +68 -0
  124. package/src/app/cli/reportCoreCommands.js +37 -0
  125. package/src/app/cli/run.js +82 -42
  126. package/src/app/cli/traceCommands.js +36 -0
  127. package/src/code/agent.js +34 -17
  128. package/src/code/busConsumer.js +1 -3
  129. package/src/code/commands.js +1 -1
  130. package/src/code/context/artifacts.js +12 -11
  131. package/src/code/context/assembler.js +9 -9
  132. package/src/code/context/promptLayers.js +1 -13
  133. package/src/code/context/stableJson.js +2 -27
  134. package/src/code/context/stateCommit.js +2 -1
  135. package/src/code/contextWindow.js +2 -117
  136. package/src/code/conversation/sessionJournal.js +3 -349
  137. package/src/code/internalThread.js +107 -0
  138. package/src/code/launcher/ucode.js +1 -1
  139. package/src/code/launcher/ucodeBootstrap.js +1 -1
  140. package/src/code/modelCommand.js +11 -35
  141. package/src/code/nativeRunner.js +104 -2697
  142. package/src/code/protocol/faultHarness.js +2 -88
  143. package/src/code/protocol/materialize.js +2 -105
  144. package/src/code/protocol/toolCallLedger.js +5 -215
  145. package/src/code/providers/anthropicMessagesTransport.js +2 -118
  146. package/src/code/providers/modelsCatalog.js +1 -317
  147. package/src/code/providers/openaiChatTransport.js +2 -114
  148. package/src/code/providers/openaiResponsesTransport.js +2 -117
  149. package/src/code/providers/responsesProtocol.js +2 -497
  150. package/src/code/providers/transportContract.js +2 -48
  151. package/src/code/providers/visionBlocks.js +2 -149
  152. package/src/code/repl.js +2 -11
  153. package/src/code/sessionStore.js +27 -99
  154. package/src/code/taskDecomposer.js +18 -0
  155. package/src/code/thinkingLevels.js +1 -130
  156. package/src/code/toolBudget.js +1 -17
  157. package/src/code/toolLoopGuard.js +3 -49
  158. package/src/code/tools/artifactRead.js +1 -1
  159. package/src/code/tools/executor.js +373 -0
  160. package/src/code/tools/specs.js +312 -0
  161. package/src/config.js +95 -131
  162. package/src/coordination/bus/deliveryQueue.js +16 -2
  163. package/src/coordination/bus/index.js +14 -9
  164. package/src/coordination/bus/inject.js +15 -7
  165. package/src/coordination/bus/message.js +15 -1
  166. package/src/coordination/bus/nativeReceipts.js +100 -0
  167. package/src/coordination/bus/nickname.js +1 -1
  168. package/src/coordination/bus/queue.js +1 -3
  169. package/src/coordination/bus/subscriber.js +3 -2
  170. package/src/coordination/bus/utils.js +8 -4
  171. package/src/coordination/history/agentPerformance.js +279 -0
  172. package/src/coordination/history/agentSurface.js +142 -0
  173. package/src/coordination/history/agentTrace.js +249 -0
  174. package/src/coordination/memory/index.js +5 -21
  175. package/src/coordination/report/store.js +103 -83
  176. package/src/coordination/state/agentsStore.js +57 -3
  177. package/src/coordination/state/fileLock.js +2 -0
  178. package/src/coordination/state/workspaceAccess.js +36 -0
  179. package/src/orchestration/controller/index.js +1 -8
  180. package/src/orchestration/controller/launchRouting.js +1 -1
  181. package/src/orchestration/solo/commands.js +3 -1
  182. package/src/runtime/contracts/agentMode.js +26 -0
  183. package/src/runtime/contracts/eventContract.js +3 -0
  184. package/src/runtime/contracts/uiProtocol.js +20 -17
  185. package/src/runtime/daemon/agentHost.js +407 -0
  186. package/src/runtime/daemon/agentRecoveryGroups.js +70 -0
  187. package/src/runtime/daemon/busBridge.js +396 -0
  188. package/src/runtime/daemon/claudeChannel.js +159 -0
  189. package/src/runtime/daemon/controlPlaneService.js +28 -18
  190. package/src/runtime/daemon/cronOps.js +25 -17
  191. package/src/runtime/daemon/deliveryScheduler.js +32 -5
  192. package/src/runtime/daemon/globalDaemon.js +28 -1
  193. package/src/runtime/daemon/groupOrchestrator.js +21 -5
  194. package/src/runtime/daemon/groupStatus.js +20 -0
  195. package/src/runtime/daemon/index.js +120 -375
  196. package/src/runtime/daemon/ipcServer.js +32 -10
  197. package/src/runtime/daemon/mcpConfigure.js +113 -20
  198. package/src/runtime/daemon/mcpHttpServer.js +27 -5
  199. package/src/runtime/daemon/mcpServer.js +8 -5
  200. package/src/runtime/daemon/mcpStdioProxy.js +127 -10
  201. package/src/runtime/daemon/nicknameScope.js +1 -1
  202. package/src/runtime/daemon/ops.js +68 -40
  203. package/src/runtime/daemon/projectRuntimeGateway.js +2 -0
  204. package/src/runtime/daemon/promptRequest.js +92 -570
  205. package/src/runtime/daemon/providerSessions.js +67 -33
  206. package/src/runtime/daemon/reportControlBus.js +59 -25
  207. package/src/runtime/daemon/status.js +9 -6
  208. package/src/runtime/privacy/redactor.js +2 -2
  209. package/src/runtime/projects/identity.js +2 -1
  210. package/src/runtime/projects/registry.js +98 -38
  211. package/src/tools/controllerSchemas.js +28 -0
  212. package/src/tools/handlers/dispatchMessage.js +5 -2
  213. package/src/tools/handlers/listAgents.js +3 -1
  214. package/src/tools/handlers/readBusSummary.js +3 -1
  215. package/src/tools/handlers/readProjectRegistry.js +29 -2
  216. package/src/tools/handlers/routeAgent.js +35 -0
  217. package/src/tools/handlers/tier2.js +4 -2
  218. package/src/tools/index.js +1 -0
  219. package/src/tools/registry.js +6 -0
  220. package/src/tools/schemaFixtures.js +42 -5
  221. package/src/tools/tier0/readAgentMetrics.js +14 -0
  222. package/src/tools/tier0/readAgentTrace.js +12 -0
  223. package/src/tools/tier1/routeAgent.js +2 -2
  224. package/src/tools/tier2/runtimeCoordination.js +38 -0
  225. package/src/tools/types.js +2 -0
  226. package/src/ui/agentPresentation.js +109 -0
  227. package/src/ui/agentSettingsController.js +107 -0
  228. package/src/ui/agentSurface.js +270 -0
  229. package/src/ui/dashboardBridge.js +1 -1
  230. package/src/ui/format/banner.js +9 -15
  231. package/src/ui/format/index.js +14 -10
  232. package/src/ui/format/loopSummary.js +50 -0
  233. package/src/ui/format/markdownRenderer.js +3 -4
  234. package/src/ui/format/startupBanner.js +50 -0
  235. package/src/ui/multiPaneBusMirror.js +29 -3
  236. package/src/ui/rustChatHost.js +316 -599
  237. package/src/ui/rustMultiSession.js +288 -73
  238. package/src/ui/rustUcodeHost.js +21 -88
  239. package/src/ui/settingsBridge.js +34 -14
  240. package/src/ui/toolMergeBridge.js +0 -4
  241. package/src/ui/uiHostServer.js +5 -8
  242. package/src/agents/controller/loopObservability.js +0 -200
  243. package/src/agents/controller/loopRuntime.js +0 -472
  244. package/src/agents/controller/ufooAgent.js +0 -829
  245. package/src/agents/launch/ptyRunner.js +0 -1135
  246. package/src/agents/providers/upstreamTransport.js +0 -689
  247. package/src/app/chat/agentBar.js +0 -135
  248. package/src/app/chat/agentEnter.js +0 -70
  249. package/src/app/chat/agentSockets.js +0 -225
  250. package/src/app/chat/dashboardView.js +0 -405
  251. package/src/app/chat/multiWindow/index.js +0 -310
  252. package/src/app/chat/multiWindow/paneLayout.js +0 -84
  253. package/src/app/chat/multiWindow/renderer.js +0 -420
  254. package/src/app/chat/multiWindow/virtualTerminal.js +0 -327
  255. package/src/app/chat/multiWindow/vtFrame.js +0 -93
  256. package/src/app/chat/rawKeyMap.js +0 -42
  257. package/src/app/chat/settingsController.js +0 -111
  258. package/src/orchestration/controller/flags.js +0 -167
  259. package/src/orchestration/controller/gateRouter.js +0 -211
  260. package/src/orchestration/controller/routerFastPath.js +0 -22
  261. package/src/orchestration/controller/routerFinalize.js +0 -222
  262. package/src/orchestration/controller/shadowGuard.js +0 -280
  263. package/src/runtime/daemon/promptLoop.js +0 -136
  264. package/src/runtime/privacy/shadowDiff.js +0 -174
  265. package/src/ui/multiWindowHandoff.js +0 -232
  266. package/src/ui/ptyHandoff.js +0 -23
@@ -3,18 +3,25 @@
3
3
  /**
4
4
  * In-process split-pane session for the Rust TUI host.
5
5
  *
6
- * Two kinds share the same draw/keys (Ctrl+W / Ctrl+Q) and multi.* wire:
7
- * - "multi" — /multi; panes track all active agents
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.
8
+ * Window modes are main, side and multi, including when no children exist.
9
+ * They share draw and the multi.* pane wire:
10
+ * - "multi" — all internal agents
8
11
  * - "side" — internal-only activate; single locked agent on the right
9
- * (not a user-facing mode name; looks like multi with one agent)
12
+ * (shares its pane renderer with multi)
10
13
  *
11
- * The Rust TUI owns TTY / layout / focus. Node owns paneManager (VT +
12
- * inject.sock) and ships bounded, lossy `multi.pane.frame` events.
14
+ * The Rust TUI owns TTY / layout / focus. Node owns internal pane buffers
15
+ * and ships bounded, lossy `multi.pane.frame` events.
13
16
  */
14
17
 
15
18
  const crypto = require("crypto");
19
+ const fs = require("fs");
20
+ const { getUfooPaths } = require("../coordination/state/paths");
21
+ const { isInternalAgentMeta } = require("../runtime/contracts/agentMode");
16
22
  const { createPaneManager } = require("../app/chat/multiWindow/paneManager");
17
- const { vtScreenToAnsiLines } = require("../app/chat/multiWindow/vtFrame");
23
+ const { createAgentSurface } = require("./agentSurface");
24
+ const { readAgentSurfaceEvents, createAgentSurfaceReader } = require("../coordination/history/agentSurface");
18
25
 
19
26
  const DEFAULT_COLS = 40;
20
27
  const DEFAULT_ROWS = 12;
@@ -52,12 +59,13 @@ function createRustMultiSession(options = {}) {
52
59
  const {
53
60
  getActiveAgents = () => [],
54
61
  getAgentMeta = () => ({}),
55
- getInjectSockPath = () => "",
56
- resolvePaneOptions = () => ({ mode: "socket" }),
62
+ resolvePaneOptions = () => ({ mode: "internal" }),
57
63
  onInternalSubmit = () => {},
58
64
  publish = () => {},
59
65
  publishLossy = null,
60
66
  getLabel = (id) => id,
67
+ projectRoot = "",
68
+ getProjectRoot = () => projectRoot,
61
69
  } = options;
62
70
 
63
71
  let sessionId = null;
@@ -67,6 +75,7 @@ function createRustMultiSession(options = {}) {
67
75
  let rev = 0;
68
76
  let viewportRev = 0;
69
77
  let focus = { target: "chat", agent_id: "" };
78
+ let lastActiveAgentId = "";
70
79
  const paneSizes = new Map();
71
80
  const paneMeta = new Map();
72
81
  const dirty = new Set();
@@ -74,36 +83,167 @@ function createRustMultiSession(options = {}) {
74
83
  let paneManager = null;
75
84
  /** @type {Map<string, number>} last successful frame emit per agent */
76
85
  const lastEmitAt = new Map();
86
+ const internalDrafts = new Map();
87
+ const surfaces = new Map();
88
+ const replayedAgents = new Set();
89
+ let observationRoot = "";
90
+ let surfaceReader = null;
91
+ let surfaceWatch = null;
92
+ let surfacePoll = null;
93
+ let surfaceRefresh = null;
94
+
95
+ function closeSurfaceObservation() {
96
+ surfaceWatch?.close();
97
+ surfaceWatch = null;
98
+ clearInterval(surfacePoll);
99
+ surfacePoll = null;
100
+ clearTimeout(surfaceRefresh);
101
+ surfaceRefresh = null;
102
+ }
103
+
104
+ function refreshSurfaceObservations() {
105
+ if (!active) return;
106
+ const root = getProjectRoot();
107
+ if (!root) return;
108
+ if (root !== observationRoot) {
109
+ closeSurfaceObservation();
110
+ observationRoot = root;
111
+ surfaceReader = createAgentSurfaceReader(root);
112
+ }
113
+ for (const event of surfaceReader.read(listInternalAgentIds())) {
114
+ acceptEvent(event.publisher, event.data.surface, event.seq);
115
+ }
116
+ if (!surfaceWatch) {
117
+ try {
118
+ const watch = fs.watch(getUfooPaths(root).busEventsDir, () => {
119
+ if (surfaceRefresh) return;
120
+ surfaceRefresh = setTimeout(() => {
121
+ surfaceRefresh = null;
122
+ refreshSurfaceObservations();
123
+ }, 25);
124
+ surfaceRefresh.unref?.();
125
+ });
126
+ surfaceWatch = watch;
127
+ watch.unref?.();
128
+ watch.on("error", () => {
129
+ watch.close();
130
+ if (surfaceWatch === watch) surfaceWatch = null;
131
+ });
132
+ } catch { /* Retry from the poll after the first provider event. */ }
133
+ }
134
+ if (!surfacePoll) {
135
+ surfacePoll = setInterval(refreshSurfaceObservations, 500);
136
+ surfacePoll.unref?.();
137
+ }
138
+ }
139
+
140
+ function surfaceFor(agentId) {
141
+ if (!isInternalAgentMeta(getAgentMeta(agentId))) return null;
142
+ if (!surfaces.has(agentId)) {
143
+ const surface = createAgentSurface();
144
+ const opts = ensurePaneMeta(agentId);
145
+ if (Array.isArray(opts.initialEntries)) {
146
+ surface.apply("transcript.reset", { entries: opts.initialEntries });
147
+ } else {
148
+ const initial = (opts.initialLines || []).join("\n");
149
+ if (initial) surface.apply("transcript.append", { kind: "meta", text: initial });
150
+ }
151
+ surfaces.set(agentId, { surface, seq: 0, structured: false });
152
+ }
153
+ return surfaces.get(agentId);
154
+ }
155
+
156
+ function syncActivity(agentId) {
157
+ const view = surfaceFor(agentId);
158
+ if (!view || view.structured) return;
159
+ const meta = getAgentMeta(agentId) || {};
160
+ const key = JSON.stringify([meta.activity_state, meta.activity_detail, meta.activity_since]);
161
+ if (view.activityKey === key) return;
162
+ view.activityKey = key;
163
+ if (meta.activity_state) acceptEvent(agentId, { type: "activity", state: meta.activity_state,
164
+ detail: meta.activity_detail || "", ts: meta.activity_since, started_at: Date.parse(meta.activity_since) || 0,
165
+ authoritative: true });
166
+ }
167
+
168
+ function acceptEvent(agentId, event, seq = 0) {
169
+ const view = surfaceFor(agentId);
170
+ if (!view || (seq > 0 && seq <= view.seq)) return false;
171
+ if (event.type === "submission_failed") {
172
+ const pane = paneManager?.getPane(agentId);
173
+ if (pane && !pane.internalInput) {
174
+ pane.internalInput = String(event.message || "");
175
+ pane.internalCursor = pane.internalInput.length;
176
+ } else if (!pane && !internalDrafts.get(agentId)?.initialInput) {
177
+ internalDrafts.set(agentId, { initialInput: String(event.message || ""), initialCursor: String(event.message || "").length });
178
+ }
179
+ }
180
+ if (seq > 0) { view.seq = seq; view.structured = true; }
181
+ if (event.type === "activity") event = { ...event, authoritative: !view.structured };
182
+ const changed = view.surface.accept(event);
183
+ if (changed) markDirty(agentId);
184
+ return changed;
185
+ }
186
+
187
+ function replaySurfaces() {
188
+ const ids = listInternalAgentIds().filter((id) => !replayedAgents.has(id));
189
+ const root = getProjectRoot();
190
+ if (!root || !ids.length) return;
191
+ const events = readAgentSurfaceEvents(root, ids);
192
+ for (const id of new Set(events.map((event) => event.publisher))) {
193
+ const view = surfaceFor(id);
194
+ if (view && !view.structured) view.surface.apply("transcript.reset", { entries: [] });
195
+ }
196
+ for (const event of events) {
197
+ acceptEvent(event.publisher, event.data.surface, event.seq);
198
+ }
199
+ for (const id of ids) replayedAgents.add(id);
200
+ }
201
+
202
+ function rememberDraft(agentId) {
203
+ const pane = paneManager && paneManager.getPane(agentId);
204
+ if (pane && pane.mode === "internal") {
205
+ internalDrafts.set(agentId, { initialInput: pane.internalInput, initialCursor: pane.internalCursor,
206
+ inputRevision: pane.inputRevision, scrollOffset: pane.scrollOffset });
207
+ }
208
+ }
77
209
 
78
210
  function paneAgentIds() {
79
- if (kind === KIND_SIDE && lockedAgentIds.length > 0) {
80
- return lockedAgentIds.slice();
211
+ const ids = listInternalAgentIds();
212
+ if (kind === KIND_SIDE) {
213
+ const selected = lockedAgentIds.find((id) => ids.includes(id)) || preferredAgentId(ids);
214
+ lockedAgentIds = selected ? [selected] : [];
215
+ return lockedAgentIds;
81
216
  }
82
- return normalizeAgentList(getActiveAgents);
217
+ return ids;
218
+ }
219
+
220
+ function preferredAgentId(ids = listInternalAgentIds()) {
221
+ return ids.includes(lastActiveAgentId) ? lastActiveAgentId : ids[0] || "";
222
+ }
223
+
224
+ function getMode() {
225
+ return active ? kind : "main";
83
226
  }
84
227
 
85
228
  function currentPanesDesc() {
86
229
  return paneAgentIds().map((id) => {
87
- const opts = paneMeta.get(id) || (() => {
88
- try { return resolvePaneOptions(id) || {}; } catch { return {}; }
89
- })();
90
230
  return {
91
231
  agent_id: id,
92
232
  label: String(getLabel(id) || id),
93
- mode: opts.mode === "internal" ? "internal" : "socket",
233
+ mode: "internal",
94
234
  };
95
235
  });
96
236
  }
97
237
 
98
238
  function ensurePaneMeta(id) {
99
239
  if (paneMeta.has(id)) return paneMeta.get(id);
100
- let opts = { mode: "socket" };
240
+ let opts = { mode: "internal" };
101
241
  try {
102
242
  opts = resolvePaneOptions(id) || opts;
103
243
  } catch {
104
244
  // ignore
105
245
  }
106
- if (!opts.mode) opts.mode = "socket";
246
+ if (!opts.mode) opts = { ...opts, mode: "internal" };
107
247
  paneMeta.set(id, opts);
108
248
  return opts;
109
249
  }
@@ -134,7 +274,7 @@ function createRustMultiSession(options = {}) {
134
274
  const last = lastEmitAt.get(id) || 0;
135
275
  if (now - last < MIN_EMIT_GAP_MS) {
136
276
  // Keep dirty; schedule another pass — drop intermediate by only
137
- // re-emitting once the gap elapses (VT snapshot is always current).
277
+ // re-emitting once the gap elapses (transcript snapshot is always current).
138
278
  dirty.add(id);
139
279
  deferred = true;
140
280
  continue;
@@ -149,12 +289,7 @@ function createRustMultiSession(options = {}) {
149
289
  if (!active || !paneManager) return;
150
290
  const pane = paneManager.getPane(agentId);
151
291
  if (!pane) return;
152
- const size = paneSizes.get(agentId) || { cols: DEFAULT_COLS, rows: DEFAULT_ROWS };
153
- const lines = vtScreenToAnsiLines(pane.vt, {
154
- maxCols: Math.max(1, size.cols),
155
- maxRows: Math.max(1, size.rows),
156
- });
157
- const opts = paneMeta.get(agentId) || {};
292
+ const view = pane.surface.snapshot();
158
293
  const meta = (() => {
159
294
  try { return getAgentMeta(agentId) || {}; } catch { return {}; }
160
295
  })();
@@ -162,15 +297,21 @@ function createRustMultiSession(options = {}) {
162
297
  session_id: sessionId,
163
298
  agent_id: agentId,
164
299
  label: String(getLabel(agentId) || agentId),
165
- mode: opts.mode === "internal" ? "internal" : "socket",
166
- lines,
167
- status: String(meta.activity_state || meta.state || "ready"),
300
+ mode: "internal",
301
+ entries: view.entries,
302
+ status: view.status || String(meta.activity_state || "ready"),
303
+ busy: view.busy,
304
+ usage: view.usage,
305
+ plan: view.plan,
306
+ revision: view.revision,
307
+ started_at: view.started_at,
308
+ activity_detail: String(meta.activity_detail || ""),
168
309
  viewport_rev: viewportRev,
310
+ scroll_offset: pane.scrollOffset,
169
311
  };
170
- if (opts.mode === "internal") {
171
- payload.input = String(pane.internalInput || "");
172
- payload.cursor = Number.isFinite(pane.internalCursor) ? pane.internalCursor : 0;
173
- }
312
+ payload.input = String(pane.internalInput || "");
313
+ payload.cursor = Number.isFinite(pane.internalCursor) ? pane.internalCursor : 0;
314
+ payload.input_revision = pane.inputRevision || 0;
174
315
  const emit = typeof publishLossy === "function" ? publishLossy : publish;
175
316
  try { emit("multi.pane.frame", payload); } catch {}
176
317
  }
@@ -185,17 +326,30 @@ function createRustMultiSession(options = {}) {
185
326
  function ensurePaneManager() {
186
327
  if (paneManager) return paneManager;
187
328
  paneManager = createPaneManager({
188
- getInjectSockPath,
189
329
  onPaneOutput: (agentId) => markDirty(agentId),
190
330
  onInternalSubmit: (agentId, message) => {
191
- try { onInternalSubmit(agentId, message); } catch {}
192
331
  markDirty(agentId);
332
+ return onInternalSubmit(agentId, message);
193
333
  },
194
334
  });
195
335
  return paneManager;
196
336
  }
197
337
 
338
+ function publishFrames() {
339
+ if (!active || !paneManager) return;
340
+ for (const id of paneManager.getAgentIds()) publishFrame(id);
341
+ }
342
+
198
343
  function syncAgents() {
344
+ const live = new Set(listInternalAgentIds());
345
+ for (const id of surfaces.keys()) if (!live.has(id)) {
346
+ surfaces.delete(id); replayedAgents.delete(id); internalDrafts.delete(id);
347
+ }
348
+ replaySurfaces();
349
+ // Observe durable provider output independently of daemon inbox delivery.
350
+ // This also covers daemons already running when the package was upgraded.
351
+ refreshSurfaceObservations();
352
+ for (const id of live) syncActivity(id);
199
353
  if (!paneManager) return;
200
354
  const ids = paneAgentIds();
201
355
  const existing = new Set(paneManager.getAgentIds());
@@ -204,13 +358,17 @@ function createRustMultiSession(options = {}) {
204
358
  const opts = ensurePaneMeta(id);
205
359
  const size = paneSizes.get(id) || { cols: DEFAULT_COLS, rows: DEFAULT_ROWS };
206
360
  if (!existing.has(id)) {
207
- paneManager.addAgent(id, size.cols, size.rows, opts);
361
+ paneManager.addAgent(id, size.cols, size.rows, { ...opts, surface: surfaceFor(id).surface, ...internalDrafts.get(id) });
362
+ paneManager.sendResize(id, size.cols, size.rows, size.inputCols || size.cols);
208
363
  markDirty(id);
209
364
  changed = true;
365
+ } else {
366
+ markDirty(id);
210
367
  }
211
368
  }
212
369
  for (const id of existing) {
213
370
  if (!ids.includes(id)) {
371
+ rememberDraft(id);
214
372
  paneManager.removeAgent(id);
215
373
  paneSizes.delete(id);
216
374
  paneMeta.delete(id);
@@ -218,9 +376,9 @@ function createRustMultiSession(options = {}) {
218
376
  changed = true;
219
377
  }
220
378
  }
221
- // Only republish multi.set when membership actually changes. Spamming
222
- // multi.set on every daemon status tick forced Rust to bump viewport_rev
223
- // and drop in-flight pane frames (Ctrl+W felt stuck).
379
+ // Only republish window.set when membership actually changes. Spamming
380
+ // window.set on every daemon status tick forced Rust to bump viewport_rev
381
+ // and drop in-flight pane frames (focus switching felt stuck).
224
382
  if (active && changed) {
225
383
  rev += 1;
226
384
  publishSet();
@@ -236,10 +394,10 @@ function createRustMultiSession(options = {}) {
236
394
  focus = { target: "chat", agent_id: "" };
237
395
  }
238
396
  }
239
- publish("multi.set", {
397
+ publish("window.set", {
240
398
  session_id: sessionId,
241
399
  active,
242
- kind,
400
+ mode: getMode(),
243
401
  rev,
244
402
  panes,
245
403
  focus,
@@ -250,51 +408,46 @@ function createRustMultiSession(options = {}) {
250
408
  /**
251
409
  * @param {object} [options]
252
410
  * @param {"multi"|"side"} [options.kind]
253
- * @param {string[]} [options.agentIds] — required for kind "side" (exactly one)
411
+ * @param {string[]} [options.agentIds] — optional selected child for kind "side"
254
412
  * @param {{ target?: string, agent_id?: string }} [options.focus]
255
413
  */
256
414
  function start(options = {}) {
257
415
  const nextKind = options.kind === KIND_SIDE ? KIND_SIDE : KIND_MULTI;
258
416
  if (active && kind === nextKind && nextKind === KIND_MULTI) {
259
- return { ok: true, session_id: sessionId, kind };
260
- }
261
- if (active) {
262
- stop();
417
+ return { ok: true, session_id: sessionId, mode: getMode() };
263
418
  }
264
-
265
419
  let ids;
266
420
  if (nextKind === KIND_SIDE) {
267
421
  const raw = Array.isArray(options.agentIds) ? options.agentIds : [];
268
- const id = String(raw[0] || "").trim();
269
- if (!id) {
270
- return { ok: false, error: "side requires one agent_id" };
271
- }
272
- ids = [id];
273
- lockedAgentIds = [id];
422
+ const id = String(raw[0] || "").trim() || preferredAgentId();
423
+ if (id && !listInternalAgentIds().includes(id)) return { ok: false, error: "Dashboard supports active internal agents only" };
424
+ ids = id ? [id] : [];
274
425
  } else {
275
- lockedAgentIds = [];
276
- ids = normalizeAgentList(getActiveAgents);
277
- if (ids.length === 0) {
278
- return { ok: false, error: "No active agents for multi-window mode" };
279
- }
426
+ ids = normalizeAgentList(getActiveAgents).filter((id) => isInternalAgentMeta(getAgentMeta(id)));
280
427
  }
281
428
 
429
+ const previousFocus = active ? { ...focus } : null;
430
+ if (active) stop();
431
+ lockedAgentIds = nextKind === KIND_SIDE ? ids.slice() : [];
432
+
282
433
  kind = nextKind;
283
434
  sessionId = generateSessionId(kind);
284
435
  active = true;
285
436
  rev = 1;
286
437
  viewportRev = 0;
287
- const focusOpt = options.focus && typeof options.focus === "object" ? options.focus : null;
288
- if (focusOpt && focusOpt.target === "agent" && String(focusOpt.agent_id || "").trim()) {
438
+ const focusOpt = options.focus && typeof options.focus === "object" ? options.focus
439
+ : nextKind === KIND_MULTI ? previousFocus : null;
440
+ if (focusOpt && focusOpt.target === "agent" && ids.includes(String(focusOpt.agent_id || "").trim())) {
289
441
  focus = {
290
442
  target: "agent",
291
443
  agent_id: String(focusOpt.agent_id).trim(),
292
444
  };
293
- } else if (nextKind === KIND_SIDE) {
445
+ } else if (!focusOpt && nextKind === KIND_SIDE && ids.length) {
294
446
  focus = { target: "agent", agent_id: ids[0] };
295
447
  } else {
296
448
  focus = { target: "chat", agent_id: "" };
297
449
  }
450
+ if (focus.target === "agent") lastActiveAgentId = focus.agent_id;
298
451
  paneSizes.clear();
299
452
  paneMeta.clear();
300
453
  dirty.clear();
@@ -302,10 +455,17 @@ function createRustMultiSession(options = {}) {
302
455
  ensurePaneManager();
303
456
  syncAgents();
304
457
  publishSet();
305
- return { ok: true, session_id: sessionId, kind };
458
+ publishFrames();
459
+ return { ok: true, session_id: sessionId, mode: getMode() };
306
460
  }
307
461
 
308
- function stop() {
462
+ function stop({ clearDrafts = false } = {}) {
463
+ closeSurfaceObservation();
464
+ if (clearDrafts) {
465
+ lastActiveAgentId = "";
466
+ internalDrafts.clear(); surfaces.clear(); replayedAgents.clear();
467
+ surfaceReader = null; observationRoot = "";
468
+ }
309
469
  if (!active && !paneManager) return;
310
470
  if (flushTimer) {
311
471
  clearTimeout(flushTimer);
@@ -313,6 +473,7 @@ function createRustMultiSession(options = {}) {
313
473
  }
314
474
  dirty.clear();
315
475
  if (paneManager) {
476
+ if (!clearDrafts) for (const id of paneManager.getAgentIds()) rememberDraft(id);
316
477
  try { paneManager.disconnectAll(); } catch {}
317
478
  paneManager = null;
318
479
  }
@@ -320,10 +481,10 @@ function createRustMultiSession(options = {}) {
320
481
  paneMeta.clear();
321
482
  lastEmitAt.clear();
322
483
  active = false;
323
- publish("multi.set", {
484
+ publish("window.set", {
324
485
  session_id: sessionId,
325
486
  active: false,
326
- kind,
487
+ mode: "main",
327
488
  rev: rev + 1,
328
489
  panes: [],
329
490
  focus: { target: "chat", agent_id: "" },
@@ -337,6 +498,19 @@ function createRustMultiSession(options = {}) {
337
498
  focus = { target: "chat", agent_id: "" };
338
499
  }
339
500
 
501
+ function setLayout(layout = "cycle", agentId = "") {
502
+ const mode = layout === "cycle"
503
+ ? getMode() === "main" ? "side" : getMode() === "side" ? "multi" : "main"
504
+ : layout;
505
+ if (mode === "main") {
506
+ stop();
507
+ return { ok: true, mode: "main" };
508
+ }
509
+ if (mode === "multi") return start({ kind: KIND_MULTI });
510
+ if (mode === "side") return start({ kind: KIND_SIDE, agentIds: [agentId], focus: { ...focus } });
511
+ return { ok: false, error: "unknown layout" };
512
+ }
513
+
340
514
  function handleViewport(payload = {}) {
341
515
  if (!active || !paneManager) return { ok: false, error: "multi not active" };
342
516
  if (payload.session_id && payload.session_id !== sessionId) {
@@ -354,9 +528,10 @@ function createRustMultiSession(options = {}) {
354
528
  if (!id) continue;
355
529
  const cols = Math.max(1, Math.floor(Number(spec.cols) || DEFAULT_COLS));
356
530
  const rows = Math.max(1, Math.floor(Number(spec.rows) || DEFAULT_ROWS));
357
- paneSizes.set(id, { cols, rows });
531
+ const inputCols = Math.max(1, Math.floor(Number(spec.input_cols) || cols));
532
+ paneSizes.set(id, { cols, rows, inputCols });
358
533
  if (paneManager.getPane(id)) {
359
- try { paneManager.sendResize(id, cols, rows); } catch {}
534
+ try { paneManager.sendResize(id, cols, rows, inputCols); } catch {}
360
535
  markDirty(id);
361
536
  }
362
537
  }
@@ -370,6 +545,19 @@ function createRustMultiSession(options = {}) {
370
545
  }
371
546
  const agentId = String(payload.agent_id || "").trim();
372
547
  if (!agentId) return { ok: false, error: "missing agent_id" };
548
+ const pane = paneManager.getPane(agentId);
549
+ if (!pane || !listInternalAgentIds().includes(agentId)) return { ok: false, error: "Unknown internal agent" };
550
+ if (typeof payload.input === "string") {
551
+ const revision = Number(payload.input_revision);
552
+ if (!Number.isSafeInteger(revision) || revision < 1) return { ok: false, error: "invalid input_revision" };
553
+ if (revision <= (pane.inputRevision || 0)) return { ok: true, stale: true };
554
+ pane.inputRevision = revision;
555
+ pane.internalInput = payload.input;
556
+ pane.internalCursor = Math.max(0, Math.min(payload.input.length, Math.trunc(Number(payload.cursor) || 0)));
557
+ if (payload.submit === true) paneManager.sendInputToAgent(agentId, "\r");
558
+ markDirty(agentId);
559
+ return { ok: true, agent_id: agentId, input_revision: revision };
560
+ }
373
561
  let data = "";
374
562
  if (payload.data_encoding === "base64" && typeof payload.data === "string") {
375
563
  try { data = Buffer.from(payload.data, "base64").toString("utf8"); } catch { data = ""; }
@@ -381,6 +569,21 @@ function createRustMultiSession(options = {}) {
381
569
  return { ok: true };
382
570
  }
383
571
 
572
+ function handleScroll(payload = {}) {
573
+ if (!active || !paneManager) return { ok: false, error: "multi not active" };
574
+ if (payload.session_id && payload.session_id !== sessionId) return { ok: false, error: "stale session_id" };
575
+ const agentId = String(payload.agent_id || "").trim();
576
+ const lines = Math.max(-2000, Math.min(2000, Math.trunc(Number(payload.lines) || 0)));
577
+ const maxOffset = Number.isFinite(Number(payload.max_offset)) ? Math.max(0, Number(payload.max_offset)) : 2000;
578
+ const pane = paneManager.getPane(agentId);
579
+ if (!pane) return { ok: false, error: "agent pane not found" };
580
+ if (Number.isFinite(Number(payload.offset))) {
581
+ pane.scrollOffset = Math.max(0, Math.min(maxOffset, Math.trunc(Number(payload.offset))));
582
+ markDirty(agentId);
583
+ } else paneManager.scrollPane(agentId, lines, maxOffset);
584
+ return { ok: true };
585
+ }
586
+
384
587
  function handleFocus(payload = {}) {
385
588
  if (!active || !paneManager) return { ok: false, error: "multi not active" };
386
589
  if (payload.session_id && payload.session_id !== sessionId) {
@@ -390,6 +593,7 @@ function createRustMultiSession(options = {}) {
390
593
  const agentId = String(payload.agent_id || "").trim();
391
594
  if (target === "agent" && agentId && paneManager.getPane(agentId)) {
392
595
  focus = { target, agent_id: agentId };
596
+ lastActiveAgentId = agentId;
393
597
  try { paneManager.setFocused(agentId); } catch {}
394
598
  } else {
395
599
  focus = { target: "chat", agent_id: "" };
@@ -432,10 +636,10 @@ function createRustMultiSession(options = {}) {
432
636
  function isSideKind() { return active && kind === KIND_SIDE; }
433
637
 
434
638
  function getSnapshot() {
435
- if (!active) return { active: false, kind: "" };
639
+ if (!active) return { active: false, mode: "main" };
436
640
  return {
437
641
  active: true,
438
- kind,
642
+ mode: getMode(),
439
643
  session_id: sessionId,
440
644
  rev,
441
645
  viewport_rev: viewportRev,
@@ -445,12 +649,16 @@ function createRustMultiSession(options = {}) {
445
649
  }
446
650
 
447
651
  function listInternalAgentIds() {
448
- const out = [];
449
- for (const id of paneAgentIds()) {
450
- const opts = paneMeta.get(id) || ensurePaneMeta(id);
451
- if (opts && opts.mode === "internal") out.push(id);
452
- }
453
- return out;
652
+ return normalizeAgentList(getActiveAgents).filter((id) => isInternalAgentMeta(getAgentMeta(id)));
653
+ }
654
+
655
+ function handleExpand(payload = {}) {
656
+ if (!active || payload.session_id !== sessionId) return { ok: false, error: "stale session_id" };
657
+ const view = surfaces.get(payload.agent_id);
658
+ if (!view || !paneManager?.getPane(payload.agent_id)) return { ok: false, error: "agent pane not found" };
659
+ view.surface.toggleExpanded();
660
+ markDirty(payload.agent_id);
661
+ return { ok: true };
454
662
  }
455
663
 
456
664
  function writeToPane(agentId, data) {
@@ -466,6 +674,8 @@ function createRustMultiSession(options = {}) {
466
674
 
467
675
  return {
468
676
  start,
677
+ setLayout,
678
+ getMode,
469
679
  stop,
470
680
  isActive,
471
681
  getSessionId,
@@ -475,6 +685,7 @@ function createRustMultiSession(options = {}) {
475
685
  getSnapshot,
476
686
  handleViewport,
477
687
  handleRaw,
688
+ handleScroll,
478
689
  handleFocus,
479
690
  focusAgent,
480
691
  handleExit,
@@ -482,6 +693,10 @@ function createRustMultiSession(options = {}) {
482
693
  markDirty,
483
694
  writeToPane,
484
695
  listInternalAgentIds,
696
+ acceptEvent,
697
+ publishFrames,
698
+ hasStructuredEvents: (id) => Boolean(surfaces.get(id)?.structured),
699
+ handleExpand,
485
700
  };
486
701
  }
487
702