u-foo 3.1.3 → 3.1.5
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.
- package/README.md +11 -0
- package/dist/tui/darwin-arm64/ufoo-tui +0 -0
- package/dist/tui/darwin-x64/ufoo-tui +0 -0
- package/dist/tui/linux-arm64/ufoo-tui +0 -0
- package/dist/tui/linux-x64/ufoo-tui +0 -0
- package/package.json +1 -1
- package/src/code/agent.js +3 -0
- package/src/code/nativeRunner.js +49 -10
- package/src/code/providers/visionBlocks.js +41 -0
- package/src/code/repl.js +11 -0
- package/src/code/taskDecomposer.js +1 -0
- package/src/code/toolBudget.js +21 -0
- package/src/code/toolLoopGuard.js +55 -0
- package/src/coordination/bus/index.js +4 -4
- package/src/coordination/bus/message.js +5 -11
- package/src/runtime/daemon/controlPlaneService.js +21 -10
- package/src/runtime/daemon/globalDaemon.js +160 -1
- package/src/runtime/daemon/index.js +47 -22
- package/src/runtime/daemon/mcpServer.js +9 -3
- package/src/runtime/daemon/projectRuntimeGateway.js +22 -8
- package/src/ui/rustUcodeHost.js +1 -0
package/README.md
CHANGED
|
@@ -67,6 +67,17 @@ Installed binaries:
|
|
|
67
67
|
| `ukimi` | Kimi Code wrapper with ufoo bootstrap and bus identity. |
|
|
68
68
|
| `ucode` | Native ufoo coding-agent CLI/TUI. |
|
|
69
69
|
|
|
70
|
+
`ucode` has no tool-call count limit by default. Set an optional per-run cap with
|
|
71
|
+
`ucode --max-tool-calls 200`, or `UFOO_UCODE_MAX_TOOL_CALLS=200 ucode`.
|
|
72
|
+
`ucode --max-tool-calls none` explicitly disables the cap, including an environment
|
|
73
|
+
override. The CLI option takes precedence. Limits count individual tool calls,
|
|
74
|
+
not model turns; timeouts and the tool-error budget still apply.
|
|
75
|
+
Consecutive identical tool batches trigger a model reminder, then stop the run
|
|
76
|
+
if repetition continues: read/plan-only batches warn at 4 steps and stop at 8;
|
|
77
|
+
other batches warn at 8 and stop at 12. Comparison uses tool names and arguments,
|
|
78
|
+
ignoring JSON key order and parallel call order. A different batch resets the
|
|
79
|
+
streak; this is not a semantic check of tool results or alternating loops.
|
|
80
|
+
|
|
70
81
|
## Quick Start
|
|
71
82
|
|
|
72
83
|
Initialize a project and open the chat dashboard:
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
package/package.json
CHANGED
package/src/code/agent.js
CHANGED
|
@@ -667,6 +667,7 @@ async function runNaturalLanguageTask(task = "", state = {}, options = {}) {
|
|
|
667
667
|
messages: historyMessages,
|
|
668
668
|
sessionId: String(sessionIdValue || state.sessionId || ""),
|
|
669
669
|
timeoutMs: timeoutOverrideMs,
|
|
670
|
+
maxToolCalls: state.maxToolCalls,
|
|
670
671
|
onStreamDelta: onStream,
|
|
671
672
|
onThinkingDelta,
|
|
672
673
|
onPhase,
|
|
@@ -1178,6 +1179,7 @@ async function resumeAfterUserInteraction(answerText = "", state = {}, options =
|
|
|
1178
1179
|
messages,
|
|
1179
1180
|
sessionId: String(state.sessionId || ""),
|
|
1180
1181
|
onToolEvent: pushToolLog,
|
|
1182
|
+
maxToolCalls: state.maxToolCalls,
|
|
1181
1183
|
onStreamDelta: trackingOnDelta,
|
|
1182
1184
|
onThinkingDelta: typeof options.onThinkingDelta === "function" ? options.onThinkingDelta : null,
|
|
1183
1185
|
onPhase: typeof options.onPhase === "function" ? options.onPhase : null,
|
|
@@ -1311,6 +1313,7 @@ if (require.main === module) {
|
|
|
1311
1313
|
systemPrompt: parsed.systemPrompt,
|
|
1312
1314
|
sessionId: parsed.sessionId,
|
|
1313
1315
|
timeoutMs: parsed.timeoutMs,
|
|
1316
|
+
maxToolCalls: parsed.maxToolCalls,
|
|
1314
1317
|
jsonOutput: parsed.jsonOutput,
|
|
1315
1318
|
forceTui: parsed.forceTui,
|
|
1316
1319
|
disableTui: parsed.disableTui,
|
package/src/code/nativeRunner.js
CHANGED
|
@@ -19,6 +19,9 @@ const {
|
|
|
19
19
|
sanitizeModelMessages,
|
|
20
20
|
} = require("./context/assembler");
|
|
21
21
|
const { systemBlocksToAnthropicPayload } = require("./context/promptLayers");
|
|
22
|
+
const { retireMessageImages } = require("./providers/visionBlocks");
|
|
23
|
+
const { resolveMaxToolCalls } = require("./toolBudget");
|
|
24
|
+
const { ToolLoopGuard } = require("./toolLoopGuard");
|
|
22
25
|
const { parseStructuredSideEffects } = require("./context/stateCommit");
|
|
23
26
|
const {
|
|
24
27
|
emptyExecutionState,
|
|
@@ -109,10 +112,8 @@ const DEFAULT_XAI_BASE_URL = "https://api.x.ai/v1";
|
|
|
109
112
|
const DEFAULT_GROK_BUILD_BASE_URL = DEFAULT_XAI_BASE_URL;
|
|
110
113
|
const DEFAULT_GROK_BUILD_MODEL = "grok-4.6";
|
|
111
114
|
const DEFAULT_KIMI_MODEL = "k3";
|
|
112
|
-
//
|
|
113
|
-
|
|
114
|
-
// for non-trivial tasks while still catching runaway loops. Override via env.
|
|
115
|
-
const DEFAULT_MAX_NATIVE_TOOL_CALLS = 100;
|
|
115
|
+
// No tool-call cap unless explicitly configured by the caller or environment.
|
|
116
|
+
const DEFAULT_MAX_NATIVE_TOOL_CALLS = null;
|
|
116
117
|
const DEFAULT_MAX_NATIVE_TOOL_ERRORS = 20;
|
|
117
118
|
const MAX_EMPTY_TERMINAL_RETRIES = 2;
|
|
118
119
|
const DEFAULT_NATIVE_TIMEOUT_MS = 43200000; // 12 hours
|
|
@@ -190,9 +191,9 @@ function normalizePositiveInt(value, fallback) {
|
|
|
190
191
|
return Math.floor(parsed);
|
|
191
192
|
}
|
|
192
193
|
|
|
193
|
-
function resolveNativeToolBudget(env = process.env) {
|
|
194
|
+
function resolveNativeToolBudget(maxToolCalls, env = process.env) {
|
|
194
195
|
return {
|
|
195
|
-
maxToolCalls:
|
|
196
|
+
maxToolCalls: resolveMaxToolCalls(maxToolCalls, env),
|
|
196
197
|
maxToolErrors: normalizePositiveInt(env.UFOO_UCODE_MAX_TOOL_ERRORS, DEFAULT_MAX_NATIVE_TOOL_ERRORS),
|
|
197
198
|
};
|
|
198
199
|
}
|
|
@@ -300,7 +301,7 @@ function enforceNativeToolBudget({
|
|
|
300
301
|
lastTool = "",
|
|
301
302
|
lastError = "",
|
|
302
303
|
} = {}) {
|
|
303
|
-
if (toolCallsExecuted >= maxToolCalls) {
|
|
304
|
+
if (maxToolCalls != null && toolCallsExecuted >= maxToolCalls) {
|
|
304
305
|
throw new Error(`tool call budget exceeded (${maxToolCalls})`);
|
|
305
306
|
}
|
|
306
307
|
if (toolErrors >= maxToolErrors) {
|
|
@@ -2129,6 +2130,7 @@ async function runNativeLoop({
|
|
|
2129
2130
|
provider = "",
|
|
2130
2131
|
accountId = "",
|
|
2131
2132
|
timeoutMs = DEFAULT_NATIVE_TIMEOUT_MS,
|
|
2133
|
+
maxToolCalls = undefined,
|
|
2132
2134
|
onStreamDelta = null,
|
|
2133
2135
|
onThinkingDelta = null,
|
|
2134
2136
|
onPhase = null,
|
|
@@ -2206,7 +2208,8 @@ async function runNativeLoop({
|
|
|
2206
2208
|
: emptyExecutionState();
|
|
2207
2209
|
if (typeof executionState.planMode !== "boolean") executionState.planMode = false;
|
|
2208
2210
|
ensurePendingUserPrompts(executionState);
|
|
2209
|
-
const toolBudget = resolveNativeToolBudget();
|
|
2211
|
+
const toolBudget = resolveNativeToolBudget(maxToolCalls);
|
|
2212
|
+
const toolLoopGuard = new ToolLoopGuard();
|
|
2210
2213
|
const usage = createUsageTotals();
|
|
2211
2214
|
// Shadow Tool Call Ledger (R1). Observes declare/defer/resolve; does not
|
|
2212
2215
|
// materialize Provider messages yet. STRICT via UFOO_UCODE_PROTOCOL_STRICT=1.
|
|
@@ -2226,6 +2229,7 @@ async function runNativeLoop({
|
|
|
2226
2229
|
function injectPendingUserReminders() {
|
|
2227
2230
|
const nudges = drainUserPrompts(executionState);
|
|
2228
2231
|
if (nudges.length === 0) return "";
|
|
2232
|
+
toolLoopGuard.reset();
|
|
2229
2233
|
const waiting = executionState.planGraph && executionState.planGraph.waitingFor
|
|
2230
2234
|
? executionState.planGraph.waitingFor
|
|
2231
2235
|
: null;
|
|
@@ -2236,6 +2240,7 @@ async function runNativeLoop({
|
|
|
2236
2240
|
function injectRuntimeMailboxEvents(targetMessages) {
|
|
2237
2241
|
const drained = drainAgentMailboxForTurn(executionState);
|
|
2238
2242
|
if (!drained.text) return false;
|
|
2243
|
+
toolLoopGuard.reset();
|
|
2239
2244
|
targetMessages.push({ role: "user", content: drained.text });
|
|
2240
2245
|
return true;
|
|
2241
2246
|
}
|
|
@@ -2267,6 +2272,7 @@ async function runNativeLoop({
|
|
|
2267
2272
|
}
|
|
2268
2273
|
const drained = drainAgentMailboxForTurn(executionState);
|
|
2269
2274
|
const userNudge = injectPendingUserReminders();
|
|
2275
|
+
if (drained.events && drained.events.length > 0) toolLoopGuard.reset();
|
|
2270
2276
|
const isolated = buildIsolatedTaskFocusTurn(executionState, {
|
|
2271
2277
|
mailboxEvents: drained.events || [],
|
|
2272
2278
|
userNudge,
|
|
@@ -2343,6 +2349,28 @@ async function runNativeLoop({
|
|
|
2343
2349
|
runProviderTurnGate(activeLedger);
|
|
2344
2350
|
}
|
|
2345
2351
|
|
|
2352
|
+
// Check only after the preceding batch has been fully materialized. A
|
|
2353
|
+
// warning must never split tool calls from their results, and a stop must
|
|
2354
|
+
// return the completed transcript instead of losing it through an exception.
|
|
2355
|
+
const loopAction = toolLoopGuard.nextAction();
|
|
2356
|
+
if (loopAction && loopAction.kind === "stop") {
|
|
2357
|
+
return {
|
|
2358
|
+
error: loopAction.message,
|
|
2359
|
+
stopReason: "repeated_tool_calls",
|
|
2360
|
+
text: aggregated,
|
|
2361
|
+
streamed,
|
|
2362
|
+
toolCallsExecuted,
|
|
2363
|
+
messages,
|
|
2364
|
+
turnItems: currentTurnItems(),
|
|
2365
|
+
usage,
|
|
2366
|
+
executionState,
|
|
2367
|
+
protocolLedger: lastProtocolLedger,
|
|
2368
|
+
};
|
|
2369
|
+
}
|
|
2370
|
+
if (loopAction && loopAction.kind === "warn") {
|
|
2371
|
+
providerMessages.push({ role: "user", content: loopAction.message });
|
|
2372
|
+
}
|
|
2373
|
+
|
|
2346
2374
|
const turnResult = await transport.runTurn({
|
|
2347
2375
|
url: requestUrl,
|
|
2348
2376
|
apiKey,
|
|
@@ -2368,6 +2396,12 @@ async function runNativeLoop({
|
|
|
2368
2396
|
},
|
|
2369
2397
|
});
|
|
2370
2398
|
|
|
2399
|
+
// Images belong to the request that just completed, not subsequent tool
|
|
2400
|
+
// iterations. Run only after success so failed requests retain their images.
|
|
2401
|
+
// TaskFocus may already have mirrored these blocks into the main transcript.
|
|
2402
|
+
retireMessageImages(providerMessages);
|
|
2403
|
+
if (providerMessages !== messages) retireMessageImages(messages);
|
|
2404
|
+
|
|
2371
2405
|
usage.turns += 1;
|
|
2372
2406
|
addUsageTotals(usage, turnResult && turnResult.usage);
|
|
2373
2407
|
emitContextUsage(turnResult && turnResult.usage);
|
|
@@ -2375,6 +2409,7 @@ async function runNativeLoop({
|
|
|
2375
2409
|
const toolCalls = transport.getToolCalls(turnResult);
|
|
2376
2410
|
|
|
2377
2411
|
if (toolCalls.length === 0) {
|
|
2412
|
+
toolLoopGuard.reset();
|
|
2378
2413
|
const text = String(turnResult.text || "").trim();
|
|
2379
2414
|
if (!text && toolCallsExecuted > 0) {
|
|
2380
2415
|
if (emptyTerminalRetries >= MAX_EMPTY_TERMINAL_RETRIES) {
|
|
@@ -2468,6 +2503,7 @@ async function runNativeLoop({
|
|
|
2468
2503
|
};
|
|
2469
2504
|
}
|
|
2470
2505
|
|
|
2506
|
+
toolLoopGuard.observe(pendingCalls);
|
|
2471
2507
|
activeLedger = createToolCallLedger({ provider, sessionId });
|
|
2472
2508
|
shadowDeclarePendingCalls(activeLedger, pendingCalls);
|
|
2473
2509
|
lastProtocolLedger = snapshotLedger(activeLedger);
|
|
@@ -2702,6 +2738,7 @@ async function runNativeAgentTask({
|
|
|
2702
2738
|
messages = [],
|
|
2703
2739
|
sessionId = "",
|
|
2704
2740
|
timeoutMs = DEFAULT_NATIVE_TIMEOUT_MS,
|
|
2741
|
+
maxToolCalls = undefined,
|
|
2705
2742
|
onStreamDelta = null,
|
|
2706
2743
|
onThinkingDelta = null,
|
|
2707
2744
|
onPhase = null,
|
|
@@ -2809,6 +2846,7 @@ async function runNativeAgentTask({
|
|
|
2809
2846
|
provider: runtime.provider,
|
|
2810
2847
|
accountId,
|
|
2811
2848
|
timeoutMs,
|
|
2849
|
+
maxToolCalls,
|
|
2812
2850
|
onStreamDelta: trackingStreamDelta,
|
|
2813
2851
|
onThinkingDelta,
|
|
2814
2852
|
onPhase,
|
|
@@ -2848,8 +2886,9 @@ async function runNativeAgentTask({
|
|
|
2848
2886
|
});
|
|
2849
2887
|
|
|
2850
2888
|
return {
|
|
2851
|
-
ok:
|
|
2852
|
-
error: "",
|
|
2889
|
+
ok: !runResult.error,
|
|
2890
|
+
error: runResult.error || "",
|
|
2891
|
+
stopReason: runResult.stopReason || "",
|
|
2853
2892
|
output: outputText,
|
|
2854
2893
|
messages: cloneMessageList(runResult.messages),
|
|
2855
2894
|
turnItems: cloneMessageList(runResult.turnItems),
|
|
@@ -99,6 +99,46 @@ function degradeVisionContent(content) {
|
|
|
99
99
|
return texts.filter(Boolean).join("\n") || "[multimodal content]";
|
|
100
100
|
}
|
|
101
101
|
|
|
102
|
+
// Retire only visual blocks after a successful model call. In particular,
|
|
103
|
+
// preserve Anthropic tool_result envelopes and their tool_use_id linkage.
|
|
104
|
+
function retireVisionContent(content) {
|
|
105
|
+
if (!Array.isArray(content)) return content;
|
|
106
|
+
let changed = false;
|
|
107
|
+
const retired = content.map((block) => {
|
|
108
|
+
if (!block || typeof block !== "object") return block;
|
|
109
|
+
const type = String(block.type || "").toLowerCase();
|
|
110
|
+
if (type === "image" || type === "image_url" || type === "input_image") {
|
|
111
|
+
changed = true;
|
|
112
|
+
const pathHint = block.path || (block.source && block.source.path) || "";
|
|
113
|
+
return {
|
|
114
|
+
type: "text",
|
|
115
|
+
text: pathHint
|
|
116
|
+
? `[image already viewed: ${pathHint}; use read_image to view again]`
|
|
117
|
+
: "[image already viewed; use read_image with the recorded path to view again]",
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
if (Array.isArray(block.content)) {
|
|
121
|
+
const nested = retireVisionContent(block.content);
|
|
122
|
+
if (nested !== block.content) {
|
|
123
|
+
changed = true;
|
|
124
|
+
return { ...block, content: nested };
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return block;
|
|
128
|
+
});
|
|
129
|
+
return changed ? retired : content;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function retireMessageImages(messages = []) {
|
|
133
|
+
for (let i = 0; i < messages.length; i += 1) {
|
|
134
|
+
const message = messages[i];
|
|
135
|
+
if (message && Array.isArray(message.content)) {
|
|
136
|
+
const content = retireVisionContent(message.content);
|
|
137
|
+
if (content !== message.content) messages[i] = { ...message, content };
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
102
142
|
module.exports = {
|
|
103
143
|
extractVisionPayload,
|
|
104
144
|
isVisionToolResult,
|
|
@@ -107,4 +147,5 @@ module.exports = {
|
|
|
107
147
|
toAnthropicImageBlock,
|
|
108
148
|
toOpenAiImagePart,
|
|
109
149
|
degradeVisionContent,
|
|
150
|
+
retireMessageImages,
|
|
110
151
|
};
|
package/src/code/repl.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
const readline = require("readline");
|
|
2
|
+
const { parseMaxToolCalls } = require("./toolBudget");
|
|
2
3
|
const { runToolCall, TOOL_NAMES } = require("./dispatch");
|
|
3
4
|
const {
|
|
4
5
|
runUcodeTui,
|
|
@@ -289,6 +290,7 @@ async function runUcodeCoreAgent({
|
|
|
289
290
|
systemPrompt = "",
|
|
290
291
|
sessionId = "",
|
|
291
292
|
timeoutMs = 0,
|
|
293
|
+
maxToolCalls = undefined,
|
|
292
294
|
jsonOutput = false,
|
|
293
295
|
forceTui = false,
|
|
294
296
|
disableTui = false,
|
|
@@ -346,6 +348,7 @@ async function runUcodeCoreAgent({
|
|
|
346
348
|
nlMessages: [],
|
|
347
349
|
sessionId: resolveSessionId(String(sessionId || "").trim()),
|
|
348
350
|
timeoutMs: resolveNlTaskTimeoutMs(Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : NaN),
|
|
351
|
+
maxToolCalls,
|
|
349
352
|
jsonOutput,
|
|
350
353
|
};
|
|
351
354
|
// Named levels sync into env; leave an explicit numeric budget override alone.
|
|
@@ -514,6 +517,7 @@ async function runUcodeCoreAgent({
|
|
|
514
517
|
nlMessages: Array.isArray(state.nlMessages) ? state.nlMessages.slice() : [],
|
|
515
518
|
sessionId: "",
|
|
516
519
|
timeoutMs: state.timeoutMs,
|
|
520
|
+
maxToolCalls: state.maxToolCalls,
|
|
517
521
|
jsonOutput: false,
|
|
518
522
|
};
|
|
519
523
|
const run = runNaturalLanguageTask(task, bgState)
|
|
@@ -824,6 +828,7 @@ function parseAgentArgs(argv = []) {
|
|
|
824
828
|
systemPrompt: "",
|
|
825
829
|
sessionId: "",
|
|
826
830
|
timeoutMs: 0,
|
|
831
|
+
maxToolCalls: undefined,
|
|
827
832
|
jsonOutput: false,
|
|
828
833
|
forceTui: false,
|
|
829
834
|
disableTui: false,
|
|
@@ -861,6 +866,12 @@ function parseAgentArgs(argv = []) {
|
|
|
861
866
|
i += 1;
|
|
862
867
|
continue;
|
|
863
868
|
}
|
|
869
|
+
if (item === "--max-tool-calls" || item.startsWith("--max-tool-calls=")) {
|
|
870
|
+
const value = item === "--max-tool-calls" ? args[++i] : item.slice("--max-tool-calls=".length);
|
|
871
|
+
if (value === undefined) throw new Error("--max-tool-calls requires a positive integer or none");
|
|
872
|
+
out.maxToolCalls = parseMaxToolCalls(value);
|
|
873
|
+
continue;
|
|
874
|
+
}
|
|
864
875
|
if (item === "--timeout-ms") {
|
|
865
876
|
const parsed = Number(args[i + 1]);
|
|
866
877
|
if (Number.isFinite(parsed)) out.timeoutMs = Math.max(1000, Math.floor(parsed));
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
function parseMaxToolCalls(value) {
|
|
4
|
+
if (value == null || String(value).trim().toLowerCase() === "none") return null;
|
|
5
|
+
const text = String(value).trim();
|
|
6
|
+
const count = Number(text);
|
|
7
|
+
if (!/^\d+$/.test(text) || !Number.isSafeInteger(count) || count <= 0) {
|
|
8
|
+
throw new Error("max tool calls must be a positive integer or none");
|
|
9
|
+
}
|
|
10
|
+
return count;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function resolveMaxToolCalls(value, env = process.env) {
|
|
14
|
+
if (value !== undefined) return parseMaxToolCalls(value);
|
|
15
|
+
const configured = env.UFOO_UCODE_MAX_TOOL_CALLS;
|
|
16
|
+
return configured == null || String(configured).trim() === ""
|
|
17
|
+
? null
|
|
18
|
+
: parseMaxToolCalls(configured);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
module.exports = { parseMaxToolCalls, resolveMaxToolCalls };
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const { createHash } = require("crypto");
|
|
4
|
+
const { stableStringify } = require("./context/stableJson");
|
|
5
|
+
|
|
6
|
+
const TIGHT_TOOLS = new Set(["read", "read_image", "artifact_read", "plan_graph"]);
|
|
7
|
+
|
|
8
|
+
// One observation is a model step, including its complete parallel tool batch.
|
|
9
|
+
// Ignore call IDs, JSON key order, and parallel ordering when comparing steps.
|
|
10
|
+
class ToolLoopGuard {
|
|
11
|
+
constructor() {
|
|
12
|
+
this.reset();
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
reset() {
|
|
16
|
+
this.signature = "";
|
|
17
|
+
this.count = 0;
|
|
18
|
+
this.warned = false;
|
|
19
|
+
this.names = [];
|
|
20
|
+
this.tight = false;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
observe(calls) {
|
|
24
|
+
if (!calls.length) return this.reset();
|
|
25
|
+
const parts = calls.map((call) => stableStringify({ name: call.name, args: call.args }));
|
|
26
|
+
const signature = createHash("sha256").update(JSON.stringify(parts.sort())).digest("hex");
|
|
27
|
+
if (signature !== this.signature) this.reset();
|
|
28
|
+
this.signature = signature;
|
|
29
|
+
this.count += 1;
|
|
30
|
+
this.names = [...new Set(calls.map((call) => call.name))].sort();
|
|
31
|
+
this.tight = calls.every((call) => TIGHT_TOOLS.has(call.name));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
nextAction() {
|
|
35
|
+
const warnAt = this.tight ? 4 : 8;
|
|
36
|
+
const stopAt = this.tight ? 8 : 12;
|
|
37
|
+
const tools = this.names.join(", ");
|
|
38
|
+
if (this.count >= stopAt) {
|
|
39
|
+
return {
|
|
40
|
+
kind: "stop",
|
|
41
|
+
message: `Stopped repeated tool calls: ${tools} used identical arguments for ${this.count} consecutive model steps after a warning. Change the approach or provide new information to continue.`,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
if (this.count >= warnAt && !this.warned) {
|
|
45
|
+
this.warned = true;
|
|
46
|
+
return {
|
|
47
|
+
kind: "warn",
|
|
48
|
+
message: `You have repeated the same tool batch (${tools}) with identical arguments for ${this.count} consecutive model steps. Stop repeating it and use a different approach. If waiting for a task, use its supported waiting mechanism instead of repeatedly checking. If blocked, explain the blocker to the user. This run will stop at ${stopAt} consecutive identical steps.`,
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
module.exports = { ToolLoopGuard };
|
|
@@ -610,11 +610,11 @@ class EventBus {
|
|
|
610
610
|
/**
|
|
611
611
|
* 智能路由
|
|
612
612
|
*/
|
|
613
|
-
async resolve(myId,
|
|
613
|
+
async resolve(myId, target) {
|
|
614
614
|
this.ensureBus();
|
|
615
615
|
this.loadBusData();
|
|
616
616
|
|
|
617
|
-
const result = await this.messageManager.resolve(myId,
|
|
617
|
+
const result = await this.messageManager.resolve(myId, target);
|
|
618
618
|
|
|
619
619
|
if (result.single) {
|
|
620
620
|
console.log(result.single);
|
|
@@ -622,11 +622,11 @@ class EventBus {
|
|
|
622
622
|
}
|
|
623
623
|
|
|
624
624
|
if (result.candidates.length === 0) {
|
|
625
|
-
logError(`No ${
|
|
625
|
+
logError(`No agents found for target "${target}"`);
|
|
626
626
|
return null;
|
|
627
627
|
}
|
|
628
628
|
|
|
629
|
-
console.log(`Multiple ${
|
|
629
|
+
console.log(`Multiple agents found for target "${target}":`);
|
|
630
630
|
for (const candidate of result.candidates) {
|
|
631
631
|
const nickname = candidate.nickname ? ` (${candidate.nickname})` : "";
|
|
632
632
|
console.log(` ${candidate.id}${nickname}`);
|
|
@@ -578,18 +578,12 @@ class MessageManager {
|
|
|
578
578
|
/**
|
|
579
579
|
* 智能路由解析(找出所有匹配的候选者)
|
|
580
580
|
*/
|
|
581
|
-
async resolve(myId,
|
|
582
|
-
const normalizedTargetType = normalizeAgentTypeAlias(targetType);
|
|
581
|
+
async resolve(myId, target) {
|
|
583
582
|
const subscribers = this.busData.agents || {};
|
|
584
|
-
const candidates =
|
|
585
|
-
.filter((
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
if (normalizeAgentTypeAlias(meta.agent_type) === normalizedTargetType) return true;
|
|
590
|
-
|
|
591
|
-
return false;
|
|
592
|
-
})
|
|
583
|
+
const candidates = this.resolveTarget(target)
|
|
584
|
+
.filter((id) => id !== myId)
|
|
585
|
+
.map((id) => [id, subscribers[id]])
|
|
586
|
+
.filter(([, meta]) => meta && meta.status === "active")
|
|
593
587
|
.map(([id, meta]) => {
|
|
594
588
|
const nickname = meta.nickname || meta.scoped_nickname;
|
|
595
589
|
return {
|
|
@@ -164,6 +164,14 @@ function notifyDaemonRefresh(projectRoot) {
|
|
|
164
164
|
}
|
|
165
165
|
}
|
|
166
166
|
|
|
167
|
+
function notifyDaemonRefreshIfEnabled(projectRoot, options = {}) {
|
|
168
|
+
if (options.notifyDaemon === false) return;
|
|
169
|
+
const notify = typeof options.notifyDaemonRefresh === "function"
|
|
170
|
+
? options.notifyDaemonRefresh
|
|
171
|
+
: notifyDaemonRefresh;
|
|
172
|
+
notify(projectRoot);
|
|
173
|
+
}
|
|
174
|
+
|
|
167
175
|
async function registerAgentFull(projectRoot, args = {}, options = {}) {
|
|
168
176
|
const {
|
|
169
177
|
validateParentPid = false,
|
|
@@ -319,7 +327,7 @@ async function registerAgentFull(projectRoot, args = {}, options = {}) {
|
|
|
319
327
|
}
|
|
320
328
|
}
|
|
321
329
|
bus.saveBusData();
|
|
322
|
-
|
|
330
|
+
notifyDaemonRefreshIfEnabled(projectRoot, options);
|
|
323
331
|
return {
|
|
324
332
|
ok: true,
|
|
325
333
|
project_root: projectRoot,
|
|
@@ -342,7 +350,7 @@ async function registerAgentFull(projectRoot, args = {}, options = {}) {
|
|
|
342
350
|
};
|
|
343
351
|
}
|
|
344
352
|
|
|
345
|
-
async function registerAgent(projectRoot, args = {}) {
|
|
353
|
+
async function registerAgent(projectRoot, args = {}, options = {}) {
|
|
346
354
|
if (!String(args.agent_type || args.agentType || "").trim()) {
|
|
347
355
|
const err = new Error("register_agent requires agent_type for canonical identity allocation");
|
|
348
356
|
err.code = "external_agent_type_required";
|
|
@@ -358,10 +366,12 @@ async function registerAgent(projectRoot, args = {}) {
|
|
|
358
366
|
return registerAgentFull(projectRoot, args, {
|
|
359
367
|
validateParentPid: false,
|
|
360
368
|
checkNicknameConflicts: false,
|
|
369
|
+
notifyDaemon: options.notifyDaemon,
|
|
370
|
+
notifyDaemonRefresh: options.notifyDaemonRefresh,
|
|
361
371
|
});
|
|
362
372
|
}
|
|
363
373
|
|
|
364
|
-
async function heartbeatAgent(projectRoot, args = {}) {
|
|
374
|
+
async function heartbeatAgent(projectRoot, args = {}, options = {}) {
|
|
365
375
|
const subscriber = resolveSubscriberArg(args);
|
|
366
376
|
const bus = ensureBusLoaded(projectRoot);
|
|
367
377
|
const meta = assertAgentHandle(bus, subscriber, args);
|
|
@@ -369,7 +379,7 @@ async function heartbeatAgent(projectRoot, args = {}) {
|
|
|
369
379
|
meta.status = "active";
|
|
370
380
|
const leaseExpiresAt = extendMcpAgentLease(meta);
|
|
371
381
|
bus.saveBusData();
|
|
372
|
-
|
|
382
|
+
notifyDaemonRefreshIfEnabled(projectRoot, options);
|
|
373
383
|
return {
|
|
374
384
|
ok: true,
|
|
375
385
|
project_root: projectRoot,
|
|
@@ -379,7 +389,7 @@ async function heartbeatAgent(projectRoot, args = {}) {
|
|
|
379
389
|
};
|
|
380
390
|
}
|
|
381
391
|
|
|
382
|
-
async function publishActivityState(projectRoot, args = {}) {
|
|
392
|
+
async function publishActivityState(projectRoot, args = {}, options = {}) {
|
|
383
393
|
const subscriber = resolveSubscriberArg(args);
|
|
384
394
|
const activityState = String(args.activity_state || args.activityState || "").trim();
|
|
385
395
|
if (!activityState) {
|
|
@@ -395,7 +405,7 @@ async function publishActivityState(projectRoot, args = {}) {
|
|
|
395
405
|
meta.activity_detail = String(args.detail || "").trim();
|
|
396
406
|
meta.activity_since = String(args.since || "").trim() || nowIso();
|
|
397
407
|
bus.saveBusData();
|
|
398
|
-
|
|
408
|
+
notifyDaemonRefreshIfEnabled(projectRoot, options);
|
|
399
409
|
return {
|
|
400
410
|
ok: true,
|
|
401
411
|
project_root: projectRoot,
|
|
@@ -406,7 +416,7 @@ async function publishActivityState(projectRoot, args = {}) {
|
|
|
406
416
|
};
|
|
407
417
|
}
|
|
408
418
|
|
|
409
|
-
async function updateAgentMetadata(projectRoot, args = {}) {
|
|
419
|
+
async function updateAgentMetadata(projectRoot, args = {}, options = {}) {
|
|
410
420
|
assertServerOwnedExternalIdentity(args, [
|
|
411
421
|
"nickname",
|
|
412
422
|
"scoped_nickname",
|
|
@@ -424,7 +434,7 @@ async function updateAgentMetadata(projectRoot, args = {}) {
|
|
|
424
434
|
}
|
|
425
435
|
bus.subscriberManager.updateLastSeen(subscriber);
|
|
426
436
|
bus.saveBusData();
|
|
427
|
-
|
|
437
|
+
notifyDaemonRefreshIfEnabled(projectRoot, options);
|
|
428
438
|
const nextMeta = bus.subscriberManager.getSubscriber(subscriber) || meta;
|
|
429
439
|
return {
|
|
430
440
|
ok: true,
|
|
@@ -655,7 +665,7 @@ async function reportAgentStatus(projectRoot, args = {}) {
|
|
|
655
665
|
};
|
|
656
666
|
}
|
|
657
667
|
|
|
658
|
-
async function unregisterAgent(projectRoot, args = {}) {
|
|
668
|
+
async function unregisterAgent(projectRoot, args = {}, options = {}) {
|
|
659
669
|
const subscriber = resolveSubscriberArg(args);
|
|
660
670
|
const bus = ensureBusLoaded(projectRoot);
|
|
661
671
|
const meta = assertAgentHandle(bus, subscriber, args, {
|
|
@@ -666,7 +676,7 @@ async function unregisterAgent(projectRoot, args = {}) {
|
|
|
666
676
|
meta.mcp_lease_expires_at = meta.mcp_revoked_at;
|
|
667
677
|
const ok = await bus.subscriberManager.leave(subscriber);
|
|
668
678
|
bus.saveBusData();
|
|
669
|
-
|
|
679
|
+
notifyDaemonRefreshIfEnabled(projectRoot, options);
|
|
670
680
|
return {
|
|
671
681
|
ok,
|
|
672
682
|
project_root: projectRoot,
|
|
@@ -684,6 +694,7 @@ module.exports = {
|
|
|
684
694
|
assertAgentHandle,
|
|
685
695
|
extendMcpAgentLease,
|
|
686
696
|
notifyDaemonRefresh,
|
|
697
|
+
notifyDaemonRefreshIfEnabled,
|
|
687
698
|
registerAgentFull,
|
|
688
699
|
registerAgent,
|
|
689
700
|
heartbeatAgent,
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
const { randomUUID } = require("crypto");
|
|
4
4
|
const fs = require("fs");
|
|
5
|
+
const path = require("path");
|
|
5
6
|
|
|
6
7
|
const {
|
|
7
8
|
defaultAgentModelForProvider,
|
|
@@ -15,9 +16,12 @@ const {
|
|
|
15
16
|
} = require("../../coordination/state/agentsStore");
|
|
16
17
|
const {
|
|
17
18
|
canonicalProjectRoot,
|
|
19
|
+
isGlobalControllerProjectRoot,
|
|
20
|
+
listProjectRuntimes,
|
|
18
21
|
markProjectStopped,
|
|
19
22
|
resolveGlobalControllerProjectRoot,
|
|
20
23
|
} = require("../projects");
|
|
24
|
+
const { isAgentPidAlive } = require("../../coordination/bus/utils");
|
|
21
25
|
const { startDaemon } = require("./index");
|
|
22
26
|
const { createProjectRuntime } = require("./projectRuntime");
|
|
23
27
|
const { ProjectRuntimeManager } = require("./projectRuntimeManager");
|
|
@@ -27,6 +31,51 @@ const {
|
|
|
27
31
|
executeProjectRuntimeOperation,
|
|
28
32
|
} = require("./projectRuntimeGateway");
|
|
29
33
|
|
|
34
|
+
const MAX_REHYDRATION_SKIP_SAMPLES = 25;
|
|
35
|
+
|
|
36
|
+
function isSocketFile(filePath = "") {
|
|
37
|
+
if (!filePath) return false;
|
|
38
|
+
try {
|
|
39
|
+
return fs.statSync(filePath).isSocket();
|
|
40
|
+
} catch {
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function hasPersistedCronTasks(projectRoot) {
|
|
46
|
+
const cronFile = path.join(getUfooPaths(projectRoot).runDir, "cron.tasks.json");
|
|
47
|
+
try {
|
|
48
|
+
const state = JSON.parse(fs.readFileSync(cronFile, "utf8"));
|
|
49
|
+
return Array.isArray(state.tasks) && state.tasks.length > 0;
|
|
50
|
+
} catch {
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function projectRuntimeRecoveryReasons(projectRoot, options = {}) {
|
|
56
|
+
const paths = getUfooPaths(projectRoot);
|
|
57
|
+
if (!fs.existsSync(paths.ufooDir)) return [];
|
|
58
|
+
const loadAgents = options.loadAgentsData || loadAgentsData;
|
|
59
|
+
const agentPidIsAlive = options.isAgentPidAlive || isAgentPidAlive;
|
|
60
|
+
const socketIsLive = options.isSocketFile || isSocketFile;
|
|
61
|
+
const reasons = [];
|
|
62
|
+
const data = fs.existsSync(paths.agentsFile)
|
|
63
|
+
? loadAgents(paths.agentsFile)
|
|
64
|
+
: { agents: {} };
|
|
65
|
+
const hasLiveHostAgent = Object.entries(data.agents || {}).some(([subscriber, meta]) => {
|
|
66
|
+
if (!meta || meta.status !== "active" || meta.mcp_bridge === true) return false;
|
|
67
|
+
if (subscriber === "ufoo-agent" || meta.agent_type === "ufoo-agent") return false;
|
|
68
|
+
const pid = Number.parseInt(meta.pid, 10);
|
|
69
|
+
return agentPidIsAlive(pid) || socketIsLive(meta.host_inject_sock);
|
|
70
|
+
});
|
|
71
|
+
if (hasLiveHostAgent) reasons.push("live_host_agent");
|
|
72
|
+
const hasCronTasks = typeof options.hasPersistedCronTasks === "function"
|
|
73
|
+
? options.hasPersistedCronTasks(projectRoot)
|
|
74
|
+
: hasPersistedCronTasks(projectRoot);
|
|
75
|
+
if (hasCronTasks) reasons.push("scheduled_task");
|
|
76
|
+
return reasons;
|
|
77
|
+
}
|
|
78
|
+
|
|
30
79
|
class GlobalDaemon {
|
|
31
80
|
constructor(options = {}) {
|
|
32
81
|
this.controllerRoot = canonicalProjectRoot(
|
|
@@ -38,6 +87,12 @@ class GlobalDaemon {
|
|
|
38
87
|
this.authorizeProjectRoot = typeof options.authorizeProjectRoot === "function"
|
|
39
88
|
? options.authorizeProjectRoot
|
|
40
89
|
: (projectRoot) => fs.existsSync(getUfooPaths(projectRoot).ufooDir);
|
|
90
|
+
this.listProjectRuntimes = options.listProjectRuntimes || listProjectRuntimes;
|
|
91
|
+
this.projectRuntimeRecoveryReasons = options.projectRuntimeRecoveryReasons
|
|
92
|
+
|| ((projectRoot) => projectRuntimeRecoveryReasons(projectRoot));
|
|
93
|
+
this.rehydrateProjects = options.rehydrateProjects === undefined
|
|
94
|
+
? isGlobalControllerProjectRoot(this.controllerRoot)
|
|
95
|
+
: options.rehydrateProjects === true;
|
|
41
96
|
this.controller = null;
|
|
42
97
|
this.runtimeManager = options.runtimeManager || new ProjectRuntimeManager({
|
|
43
98
|
authorizeProjectRoot: this.authorizeProjectRoot,
|
|
@@ -56,13 +111,24 @@ class GlobalDaemon {
|
|
|
56
111
|
const projectRoot = this.activeGatewayRequests.get(id);
|
|
57
112
|
return projectRoot ? this.runtimeManager.cancel(projectRoot, id) : false;
|
|
58
113
|
},
|
|
59
|
-
status: () =>
|
|
114
|
+
status: () => ({
|
|
115
|
+
...this.runtimeManager.status(),
|
|
116
|
+
rehydration: this.rehydration,
|
|
117
|
+
}),
|
|
60
118
|
// GlobalDaemon owns the shared manager; MCP listener restart/cleanup
|
|
61
119
|
// must not independently dispose project runtimes.
|
|
62
120
|
dispose: () => {},
|
|
63
121
|
};
|
|
64
122
|
this.disposed = false;
|
|
65
123
|
this.startedAt = "";
|
|
124
|
+
this.rehydration = {
|
|
125
|
+
state: this.rehydrateProjects ? "pending" : "disabled",
|
|
126
|
+
restored: [],
|
|
127
|
+
skipped: [],
|
|
128
|
+
skipped_count: 0,
|
|
129
|
+
failed: [],
|
|
130
|
+
};
|
|
131
|
+
this.rehydrationPromise = Promise.resolve(this.rehydration);
|
|
66
132
|
}
|
|
67
133
|
|
|
68
134
|
createHostedRuntime(context) {
|
|
@@ -175,6 +241,79 @@ class GlobalDaemon {
|
|
|
175
241
|
return runtime.hostHandle;
|
|
176
242
|
}
|
|
177
243
|
|
|
244
|
+
async restoreRegisteredProjectRuntimes() {
|
|
245
|
+
const startedAt = new Date().toISOString();
|
|
246
|
+
const restored = [];
|
|
247
|
+
const skipped = [];
|
|
248
|
+
let skippedCount = 0;
|
|
249
|
+
const failed = [];
|
|
250
|
+
const recordSkip = (entry) => {
|
|
251
|
+
skippedCount += 1;
|
|
252
|
+
if (skipped.length < MAX_REHYDRATION_SKIP_SAMPLES) skipped.push(entry);
|
|
253
|
+
};
|
|
254
|
+
this.rehydration = {
|
|
255
|
+
state: "running",
|
|
256
|
+
started_at: startedAt,
|
|
257
|
+
restored,
|
|
258
|
+
skipped,
|
|
259
|
+
skipped_count: skippedCount,
|
|
260
|
+
failed,
|
|
261
|
+
};
|
|
262
|
+
const rows = this.listProjectRuntimes({ validate: false, cleanupTmp: true });
|
|
263
|
+
const seen = new Set();
|
|
264
|
+
for (const row of rows) {
|
|
265
|
+
if (this.disposed) break;
|
|
266
|
+
const rawRoot = row && row.project_root;
|
|
267
|
+
if (!rawRoot) continue;
|
|
268
|
+
let projectRoot;
|
|
269
|
+
try {
|
|
270
|
+
projectRoot = canonicalProjectRoot(rawRoot);
|
|
271
|
+
} catch {
|
|
272
|
+
recordSkip({ project_root: String(rawRoot), reason: "missing_project_root" });
|
|
273
|
+
continue;
|
|
274
|
+
}
|
|
275
|
+
if (projectRoot === this.controllerRoot || seen.has(projectRoot)) continue;
|
|
276
|
+
seen.add(projectRoot);
|
|
277
|
+
let reasons;
|
|
278
|
+
try {
|
|
279
|
+
reasons = this.projectRuntimeRecoveryReasons(projectRoot);
|
|
280
|
+
} catch (err) {
|
|
281
|
+
failed.push({
|
|
282
|
+
project_root: projectRoot,
|
|
283
|
+
error: err && err.message ? err.message : String(err),
|
|
284
|
+
});
|
|
285
|
+
continue;
|
|
286
|
+
}
|
|
287
|
+
if (!Array.isArray(reasons) || reasons.length === 0) {
|
|
288
|
+
recordSkip({ project_root: projectRoot, reason: "no_live_runtime_owner" });
|
|
289
|
+
continue;
|
|
290
|
+
}
|
|
291
|
+
try {
|
|
292
|
+
// Preserve ordering and the manager's active-runtime bound rather than
|
|
293
|
+
// stampeding every registered project after a controller restart.
|
|
294
|
+
// eslint-disable-next-line no-await-in-loop
|
|
295
|
+
await this.activateProject(projectRoot);
|
|
296
|
+
restored.push({ project_root: projectRoot, reasons: reasons.slice() });
|
|
297
|
+
} catch (err) {
|
|
298
|
+
failed.push({
|
|
299
|
+
project_root: projectRoot,
|
|
300
|
+
reasons: reasons.slice(),
|
|
301
|
+
error: err && err.message ? err.message : String(err),
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
this.rehydration = {
|
|
306
|
+
state: failed.length > 0 ? "degraded" : "complete",
|
|
307
|
+
started_at: startedAt,
|
|
308
|
+
completed_at: new Date().toISOString(),
|
|
309
|
+
restored,
|
|
310
|
+
skipped,
|
|
311
|
+
skipped_count: skippedCount,
|
|
312
|
+
failed,
|
|
313
|
+
};
|
|
314
|
+
return this.rehydration;
|
|
315
|
+
}
|
|
316
|
+
|
|
178
317
|
async handleRequest(projectRoot, request, socket) {
|
|
179
318
|
const canonicalRoot = this.resolveProjectRoot(projectRoot);
|
|
180
319
|
const config = this.loadProjectConfig(canonicalRoot);
|
|
@@ -347,6 +486,23 @@ class GlobalDaemon {
|
|
|
347
486
|
beforeCleanup: () => this.disposeProjectRuntimes("global-controller-cleanup"),
|
|
348
487
|
});
|
|
349
488
|
this.startedAt = new Date().toISOString();
|
|
489
|
+
if (this.rehydrateProjects) {
|
|
490
|
+
this.rehydrationPromise = this.restoreRegisteredProjectRuntimes().catch((err) => {
|
|
491
|
+
this.rehydration = {
|
|
492
|
+
state: "failed",
|
|
493
|
+
started_at: this.rehydration.started_at || new Date().toISOString(),
|
|
494
|
+
completed_at: new Date().toISOString(),
|
|
495
|
+
restored: this.rehydration.restored || [],
|
|
496
|
+
skipped: this.rehydration.skipped || [],
|
|
497
|
+
skipped_count: this.rehydration.skipped_count || 0,
|
|
498
|
+
failed: [{
|
|
499
|
+
project_root: "",
|
|
500
|
+
error: err && err.message ? err.message : String(err),
|
|
501
|
+
}],
|
|
502
|
+
};
|
|
503
|
+
return this.rehydration;
|
|
504
|
+
});
|
|
505
|
+
}
|
|
350
506
|
return this;
|
|
351
507
|
}
|
|
352
508
|
|
|
@@ -378,6 +534,7 @@ class GlobalDaemon {
|
|
|
378
534
|
active_runtime_count: manager.active_runtime_count,
|
|
379
535
|
active_request_count: manager.active_request_count,
|
|
380
536
|
activating_runtime_count: this.runtimeManager.activationPromises.size,
|
|
537
|
+
rehydration: this.rehydration,
|
|
381
538
|
runtimes: manager.runtimes,
|
|
382
539
|
};
|
|
383
540
|
}
|
|
@@ -390,5 +547,7 @@ function startGlobalDaemon(options = {}) {
|
|
|
390
547
|
|
|
391
548
|
module.exports = {
|
|
392
549
|
GlobalDaemon,
|
|
550
|
+
hasPersistedCronTasks,
|
|
551
|
+
projectRuntimeRecoveryReasons,
|
|
393
552
|
startGlobalDaemon,
|
|
394
553
|
};
|
|
@@ -865,7 +865,15 @@ async function dispatchMessages(projectRoot, dispatch = []) {
|
|
|
865
865
|
}
|
|
866
866
|
}
|
|
867
867
|
|
|
868
|
-
function startBusBridge(
|
|
868
|
+
function startBusBridge(
|
|
869
|
+
projectRoot,
|
|
870
|
+
provider,
|
|
871
|
+
onEvent,
|
|
872
|
+
onStatus,
|
|
873
|
+
shouldDrain,
|
|
874
|
+
onReport,
|
|
875
|
+
options = {}
|
|
876
|
+
) {
|
|
869
877
|
const state = {
|
|
870
878
|
subscriber: null,
|
|
871
879
|
queueFile: null,
|
|
@@ -875,8 +883,13 @@ function startBusBridge(projectRoot, provider, onEvent, onStatus, shouldDrain, o
|
|
|
875
883
|
emittedEventKeys: [],
|
|
876
884
|
emittedEventKeySet: new Set(),
|
|
877
885
|
};
|
|
878
|
-
const eventBus = new EventBus(projectRoot);
|
|
879
|
-
|
|
886
|
+
const eventBus = options.eventBus || new EventBus(projectRoot);
|
|
887
|
+
const reportJoinError = typeof options.onJoinError === "function"
|
|
888
|
+
? options.onJoinError
|
|
889
|
+
: () => {};
|
|
890
|
+
let joinInProgress = null;
|
|
891
|
+
let lastJoinError = "";
|
|
892
|
+
let stopped = false;
|
|
880
893
|
let polling = false;
|
|
881
894
|
|
|
882
895
|
function getAgentNickname(agentId) {
|
|
@@ -1041,31 +1054,38 @@ function startBusBridge(projectRoot, provider, onEvent, onStatus, shouldDrain, o
|
|
|
1041
1054
|
state.lastEventSeq = Math.max(state.lastEventSeq, maxSeq);
|
|
1042
1055
|
}
|
|
1043
1056
|
|
|
1044
|
-
function ensureSubscriber() {
|
|
1045
|
-
if (state.subscriber
|
|
1046
|
-
|
|
1047
|
-
joinInProgress =
|
|
1048
|
-
(async () => {
|
|
1057
|
+
async function ensureSubscriber() {
|
|
1058
|
+
if (stopped || state.subscriber) return state.subscriber;
|
|
1059
|
+
if (joinInProgress) return joinInProgress;
|
|
1060
|
+
joinInProgress = (async () => {
|
|
1049
1061
|
try {
|
|
1050
|
-
fs.writeFileSync(debugFile, `Attempting join at ${new Date().toISOString()}\n`, { flag: "a" });
|
|
1051
1062
|
// Determine agent type based on provider configuration
|
|
1052
1063
|
const agentType = provider === "codex-cli" ? "codex" : (provider === "ucode" ? "ufoo-code" : "claude-code");
|
|
1053
1064
|
// Use fixed ID "ufoo-agent" for daemon's bus identity with explicit nickname
|
|
1054
1065
|
const sub = await eventBus.join("ufoo-agent", agentType, "ufoo-agent");
|
|
1055
|
-
if (!sub)
|
|
1056
|
-
fs.writeFileSync(debugFile, "Join returned empty subscriber\n", { flag: "a" });
|
|
1057
|
-
return;
|
|
1058
|
-
}
|
|
1066
|
+
if (!sub || stopped) return null;
|
|
1059
1067
|
state.subscriber = sub;
|
|
1060
1068
|
const safe = subscriberToSafeName(sub);
|
|
1061
1069
|
state.queueFile = path.join(getUfooPaths(projectRoot).busQueuesDir, safe, "pending.jsonl");
|
|
1062
|
-
|
|
1070
|
+
lastJoinError = "";
|
|
1071
|
+
return sub;
|
|
1063
1072
|
} catch (err) {
|
|
1064
|
-
|
|
1073
|
+
const detail = err && err.message ? err.message : String(err || "unknown join error");
|
|
1074
|
+
if (detail !== lastJoinError) {
|
|
1075
|
+
lastJoinError = detail;
|
|
1076
|
+
try {
|
|
1077
|
+
reportJoinError(err);
|
|
1078
|
+
} catch {
|
|
1079
|
+
// Diagnostics must never turn a recoverable join failure into an
|
|
1080
|
+
// unhandled rejection in the process-wide global daemon.
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
return null;
|
|
1065
1084
|
} finally {
|
|
1066
|
-
joinInProgress =
|
|
1085
|
+
joinInProgress = null;
|
|
1067
1086
|
}
|
|
1068
1087
|
})();
|
|
1088
|
+
return joinInProgress;
|
|
1069
1089
|
}
|
|
1070
1090
|
|
|
1071
1091
|
async function handleReportControlEvent(evt) {
|
|
@@ -1122,7 +1142,7 @@ function startBusBridge(projectRoot, provider, onEvent, onStatus, shouldDrain, o
|
|
|
1122
1142
|
if (polling) return;
|
|
1123
1143
|
polling = true;
|
|
1124
1144
|
try {
|
|
1125
|
-
ensureSubscriber();
|
|
1145
|
+
await ensureSubscriber();
|
|
1126
1146
|
await pollReportControlQueue();
|
|
1127
1147
|
if (typeof shouldDrain === "function" && !shouldDrain()) return;
|
|
1128
1148
|
pollQueue();
|
|
@@ -1145,13 +1165,12 @@ function startBusBridge(projectRoot, provider, onEvent, onStatus, shouldDrain, o
|
|
|
1145
1165
|
}
|
|
1146
1166
|
},
|
|
1147
1167
|
getSubscriber() {
|
|
1148
|
-
ensureSubscriber();
|
|
1149
|
-
try {
|
|
1150
|
-
fs.writeFileSync(path.join(getUfooPaths(projectRoot).runDir, "bridge-debug.txt"),
|
|
1151
|
-
`subscriber: ${state.subscriber || "NULL"}\nqueue: ${state.queueFile || "NULL"}\n`);
|
|
1152
|
-
} catch {}
|
|
1168
|
+
void ensureSubscriber();
|
|
1153
1169
|
return state.subscriber;
|
|
1154
1170
|
},
|
|
1171
|
+
refresh() {
|
|
1172
|
+
return poll();
|
|
1173
|
+
},
|
|
1155
1174
|
watchAgent(agentId, enabled = true) {
|
|
1156
1175
|
if (!agentId) return;
|
|
1157
1176
|
if (enabled) {
|
|
@@ -1165,6 +1184,7 @@ function startBusBridge(projectRoot, provider, onEvent, onStatus, shouldDrain, o
|
|
|
1165
1184
|
}
|
|
1166
1185
|
},
|
|
1167
1186
|
stop() {
|
|
1187
|
+
stopped = true;
|
|
1168
1188
|
clearInterval(interval);
|
|
1169
1189
|
},
|
|
1170
1190
|
};
|
|
@@ -1418,6 +1438,10 @@ function startDaemon({
|
|
|
1418
1438
|
} catch (err) {
|
|
1419
1439
|
log(`report bus event failed request=${meta.requestId || ""} error=${err.message || String(err)}`);
|
|
1420
1440
|
}
|
|
1441
|
+
}, {
|
|
1442
|
+
onJoinError: (err) => {
|
|
1443
|
+
log(`bus bridge join deferred: ${err && err.message ? err.message : String(err)}`);
|
|
1444
|
+
},
|
|
1421
1445
|
});
|
|
1422
1446
|
projectRuntime.own("busBridge", busBridge);
|
|
1423
1447
|
const deliveryScheduler = new DeliveryScheduler(projectRoot, {
|
|
@@ -2968,6 +2992,7 @@ function stopDaemon(projectRoot, options = {}) {
|
|
|
2968
2992
|
|
|
2969
2993
|
module.exports = {
|
|
2970
2994
|
startDaemon,
|
|
2995
|
+
startBusBridge,
|
|
2971
2996
|
stopDaemon,
|
|
2972
2997
|
isRunning,
|
|
2973
2998
|
cleanupStaleState,
|
|
@@ -36,7 +36,6 @@ const PACKAGE_ROOT = path.resolve(__dirname, "..", "..", "..");
|
|
|
36
36
|
const PACKAGE_JSON = require(path.join(PACKAGE_ROOT, "package.json"));
|
|
37
37
|
|
|
38
38
|
const EXPOSED_SHARED_TOOLS = MCP_EXPOSED_SHARED_TOOLS;
|
|
39
|
-
const DEFAULT_PROJECT_RUNTIME_GATEWAY = createLocalProjectRuntimeGateway();
|
|
40
39
|
|
|
41
40
|
const CUSTOM_TOOL_DEFINITIONS = Object.freeze([
|
|
42
41
|
{
|
|
@@ -552,15 +551,22 @@ async function invokeTool(name, args = {}, ctx = {}) {
|
|
|
552
551
|
|
|
553
552
|
class UfooMcpServer {
|
|
554
553
|
constructor(options = {}) {
|
|
554
|
+
const autoStart = options.autoStart !== false;
|
|
555
555
|
this.options = {
|
|
556
|
-
autoStart
|
|
556
|
+
autoStart,
|
|
557
557
|
validateProjectRoot: options.validateProjectRoot !== false,
|
|
558
558
|
startTimeoutMs: options.startTimeoutMs,
|
|
559
559
|
waitPollIntervalMs: options.waitPollIntervalMs,
|
|
560
560
|
waitHeartbeatIntervalMs: options.waitHeartbeatIntervalMs,
|
|
561
561
|
waitNow: options.waitNow,
|
|
562
562
|
waitSleep: options.waitSleep,
|
|
563
|
-
projectRuntimeGateway: options.projectRuntimeGateway ||
|
|
563
|
+
projectRuntimeGateway: options.projectRuntimeGateway || createLocalProjectRuntimeGateway({
|
|
564
|
+
// An explicitly embedded/no-autostart server (notably unit and
|
|
565
|
+
// integration harnesses) must never wake the user's live daemon for a
|
|
566
|
+
// temporary project. The production stdio bridge uses the global HTTP
|
|
567
|
+
// server and does not rely on this local gateway.
|
|
568
|
+
notifyDaemonRefresh: autoStart,
|
|
569
|
+
}),
|
|
564
570
|
};
|
|
565
571
|
this.initialized = false;
|
|
566
572
|
this.startup = null;
|
|
@@ -53,13 +53,20 @@ function unsupportedOperationError(operation = "") {
|
|
|
53
53
|
return err;
|
|
54
54
|
}
|
|
55
55
|
|
|
56
|
-
function createControlPlaneHandlers(service = null) {
|
|
56
|
+
function createControlPlaneHandlers(service = null, options = {}) {
|
|
57
57
|
const resolvedService = service || require("./controlPlaneService");
|
|
58
|
+
const notificationOptions = {
|
|
59
|
+
notifyDaemon: options.notifyDaemonRefresh !== false,
|
|
60
|
+
};
|
|
58
61
|
return {
|
|
59
|
-
register_agent: (projectRoot, args) =>
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
62
|
+
register_agent: (projectRoot, args) =>
|
|
63
|
+
resolvedService.registerAgent(projectRoot, args, notificationOptions),
|
|
64
|
+
heartbeat_agent: (projectRoot, args) =>
|
|
65
|
+
resolvedService.heartbeatAgent(projectRoot, args, notificationOptions),
|
|
66
|
+
publish_activity_state: (projectRoot, args) =>
|
|
67
|
+
resolvedService.publishActivityState(projectRoot, args, notificationOptions),
|
|
68
|
+
update_agent_metadata: (projectRoot, args) =>
|
|
69
|
+
resolvedService.updateAgentMetadata(projectRoot, args, notificationOptions),
|
|
63
70
|
poll_inbox: (projectRoot, args) => resolvedService.pollInbox(projectRoot, args),
|
|
64
71
|
wait_for_message: (projectRoot, args, context) => resolvedService.waitForMessage(projectRoot, args, {
|
|
65
72
|
signal: context.signal,
|
|
@@ -69,7 +76,8 @@ function createControlPlaneHandlers(service = null) {
|
|
|
69
76
|
sleep: context.waitSleep,
|
|
70
77
|
}),
|
|
71
78
|
report_agent_status: (projectRoot, args) => resolvedService.reportAgentStatus(projectRoot, args),
|
|
72
|
-
unregister_agent: (projectRoot, args) =>
|
|
79
|
+
unregister_agent: (projectRoot, args) =>
|
|
80
|
+
resolvedService.unregisterAgent(projectRoot, args, notificationOptions),
|
|
73
81
|
};
|
|
74
82
|
}
|
|
75
83
|
|
|
@@ -82,7 +90,7 @@ async function executeProjectRuntimeOperation(
|
|
|
82
90
|
) {
|
|
83
91
|
const name = String(operation || "").trim();
|
|
84
92
|
const handlers = options.controlPlaneHandlers
|
|
85
|
-
|| createControlPlaneHandlers(options.controlPlaneService);
|
|
93
|
+
|| createControlPlaneHandlers(options.controlPlaneService, options);
|
|
86
94
|
const customHandler = handlers[name];
|
|
87
95
|
if (customHandler) {
|
|
88
96
|
return customHandler(projectRoot, args, context);
|
|
@@ -126,7 +134,13 @@ function assertExternalAgentHandle(bus, subscriber, args = {}, options = {}) {
|
|
|
126
134
|
|
|
127
135
|
class LocalProjectRuntimeGateway {
|
|
128
136
|
constructor(options = {}) {
|
|
129
|
-
this.options =
|
|
137
|
+
this.options = {
|
|
138
|
+
// A local gateway is an in-process ownership boundary. It must not
|
|
139
|
+
// signal or activate a separate user daemon unless the caller opts in
|
|
140
|
+
// explicitly (the production global bridge uses a managed gateway).
|
|
141
|
+
notifyDaemonRefresh: false,
|
|
142
|
+
...options,
|
|
143
|
+
};
|
|
130
144
|
}
|
|
131
145
|
|
|
132
146
|
call(projectRoot, operation, args = {}, context = {}) {
|
package/src/ui/rustUcodeHost.js
CHANGED
|
@@ -1007,6 +1007,7 @@ async function runUcodeRust(props = {}) {
|
|
|
1007
1007
|
: [],
|
|
1008
1008
|
sessionId: "",
|
|
1009
1009
|
timeoutMs: props.state && props.state.timeoutMs,
|
|
1010
|
+
maxToolCalls: props.state ? props.state.maxToolCalls : undefined,
|
|
1010
1011
|
jsonOutput: false,
|
|
1011
1012
|
};
|
|
1012
1013
|
Promise.resolve()
|