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
@@ -0,0 +1,341 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const { createTurnIndexStore } = require("../../runtime/context/turnIndexStore");
6
+ const { stripTurnContextWrapper } = require("../../runtime/context/turnAnalyzer");
7
+ const { replayHistory } = require("../../runtime/context/replayHistory");
8
+ const { createSessionJournal } = require("../../runtime/context/sessionJournal");
9
+ const { redactSecrets } = require("../../../runtime/privacy/redactor");
10
+
11
+ function readRuntimeEvents(workspaceRoot, namespace, sessionId) {
12
+ const eventsFile = path.join(path.resolve(workspaceRoot || process.cwd()), ".ufoo", "agent", namespace, "runtimes", sessionId, "events.jsonl");
13
+ if (!fs.existsSync(eventsFile)) return [];
14
+ const raw = fs.readFileSync(eventsFile, "utf8");
15
+ const events = [];
16
+ for (const line of raw.split("\n")) {
17
+ if (!line.trim()) continue;
18
+ try { events.push(JSON.parse(line)); } catch { break; }
19
+ }
20
+ return events;
21
+ }
22
+
23
+ function resolveNamespace(workspaceRoot, sessionId, preferredNamespace) {
24
+ const root = path.resolve(workspaceRoot || process.cwd());
25
+ const candidates = [];
26
+ if (preferredNamespace) candidates.push(preferredNamespace);
27
+ for (const fallback of ["main", "ucode", "main-task", "global-router", "runtime"]) {
28
+ if (!candidates.includes(fallback)) candidates.push(fallback);
29
+ }
30
+ for (const ns of candidates) {
31
+ const turnsFile = path.join(root, ".ufoo", "agent", ns, "context", `${sessionId}.turns.jsonl`);
32
+ if (fs.existsSync(turnsFile)) return ns;
33
+ }
34
+ return preferredNamespace || "ucode";
35
+ }
36
+
37
+ function loadRawTurnMessages({ workspaceRoot, namespace, sessionId, turn }) {
38
+ let journalEvents = [];
39
+ const toMessage = (ev) => {
40
+ const p = (ev && ev.payload) || {};
41
+ const msg = { role: p.role || "assistant" };
42
+ if (p.content !== undefined) msg.content = p.content;
43
+ else if (p.preview !== undefined) msg.content = p.preview;
44
+ if (Array.isArray(p.toolCalls) && p.toolCalls.length) msg.tool_calls = p.toolCalls;
45
+ if (p.toolCallId) msg.tool_call_id = p.toolCallId;
46
+ if (p.artifactId) msg.artifactId = p.artifactId;
47
+ return msg;
48
+ };
49
+ try {
50
+ const journalApi = createSessionJournal({ namespace });
51
+ const loaded = journalApi.loadJournal(workspaceRoot, sessionId);
52
+ journalEvents = Array.isArray(loaded && loaded.events) ? loaded.events : [];
53
+ const matchedByTurn = journalEvents.filter((ev) => ev && ev.turnId === turn.turnId);
54
+ if (matchedByTurn.length > 0) {
55
+ return matchedByTurn.map(toMessage);
56
+ }
57
+ } catch {}
58
+
59
+ const events = readRuntimeEvents(workspaceRoot, namespace, sessionId);
60
+ let accepted = null;
61
+ let terminal = null;
62
+ let acceptedText = "";
63
+ if (events.length > 0) {
64
+ accepted = events.find((e) => e && e.type === "request.accepted" && (e.taskRunId === turn.turnId || e.request?.requestId === turn.turnId));
65
+ terminal = [...events].reverse().find((e) =>
66
+ e && e.taskRunId === turn.turnId && ["task.completed", "task.failed", "task.cancelled", "task.interrupted", "task.paused"].includes(e.type)
67
+ );
68
+ acceptedText = typeof accepted?.request?.text === "string"
69
+ ? accepted.request.text
70
+ : (typeof accepted?.text === "string" ? accepted.text : "");
71
+ if (terminal && terminal.result && Array.isArray(terminal.result.messages)) {
72
+ const offset = Number.isInteger(terminal.result.historyOffset) && terminal.result.historyOffset >= 0
73
+ ? terminal.result.historyOffset
74
+ : 0;
75
+ const sliced = terminal.result.messages.filter((m) => m && m.role !== "system").slice(offset);
76
+ if (sliced.length > 0) return sliced;
77
+ }
78
+ if (terminal && terminal.result && Array.isArray(terminal.result.turnItems)) {
79
+ const msgs = [];
80
+ if (acceptedText.trim()) {
81
+ msgs.push({ role: "user", content: stripTurnContextWrapper(acceptedText) });
82
+ }
83
+ for (const m of terminal.result.turnItems) msgs.push(m);
84
+ if (msgs.length > 0) return msgs;
85
+ }
86
+ }
87
+
88
+ if (journalEvents.length > 0) {
89
+ const allMsgs = journalEvents.map(toMessage);
90
+ if (Number.isInteger(turn.historyOffset) && Number.isInteger(turn.historyEnd) && turn.historyEnd > turn.historyOffset) {
91
+ return allMsgs.slice(turn.historyOffset, turn.historyEnd);
92
+ }
93
+ return allMsgs;
94
+ }
95
+
96
+ if (events.length > 0) {
97
+ if (accepted || terminal) {
98
+ const msgs = [];
99
+ if (acceptedText.trim()) {
100
+ msgs.push({ role: "user", content: stripTurnContextWrapper(acceptedText) });
101
+ }
102
+ if (typeof terminal?.result?.text === "string" && terminal.result.text.trim()) {
103
+ msgs.push({ role: "assistant", content: terminal.result.text });
104
+ }
105
+ if (msgs.length > 0) return msgs;
106
+ }
107
+
108
+ const replayed = replayHistory(events);
109
+ if (replayed.length && Number.isInteger(turn.historyOffset) && Number.isInteger(turn.historyEnd) && turn.historyEnd > turn.historyOffset) {
110
+ return replayed.slice(turn.historyOffset, turn.historyEnd);
111
+ }
112
+ }
113
+
114
+ return [];
115
+ }
116
+
117
+ function sanitizeMessageForDisplay(msg) {
118
+ if (!msg || typeof msg !== "object") return msg;
119
+ const copy = { ...msg };
120
+ if (copy.role === "user") {
121
+ if (typeof copy.content === "string") {
122
+ copy.content = stripTurnContextWrapper(copy.content);
123
+ } else if (Array.isArray(copy.content)) {
124
+ copy.content = copy.content
125
+ .map((part) => (part && part.type === "text" && typeof part.text === "string"
126
+ ? { ...part, text: stripTurnContextWrapper(part.text) }
127
+ : part))
128
+ .filter((part) => !(part && part.type === "text" && !part.text));
129
+ }
130
+ }
131
+ return redactSecrets(copy);
132
+ }
133
+
134
+ function emitToolEvent(callback, event = {}) {
135
+ if (typeof callback !== "function") return;
136
+ try {
137
+ callback(event && typeof event === "object" ? { ...event } : {});
138
+ } catch {
139
+ // observer callback errors must not break recall_turn execution
140
+ }
141
+ }
142
+
143
+ function createTurnRecallCapability(host = {}, { defaultNamespace = "" } = {}) {
144
+ return {
145
+ id: "turn-recall",
146
+ version: "1.0",
147
+ promptSections: [
148
+ "When <turn_context> mentions off-window topics or relevant past turns and you need exact prior code, file paths, or tool results, call recall_turn (mode='search' to find turn_ids, mode='detail' with turn_id to page through raw transcript).",
149
+ ],
150
+ tools: [
151
+ {
152
+ name: "recall_turn",
153
+ description: "Recall earlier turns from the current session index by semantic/keyword search or paginate full raw messages/tool results for a specific turn_id.",
154
+ permissions: [],
155
+ deferable: true,
156
+ inputSchema: {
157
+ type: "object",
158
+ properties: {
159
+ mode: {
160
+ type: "string",
161
+ enum: ["search", "detail"],
162
+ description: "Use 'search' to find relevant turns by query/topic, or 'detail' to inspect raw transcript messages for turn_id.",
163
+ },
164
+ query: {
165
+ type: "string",
166
+ description: "Search keywords, file path, symbol name, or topic (for search mode).",
167
+ },
168
+ topic: {
169
+ type: "string",
170
+ description: "Optional topic slug filter (for search mode).",
171
+ },
172
+ turn_id: {
173
+ type: "string",
174
+ description: "Specific turnId to read in detail mode.",
175
+ },
176
+ turnId: {
177
+ type: "string",
178
+ description: "Alias for turn_id in detail mode.",
179
+ },
180
+ limit: {
181
+ type: "integer",
182
+ minimum: 1,
183
+ maximum: 20,
184
+ description: "Maximum search results to return (default 6).",
185
+ },
186
+ page: {
187
+ type: "integer",
188
+ minimum: 1,
189
+ description: "1-based page number for detail mode pagination (default 1).",
190
+ },
191
+ page_chars: {
192
+ type: "integer",
193
+ minimum: 400,
194
+ maximum: 24000,
195
+ description: "Characters per page for detail mode (default 4000).",
196
+ },
197
+ pageChars: {
198
+ type: "integer",
199
+ minimum: 400,
200
+ maximum: 24000,
201
+ description: "Alias for page_chars in detail mode.",
202
+ },
203
+ },
204
+ additionalProperties: false,
205
+ },
206
+ async handler(args = {}, context = {}) {
207
+ const safeArgs = args && typeof args === "object" ? { ...args } : {};
208
+ const finish = (result) => {
209
+ if (!result || result.ok === false) {
210
+ emitToolEvent(context.onToolEvent, {
211
+ tool: "recall_turn",
212
+ phase: "error",
213
+ args: safeArgs,
214
+ error: String((result && result.error) || "recall_turn failed"),
215
+ });
216
+ } else {
217
+ emitToolEvent(context.onToolEvent, {
218
+ tool: "recall_turn",
219
+ phase: "end",
220
+ args: safeArgs,
221
+ result,
222
+ error: "",
223
+ });
224
+ }
225
+ return result;
226
+ };
227
+
228
+ emitToolEvent(context.onToolEvent, {
229
+ tool: "recall_turn",
230
+ phase: "start",
231
+ args: safeArgs,
232
+ });
233
+
234
+ try {
235
+ const workspaceRoot = context.workspaceRoot || host.projectRoot || process.cwd();
236
+ const sessionId = String(context.sessionId || host.sessionId || "").trim();
237
+ if (!sessionId) {
238
+ return finish({ ok: false, code: "missing_session", error: "recall_turn requires an active sessionId" });
239
+ }
240
+ const preferredNs = host.contextNamespace || context.contextNamespace || defaultNamespace || context.artifactNamespace || "";
241
+ const namespace = resolveNamespace(workspaceRoot, sessionId, preferredNs);
242
+ const store = createTurnIndexStore({
243
+ workspaceRoot,
244
+ namespace,
245
+ sessionId,
246
+ redact: redactSecrets,
247
+ });
248
+
249
+ const rawTurnId = String(args.turn_id || args.turnId || "").trim();
250
+ const mode = args.mode || (rawTurnId && !args.query ? "detail" : "search");
251
+ if (mode === "detail") {
252
+ const turnId = rawTurnId;
253
+ if (!turnId) {
254
+ return finish({ ok: false, code: "invalid_arguments", error: "turn_id is required when mode is 'detail'" });
255
+ }
256
+ const turn = store.getTurn(turnId);
257
+ if (!turn) {
258
+ return finish({ ok: false, code: "turn_not_found", error: `turn not found in current session: ${turnId}` });
259
+ }
260
+ const rawMessages = loadRawTurnMessages({ workspaceRoot, namespace, sessionId, turn })
261
+ .map(sanitizeMessageForDisplay);
262
+ const payload = redactSecrets({
263
+ turn: {
264
+ turnId: turn.turnId,
265
+ turnIndex: turn.turnIndex,
266
+ topic: turn.topic,
267
+ turnKind: turn.turnKind,
268
+ outcome: turn.outcome,
269
+ modifiedFiles: turn.modifiedFiles,
270
+ touchedFiles: turn.touchedFiles,
271
+ artifactIds: turn.artifactIds,
272
+ decisions: turn.decisions,
273
+ },
274
+ messages: rawMessages.length ? rawMessages : [
275
+ { role: "user", content: turn.rawUserText || turn.userSummary },
276
+ ...(turn.assistantSummary ? [{ role: "assistant", content: turn.assistantSummary }] : []),
277
+ ],
278
+ });
279
+ const fullText = JSON.stringify(payload, null, 2);
280
+ const pageChars = Math.max(400, Math.min(24000, Number(args.page_chars ?? args.pageChars) || 4000));
281
+ const totalPages = Math.max(1, Math.ceil(fullText.length / pageChars));
282
+ const page = Math.max(1, Math.min(totalPages, Number(args.page) || 1));
283
+ const start = (page - 1) * pageChars;
284
+ const content = fullText.slice(start, start + pageChars);
285
+ return finish(redactSecrets({
286
+ ok: true,
287
+ mode: "detail",
288
+ sessionId,
289
+ namespace,
290
+ turnId: turn.turnId,
291
+ topic: turn.topic,
292
+ outcome: turn.outcome,
293
+ page,
294
+ totalPages,
295
+ totalChars: fullText.length,
296
+ hasMore: page < totalPages,
297
+ content,
298
+ }));
299
+ }
300
+
301
+ const limit = Math.max(1, Math.min(20, Number(args.limit) || 6));
302
+ const hits = store.search(args.query || "", { limit, topic: args.topic });
303
+ return finish(redactSecrets({
304
+ ok: true,
305
+ mode: "search",
306
+ sessionId,
307
+ namespace,
308
+ count: hits.length,
309
+ turns: hits.map(({ turn, score, matchedTerms }) => ({
310
+ turnId: turn.turnId,
311
+ turn_id: turn.turnId,
312
+ turnIndex: turn.turnIndex,
313
+ topic: turn.topic,
314
+ turnKind: turn.turnKind,
315
+ outcome: turn.outcome,
316
+ userSummary: turn.userSummary,
317
+ assistantSummary: turn.assistantSummary,
318
+ modifiedFiles: turn.modifiedFiles,
319
+ touchedFiles: turn.touchedFiles,
320
+ artifactIds: turn.artifactIds,
321
+ score,
322
+ matchedTerms,
323
+ })),
324
+ topics: store.listTopics().slice(0, 12),
325
+ }));
326
+ } catch (error) {
327
+ emitToolEvent(context.onToolEvent, {
328
+ tool: "recall_turn",
329
+ phase: "error",
330
+ args: safeArgs,
331
+ error: String((error && error.message) || "recall_turn failed"),
332
+ });
333
+ throw error;
334
+ }
335
+ },
336
+ },
337
+ ],
338
+ };
339
+ }
340
+
341
+ module.exports = { createTurnRecallCapability };
@@ -42,9 +42,9 @@ function resolveDispatchTargets(ctx, target) {
42
42
  const targets = target === "broadcast"
43
43
  ? Object.keys(agents)
44
44
  : eventBus.messageManager.resolveTarget(target);
45
- const active = targets.filter((id) => id !== "ufoo-agent" && isInternalAgentMeta(agents[id]) && isMetaActive(agents[id]));
45
+ const active = targets.filter((id) => id !== "ufoo-agent" && (ctx.includeExternalAgents || isInternalAgentMeta(agents[id])) && isMetaActive(agents[id]));
46
46
  if (active.length) return active;
47
- throw buildStructuredError("invalid_target", `dispatch_message target not found among active internal agents: ${target}`);
47
+ throw buildStructuredError("invalid_target", `dispatch_message target not found among active project agents: ${target}`);
48
48
  }
49
49
  if (typeof ctx.resolveDispatchTargets === "function") {
50
50
  const resolved = ctx.resolveDispatchTargets(target);
@@ -347,7 +347,7 @@ async function handleEvent(
347
347
  const taskId = getTaskIdFromEvent(evt) || inherited.taskId || `worker-${randomUUID()}`;
348
348
  const runtimeContext = { ...inherited, taskId, traceId: inherited.traceId || taskId,
349
349
  taskRunId: `worker-run-${randomUUID()}`, requestId: `bus-${evt.seq || randomUUID()}`, attemptId: `attempt-${randomUUID()}`,
350
- requestKind: publisher === "ufoo-agent" && getTaskIdFromEvent(evt) ? "worker-task" : "bus-message" };
350
+ requestKind: evt.__runtimeWake ? "system_wake" : publisher === "ufoo-agent" && getTaskIdFromEvent(evt) ? "worker-task" : "bus-message" };
351
351
  const emitSurface = event => busSender.surface?.({ ...runtimeContext, task_id: taskId, agentId: subscriber,
352
352
  provider, model, sessionId: threadRuntime?.thread?.id || "", ...event });
353
353
  const delegated = publisher === "ufoo-agent" && Boolean(getTaskIdFromEvent(evt));
@@ -537,7 +537,7 @@ async function handleThreadedEvent({
537
537
  } else {
538
538
  // Live progress belongs to the worker pane. Peers receive only the final
539
539
  // answer, including an explicitly empty ack-only result.
540
- if (reply) busSender.enqueue(publisher, reply);
540
+ if (reply && runtimeContext.requestKind !== "system_wake") busSender.enqueue(publisher, reply);
541
541
  }
542
542
  await busSender.flush();
543
543
  return {
@@ -571,7 +571,7 @@ async function handleThreadedEvent({
571
571
  publisher,
572
572
  JSON.stringify({ stream: true, done: true, reason: "error" })
573
573
  );
574
- } else {
574
+ } else if (runtimeContext.requestKind !== "system_wake") {
575
575
  busSender.enqueue(publisher, errorText);
576
576
  }
577
577
  await busSender.flush();
@@ -894,6 +894,9 @@ async function runInternalRunner({ projectRoot, agentType = "codex", extraArgs =
894
894
  let lastHeartbeat = 0;
895
895
  const HEARTBEAT_INTERVAL = 30000; // 30秒心跳间隔
896
896
  const runnerAbort = new AbortController();
897
+ const { createTaskControl, startTaskControlServer } = require("./taskControl");
898
+ const taskControl = createTaskControl(runnerAbort.signal);
899
+ const controlServer = await startTaskControlServer(projectRoot, subscriber, taskControl);
897
900
 
898
901
  const stop = () => {
899
902
  running = false;
@@ -945,7 +948,7 @@ async function runInternalRunner({ projectRoot, agentType = "codex", extraArgs =
945
948
  }
946
949
  };
947
950
 
948
- while (running) {
951
+ try { while (running) {
949
952
  // 定期心跳更新
950
953
  const now = Date.now();
951
954
  if (now - lastHeartbeat > HEARTBEAT_INTERVAL) {
@@ -988,7 +991,7 @@ async function runInternalRunner({ projectRoot, agentType = "codex", extraArgs =
988
991
  try {
989
992
  for (const runnableEvent of runnableEvents) {
990
993
  // eslint-disable-next-line no-await-in-loop
991
- await handleEvent(
994
+ await taskControl.run((signal) => handleEvent(
992
995
  projectRoot,
993
996
  parsedAgentType,
994
997
  provider,
@@ -1001,8 +1004,8 @@ async function runInternalRunner({ projectRoot, agentType = "codex", extraArgs =
1001
1004
  threadRuntime,
1002
1005
  bootstrap.promptText,
1003
1006
  activityTracker,
1004
- runnerAbort.signal
1005
- );
1007
+ signal
1008
+ ));
1006
1009
  if (runnableEvent.__internalRawInput) {
1007
1010
  getInteractiveSession(runnableEvent.publisher || "unknown").writeResponsePrompt();
1008
1011
  }
@@ -1026,11 +1029,30 @@ async function runInternalRunner({ projectRoot, agentType = "codex", extraArgs =
1026
1029
  processing = false;
1027
1030
  }
1028
1031
  }
1032
+ if (running && threadRuntime.thread?.pollWakes) {
1033
+ await threadRuntime.thread.pollWakes(async (event, claim, text) => {
1034
+ if (!running || !claim()) return false;
1035
+ activityTracker.notifyTurnStart("thinking");
1036
+ try {
1037
+ await taskControl.run((signal) => handleEvent(projectRoot, parsedAgentType, provider, model, subscriber, nickname,
1038
+ { publisher: "runtime", __runtimeWake: true, seq: event.id,
1039
+ data: { message: text, runtime_context: { parentTaskRunId: event.ownerTaskRunId } } },
1040
+ busSender, bootstrap.extraArgs, threadRuntime, bootstrap.promptText, activityTracker, signal));
1041
+ await busSender.flush();
1042
+ } finally { if (activityTracker.getState().state !== "waiting_input") activityTracker.markIdle(); }
1043
+ return true;
1044
+ });
1045
+ }
1029
1046
  // eslint-disable-next-line no-await-in-loop
1030
1047
  await sleep(1000);
1031
1048
  }
1032
1049
 
1033
- await threadRuntime.close();
1050
+ } finally {
1051
+ await controlServer.close();
1052
+ process.removeListener("SIGTERM", stop);
1053
+ process.removeListener("SIGINT", stop);
1054
+ await threadRuntime.close();
1055
+ }
1034
1056
  }
1035
1057
 
1036
1058
  module.exports = {
@@ -0,0 +1,107 @@
1
+ "use strict";
2
+
3
+ const net = require("net");
4
+ const fs = require("fs");
5
+ const path = require("path");
6
+ const os = require("os");
7
+ const { createHash } = require("crypto");
8
+ const { getUfooPaths } = require("../../coordination/state/paths");
9
+ const { loadAgentsData } = require("../../coordination/state/agentsStore");
10
+ const { isInternalAgentMeta } = require("../../runtime/contracts/agentMode");
11
+ const { isMetaActive } = require("../../coordination/bus/utils");
12
+
13
+ function socketPath(root, subscriber) {
14
+ const key = createHash("sha256").update(`${path.resolve(root)}\0${subscriber}`).digest("hex").slice(0, 24);
15
+ return path.join(os.tmpdir(), `ufctl-${key}.sock`);
16
+ }
17
+
18
+ // The control channel stays responsive while the inbox is executing a turn.
19
+ // Each turn gets a fresh signal: cancellation never poisons the next message.
20
+ function createTaskControl(parentSignal) {
21
+ let active = null;
22
+ return {
23
+ cancel() {
24
+ if (!active) return { ok: true, cancelled: false };
25
+ active.abort("user_cancelled");
26
+ return { ok: true, cancelled: true };
27
+ },
28
+ async run(fn) {
29
+ if (active) throw new Error("An internal turn is already running");
30
+ const controller = new AbortController();
31
+ const abort = () => controller.abort(parentSignal?.reason || "runner_stopped");
32
+ active = controller;
33
+ if (parentSignal?.aborted) abort();
34
+ else parentSignal?.addEventListener("abort", abort, { once: true });
35
+ try { return await fn(controller.signal); }
36
+ finally { parentSignal?.removeEventListener("abort", abort); active = null; }
37
+ },
38
+ };
39
+ }
40
+
41
+ function callControl(file, request) {
42
+ return new Promise((resolve, reject) => {
43
+ const socket = net.createConnection(file);
44
+ let buffer = "";
45
+ const finish = (error, result) => {
46
+ clearTimeout(timer); socket.removeAllListeners(); socket.destroy();
47
+ if (error) reject(error); else resolve(result);
48
+ };
49
+ const timer = setTimeout(() => finish(new Error("Internal agent control timed out")), 2000);
50
+ socket.on("connect", () => socket.write(`${JSON.stringify(request)}\n`));
51
+ socket.on("error", error => finish(error));
52
+ socket.on("end", () => finish(new Error("Internal agent control closed without a reply")));
53
+ socket.on("data", chunk => {
54
+ buffer += chunk;
55
+ if (buffer.length > 4096) return finish(new Error("Invalid control reply"));
56
+ if (!buffer.includes("\n")) return;
57
+ try { finish(null, JSON.parse(buffer.split("\n")[0])); }
58
+ catch (error) { finish(error); }
59
+ });
60
+ });
61
+ }
62
+
63
+ async function startTaskControlServer(root, subscriber, control) {
64
+ const file = socketPath(root, subscriber);
65
+ if (fs.existsSync(file)) {
66
+ try { await callControl(file, { action: "status" }); throw new Error("Internal agent control is already running"); }
67
+ catch (error) {
68
+ if (!["ECONNREFUSED", "ENOENT"].includes(error.code)) throw error;
69
+ fs.rmSync(file, { force: true });
70
+ }
71
+ }
72
+ const sockets = new Set();
73
+ const server = net.createServer(socket => {
74
+ sockets.add(socket); socket.once("close", () => sockets.delete(socket));
75
+ socket.on("error", () => {});
76
+ socket.setTimeout(2000, () => socket.destroy());
77
+ let buffer = "";
78
+ socket.on("data", chunk => {
79
+ buffer += chunk;
80
+ if (buffer.length > 4096) return socket.destroy();
81
+ if (!buffer.includes("\n")) return;
82
+ socket.removeAllListeners("data");
83
+ try {
84
+ const request = JSON.parse(buffer.split("\n")[0]);
85
+ const result = request.action === "cancel" ? control.cancel()
86
+ : request.action === "status" ? { ok: true } : { ok: false, error: "Unsupported control action" };
87
+ socket.end(`${JSON.stringify(result)}\n`);
88
+ } catch { socket.end(`${JSON.stringify({ ok: false, error: "Invalid control request" })}\n`); }
89
+ });
90
+ });
91
+ await new Promise((resolve, reject) => { server.once("error", reject); server.listen(file, resolve); });
92
+ fs.chmodSync(file, 0o600);
93
+ server.unref();
94
+ return { close: () => new Promise(resolve => {
95
+ for (const socket of sockets) socket.destroy();
96
+ server.close(() => { fs.rmSync(file, { force: true }); resolve(); });
97
+ }) };
98
+ }
99
+
100
+ async function cancelInternalTask(root, subscriber) {
101
+ const meta = loadAgentsData(getUfooPaths(root).agentsFile).agents?.[subscriber];
102
+ if (!isInternalAgentMeta(meta) || !isMetaActive(meta)) return { ok: false, error: "Unknown active internal agent" };
103
+ try { return await callControl(socketPath(root, subscriber), { action: "cancel" }); }
104
+ catch (error) { return { ok: false, error: `Cannot cancel this agent's task; restart its worker to enable controls (${error.code || error.message})` }; }
105
+ }
106
+
107
+ module.exports = { createTaskControl, startTaskControlServer, cancelInternalTask };
@@ -2,5 +2,5 @@
2
2
 
3
3
  module.exports = Object.freeze({
4
4
  id: "coding",
5
- capabilities: Object.freeze(["coding", "planning", "skills"]),
5
+ capabilities: Object.freeze(["coding", "planning", "skills", "turn-recall", "browser"]),
6
6
  });
@@ -1,5 +1,5 @@
1
1
  "use strict";
2
2
  module.exports = Object.freeze({ id: "main", capabilities: Object.freeze([
3
- "coding", "planning", "skills", "agent-management", "agent-routing", "project-discovery", "shared-memory",
3
+ "coding", "planning", "skills", "turn-recall", "browser", "agent-management", "agent-routing", "project-discovery", "shared-memory",
4
4
  "task-reports", "task-execution", "groups", "scheduling",
5
5
  ]) });
@@ -22,6 +22,7 @@ function buildMainAgentPrompt({ global = false, workspaceRoot, toolNames = [], p
22
22
  if (!global) sections.push(getSystemSection(), getDoingTasksSection({ taskTool: "manage_tasks", planTool: "" }), getActionsSection(), getSafetySection(), getOutputEfficiencySection(), COOPERATION_GUIDANCE, [
23
23
  "Coordination and execution:",
24
24
  "- Managed workers are internal codex, claude or ucode agents only. Model provider choices do not add worker types. Worker launches never open external terminals.",
25
+ "- The communication directory also includes registered external agents. You may address them with dispatch_message or delegate_task(target=existing identity), and receive their replies/reports. External agents keep their own host, terminal and receive path; do not open panes, close, resume or take over their processes. Launch mode controls lifecycle ownership, not communication eligibility.",
25
26
  "- Use manage_tasks operation=start with a stable command_id and objective for long or independent coding work. It runs in a separate context and returns immediately. Use inspect/list/cancel for status and cancellation.",
26
27
  "- Keep the main conversation available while children execute. Raw child transcripts are not your history. Use the completion summary and verify the outcome.",
27
28
  "- After a child completes, run relevant validation in its workspace. Use manage_tasks operation=accept with task_run_id, reason and evidence containing your successful bash toolCallIds after completion; use reject when the result needs revision. Execution completion is not acceptance.",
@@ -12,7 +12,13 @@ Usage notes:
12
12
  - Use write instead of echo/cat heredoc.
13
13
  - Use edit instead of sed/awk.
14
14
  - Use absolute paths when possible. The working directory resets between calls.
15
- - Do not run long-running processes (dev servers, watchers, interactive apps). Suggest the user run these manually.
15
+ - Long-running processes (dev servers, watchers, local preview servers):
16
+ - Start them with \`background: true\` (optional \`startupWaitMs\`, default 2500ms). This returns \`backgroundId\`, \`pid\`, \`running\`, \`logPath\`, \`nextOffset\`, and initial \`logOutput\` (such as bound ports/URLs or startup errors).
17
+ - Observe background output anytime with \`action: "logs"\` and \`backgroundId\`: pass \`offset: <previous nextOffset>\` for incremental new logs, or omit \`offset\` (optionally with \`tailLines\`) to inspect recent lines; use \`waitMs\` to briefly wait for new output.
18
+ - Manage lifecycle with \`action: "status"\`, \`action: "list"\`, and \`action: "stop"\` (with \`backgroundId\`).
19
+ - Supported native hosts automatically notify your session when a background command exits. Use \`wake: {conditions: [{type: "log_contains", text: "ready"}]}\` for a literal log match, \`file_exists\` with a workspace \`path\`, or \`port_open\` with a local \`port\`. Each condition fires once; \`wake.onExit: false\` disables the exit notification. A registered wake is reported in the tool result.
20
+ - After registering a wake, you may finish the foreground turn or do other work. Do not poll logs repeatedly just to keep the agent alive. Notifications resume the original session at a turn boundary and do not answer pending user questions. Stop/cancellation revokes the task's subscriptions. Runtime events never authorize replaying a command.
21
+ - Still do NOT run interactive full-screen TTY apps (vim, nano, top, less) that require keyboard input.
16
22
  - For git commands: prefer new commits over amending, never skip hooks (--no-verify) unless explicitly asked.
17
23
  - Quote file paths that contain spaces with double quotes.
18
24
  - When chaining commands: use && for sequential dependent commands, ; when you don't care if earlier commands fail.`;
@@ -18,7 +18,7 @@ const PROJECTS_DIR = path.join(CLAUDE_CONFIG_DIR, "projects");
18
18
 
19
19
  /**
20
20
  * Encode a CWD path to Claude Code's project directory name.
21
- * e.g. "/Users/icy/Code/ufoo" → "-Users-icy-Code-ufoo"
21
+ * e.g. "/Users/developer/Code/ufoo" → "-Users-developer-Code-ufoo"
22
22
  */
23
23
  function encodeProjectPath(cwd) {
24
24
  return String(cwd || "").replace(/\//g, "-");
@@ -40,7 +40,12 @@ function buildThreadOptions({
40
40
  options.skipGitRepoCheck = true;
41
41
  }
42
42
  if (options.sandboxMode === undefined) {
43
- options.sandboxMode = "workspace-write";
43
+ // Internal workers currently need host access for simulators and build
44
+ // caches. Keep explicit caller restrictions intact for permission controls.
45
+ options.sandboxMode = "danger-full-access";
46
+ }
47
+ if (options.approvalPolicy === undefined) {
48
+ options.approvalPolicy = "never";
44
49
  }
45
50
  // SDK workspace-write disables sockets unless explicitly enabled. Coding
46
51
  // tools need local services too (ADB, Gradle, dev servers), not just HTTP.