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.
- package/OBSERVABILITY.md +65 -0
- package/README.md +238 -21
- package/README.zh-CN.md +165 -20
- package/SKILLS/ufoo/SKILL.md +40 -4
- package/SKILLS/ufoo-bus/SKILL.md +46 -3
- package/bin/uclaude.js +4 -0
- package/bin/ucodex.js +4 -0
- package/bin/ufoo.js +6 -4
- 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 +14 -7
- package/scripts/postinstall-skills.js +53 -0
- package/scripts/postinstall.js +11 -16
- package/scripts/smoke-native-messages.js +214 -0
- package/src/agents/activity/activityDetector.js +1 -1
- package/src/agents/activity/activityStateWriter.js +37 -38
- package/src/agents/capabilities/agentManagement/index.js +4 -0
- package/src/agents/capabilities/agentManagement/service.js +140 -0
- package/src/agents/capabilities/agentRouting/index.js +4 -0
- package/src/agents/capabilities/coding/index.js +32 -0
- package/src/agents/capabilities/coordination/index.js +37 -0
- package/src/agents/capabilities/globalRouting/index.js +5 -0
- package/src/agents/capabilities/groups/index.js +3 -0
- package/src/agents/capabilities/index.js +25 -0
- package/src/agents/capabilities/planning/index.js +123 -0
- package/src/agents/capabilities/planning/main.js +28 -0
- package/src/agents/capabilities/projectDiscovery/index.js +3 -0
- package/src/agents/capabilities/scheduling/index.js +3 -0
- package/src/agents/capabilities/sharedMemory/index.js +4 -0
- package/src/agents/capabilities/skills/index.js +12 -0
- package/src/agents/capabilities/taskExecution/index.js +3 -0
- package/src/agents/capabilities/taskReports/index.js +6 -0
- package/src/agents/controller/controllerToolExecutor.js +40 -22
- package/src/agents/controller/index.js +1 -6
- package/src/agents/internal/internalRunner.js +181 -76
- package/src/agents/launch/index.js +0 -1
- package/src/agents/launch/launcher.js +96 -14
- package/src/agents/launch/nativeCapabilities.js +40 -0
- package/src/agents/launch/nativeMessages.js +362 -0
- package/src/agents/launch/notifier.js +15 -20
- package/src/agents/launch/readyDetector.js +28 -14
- package/src/agents/profiles/coding.js +6 -0
- package/src/agents/profiles/globalRouter.js +2 -0
- package/src/agents/profiles/main.js +5 -0
- package/src/agents/prompts/cooperation.js +14 -0
- package/src/agents/prompts/defaultBootstrap.js +1 -1
- package/src/agents/prompts/groupBootstrap.js +32 -6
- package/src/agents/prompts/mainAgent.js +48 -0
- package/src/agents/prompts/native/system.js +4 -1
- package/src/agents/prompts/native/tasks.js +2 -2
- package/src/agents/prompts/native/ufoo.js +14 -3
- package/src/agents/prompts/promptProfiles.js +2 -0
- package/src/agents/prompts/reporting.js +16 -0
- package/src/agents/providers/claudeEventTranslator.js +9 -1
- package/src/agents/providers/claudeThreadProvider.js +47 -4
- package/src/agents/providers/clientIdentity.js +75 -0
- package/src/agents/providers/codexEventTranslator.js +68 -7
- package/src/agents/providers/codexThreadProvider.js +18 -8
- package/src/agents/providers/credentials/claude.js +10 -3
- package/src/agents/providers/credentials/index.js +2 -0
- package/src/agents/providers/directAuthStatus.js +1 -1
- package/src/agents/providers/index.js +1 -1
- package/src/agents/providers/modelSettings.js +34 -0
- package/src/agents/providers/modelsCatalog.js +379 -0
- package/src/agents/providers/nativeTransport.js +1146 -0
- package/src/agents/providers/runtimeConfig.js +188 -0
- package/src/agents/providers/thinkingLevels.js +106 -0
- package/src/agents/providers/transports/anthropicMessagesTransport.js +121 -0
- package/src/agents/providers/transports/index.js +10 -0
- package/src/agents/providers/transports/openaiChatTransport.js +117 -0
- package/src/agents/providers/transports/openaiResponsesTransport.js +120 -0
- package/src/agents/providers/transports/responsesProtocol.js +504 -0
- package/src/agents/providers/transports/systemBlocks.js +16 -0
- package/src/agents/providers/transports/transportContract.js +50 -0
- package/src/agents/providers/transports/visionBlocks.js +151 -0
- package/src/agents/providers/upstreamRuntime.js +135 -0
- package/src/agents/runtime/composeCapabilities.js +89 -0
- package/src/agents/runtime/context/checkpointStore.js +38 -0
- package/src/agents/runtime/context/commandStore.js +43 -0
- package/src/agents/runtime/context/compaction.js +151 -0
- package/src/agents/runtime/context/contextBudget.js +93 -0
- package/src/agents/runtime/context/contextWindow.js +119 -0
- package/src/agents/runtime/context/fileLock.js +36 -0
- package/src/agents/runtime/context/replayHistory.js +28 -0
- package/src/agents/runtime/context/runtimeStore.js +127 -0
- package/src/agents/runtime/context/sessionJournal.js +360 -0
- package/src/agents/runtime/context/sessionStore.js +57 -0
- package/src/agents/runtime/core/agentLoop.js +351 -0
- package/src/agents/runtime/core/executionBudget.js +36 -0
- package/src/agents/runtime/core/stableJson.js +29 -0
- package/src/agents/runtime/core/toolLoopGuard.js +55 -0
- package/src/agents/runtime/createAgentRuntime.js +259 -0
- package/src/agents/runtime/index.js +14 -0
- package/src/agents/runtime/prompts/responseLanguage.js +12 -0
- package/src/agents/runtime/protocol/faultHarness.js +90 -0
- package/src/agents/runtime/protocol/materialize.js +107 -0
- package/src/agents/runtime/protocol/runObservation.js +24 -0
- package/src/agents/runtime/protocol/toolCallLedger.js +221 -0
- package/src/agents/runtime/protocol/traceContext.js +9 -0
- package/src/agents/runtime/tasks/resourceLease.js +66 -0
- package/src/agents/runtime/tasks/scheduler.js +73 -0
- package/src/agents/runtime/tools/registry.js +57 -0
- package/src/app/chat/ChatController.js +29 -45
- package/src/app/chat/agentDirectory.js +9 -18
- package/src/app/chat/bootstrap.js +1 -2
- package/src/app/chat/commandExecutor.js +111 -313
- package/src/app/chat/commands.js +39 -45
- package/src/app/chat/daemonConnection.js +58 -5
- package/src/app/chat/daemonMessageRouter.js +61 -48
- package/src/app/chat/historyStore.js +12 -48
- package/src/app/chat/inputSubmitHandler.js +21 -35
- package/src/app/chat/internalAgentLogHistory.js +19 -60
- package/src/app/chat/launchRequestContext.js +42 -0
- package/src/app/chat/multiWindow/paneManager.js +91 -164
- package/src/app/chat/streamState.js +3 -7
- package/src/app/chat/transport.js +1 -1
- package/src/app/cli/busCoreCommands.js +9 -0
- package/src/app/cli/features/doctor.js +33 -0
- package/src/app/cli/features/init.js +5 -5
- package/src/app/cli/features/skills.js +16 -4
- package/src/app/cli/metricsCommands.js +68 -0
- package/src/app/cli/reportCoreCommands.js +37 -0
- package/src/app/cli/run.js +82 -42
- package/src/app/cli/traceCommands.js +36 -0
- package/src/code/agent.js +34 -17
- package/src/code/busConsumer.js +1 -3
- package/src/code/commands.js +1 -1
- package/src/code/context/artifacts.js +12 -11
- package/src/code/context/assembler.js +9 -9
- package/src/code/context/promptLayers.js +1 -13
- package/src/code/context/stableJson.js +2 -27
- package/src/code/context/stateCommit.js +2 -1
- package/src/code/contextWindow.js +2 -117
- package/src/code/conversation/sessionJournal.js +3 -349
- package/src/code/internalThread.js +107 -0
- package/src/code/launcher/ucode.js +1 -1
- package/src/code/launcher/ucodeBootstrap.js +1 -1
- package/src/code/modelCommand.js +11 -35
- package/src/code/nativeRunner.js +104 -2697
- package/src/code/protocol/faultHarness.js +2 -88
- package/src/code/protocol/materialize.js +2 -105
- package/src/code/protocol/toolCallLedger.js +5 -215
- package/src/code/providers/anthropicMessagesTransport.js +2 -118
- package/src/code/providers/modelsCatalog.js +1 -317
- package/src/code/providers/openaiChatTransport.js +2 -114
- package/src/code/providers/openaiResponsesTransport.js +2 -117
- package/src/code/providers/responsesProtocol.js +2 -497
- package/src/code/providers/transportContract.js +2 -48
- package/src/code/providers/visionBlocks.js +2 -149
- package/src/code/repl.js +2 -11
- package/src/code/sessionStore.js +27 -99
- package/src/code/taskDecomposer.js +18 -0
- package/src/code/thinkingLevels.js +1 -130
- package/src/code/toolBudget.js +1 -17
- package/src/code/toolLoopGuard.js +3 -49
- package/src/code/tools/artifactRead.js +1 -1
- package/src/code/tools/executor.js +373 -0
- package/src/code/tools/specs.js +312 -0
- package/src/config.js +95 -131
- package/src/coordination/bus/deliveryQueue.js +16 -2
- package/src/coordination/bus/index.js +14 -9
- package/src/coordination/bus/inject.js +15 -7
- package/src/coordination/bus/message.js +15 -1
- package/src/coordination/bus/nativeReceipts.js +100 -0
- package/src/coordination/bus/nickname.js +1 -1
- package/src/coordination/bus/queue.js +1 -3
- package/src/coordination/bus/subscriber.js +3 -2
- package/src/coordination/bus/utils.js +8 -4
- package/src/coordination/history/agentPerformance.js +279 -0
- package/src/coordination/history/agentSurface.js +142 -0
- package/src/coordination/history/agentTrace.js +249 -0
- package/src/coordination/memory/index.js +5 -21
- package/src/coordination/report/store.js +103 -83
- package/src/coordination/state/agentsStore.js +57 -3
- package/src/coordination/state/fileLock.js +2 -0
- package/src/coordination/state/workspaceAccess.js +36 -0
- package/src/orchestration/controller/index.js +1 -8
- package/src/orchestration/controller/launchRouting.js +1 -1
- package/src/orchestration/solo/commands.js +3 -1
- package/src/runtime/contracts/agentMode.js +26 -0
- package/src/runtime/contracts/eventContract.js +3 -0
- package/src/runtime/contracts/uiProtocol.js +20 -17
- package/src/runtime/daemon/agentHost.js +407 -0
- package/src/runtime/daemon/agentRecoveryGroups.js +70 -0
- package/src/runtime/daemon/busBridge.js +396 -0
- package/src/runtime/daemon/claudeChannel.js +159 -0
- package/src/runtime/daemon/controlPlaneService.js +28 -18
- package/src/runtime/daemon/cronOps.js +25 -17
- package/src/runtime/daemon/deliveryScheduler.js +32 -5
- package/src/runtime/daemon/globalDaemon.js +28 -1
- package/src/runtime/daemon/groupOrchestrator.js +21 -5
- package/src/runtime/daemon/groupStatus.js +20 -0
- package/src/runtime/daemon/index.js +120 -375
- package/src/runtime/daemon/ipcServer.js +32 -10
- package/src/runtime/daemon/mcpConfigure.js +113 -20
- package/src/runtime/daemon/mcpHttpServer.js +27 -5
- package/src/runtime/daemon/mcpServer.js +8 -5
- package/src/runtime/daemon/mcpStdioProxy.js +127 -10
- package/src/runtime/daemon/nicknameScope.js +1 -1
- package/src/runtime/daemon/ops.js +68 -40
- package/src/runtime/daemon/projectRuntimeGateway.js +2 -0
- package/src/runtime/daemon/promptRequest.js +92 -570
- package/src/runtime/daemon/providerSessions.js +67 -33
- package/src/runtime/daemon/reportControlBus.js +59 -25
- package/src/runtime/daemon/status.js +9 -6
- package/src/runtime/privacy/redactor.js +2 -2
- package/src/runtime/projects/identity.js +2 -1
- package/src/runtime/projects/registry.js +98 -38
- package/src/tools/controllerSchemas.js +28 -0
- package/src/tools/handlers/dispatchMessage.js +5 -2
- package/src/tools/handlers/listAgents.js +3 -1
- package/src/tools/handlers/readBusSummary.js +3 -1
- package/src/tools/handlers/readProjectRegistry.js +29 -2
- package/src/tools/handlers/routeAgent.js +35 -0
- package/src/tools/handlers/tier2.js +4 -2
- package/src/tools/index.js +1 -0
- package/src/tools/registry.js +6 -0
- package/src/tools/schemaFixtures.js +42 -5
- package/src/tools/tier0/readAgentMetrics.js +14 -0
- package/src/tools/tier0/readAgentTrace.js +12 -0
- package/src/tools/tier1/routeAgent.js +2 -2
- package/src/tools/tier2/runtimeCoordination.js +38 -0
- package/src/tools/types.js +2 -0
- package/src/ui/agentPresentation.js +109 -0
- package/src/ui/agentSettingsController.js +107 -0
- package/src/ui/agentSurface.js +270 -0
- package/src/ui/dashboardBridge.js +1 -1
- package/src/ui/format/banner.js +9 -15
- package/src/ui/format/index.js +14 -10
- package/src/ui/format/loopSummary.js +50 -0
- package/src/ui/format/markdownRenderer.js +3 -4
- package/src/ui/format/startupBanner.js +50 -0
- package/src/ui/multiPaneBusMirror.js +29 -3
- package/src/ui/rustChatHost.js +316 -599
- package/src/ui/rustMultiSession.js +288 -73
- package/src/ui/rustUcodeHost.js +21 -88
- package/src/ui/settingsBridge.js +34 -14
- package/src/ui/toolMergeBridge.js +0 -4
- package/src/ui/uiHostServer.js +5 -8
- package/src/agents/controller/loopObservability.js +0 -200
- package/src/agents/controller/loopRuntime.js +0 -472
- package/src/agents/controller/ufooAgent.js +0 -829
- package/src/agents/launch/ptyRunner.js +0 -1135
- package/src/agents/providers/upstreamTransport.js +0 -689
- package/src/app/chat/agentBar.js +0 -135
- package/src/app/chat/agentEnter.js +0 -70
- package/src/app/chat/agentSockets.js +0 -225
- package/src/app/chat/dashboardView.js +0 -405
- package/src/app/chat/multiWindow/index.js +0 -310
- package/src/app/chat/multiWindow/paneLayout.js +0 -84
- package/src/app/chat/multiWindow/renderer.js +0 -420
- package/src/app/chat/multiWindow/virtualTerminal.js +0 -327
- package/src/app/chat/multiWindow/vtFrame.js +0 -93
- package/src/app/chat/rawKeyMap.js +0 -42
- package/src/app/chat/settingsController.js +0 -111
- package/src/orchestration/controller/flags.js +0 -167
- package/src/orchestration/controller/gateRouter.js +0 -211
- package/src/orchestration/controller/routerFastPath.js +0 -22
- package/src/orchestration/controller/routerFinalize.js +0 -222
- package/src/orchestration/controller/shadowGuard.js +0 -280
- package/src/runtime/daemon/promptLoop.js +0 -136
- package/src/runtime/privacy/shadowDiff.js +0 -174
- package/src/ui/multiWindowHandoff.js +0 -232
- package/src/ui/ptyHandoff.js +0 -23
|
@@ -15,6 +15,27 @@ function createDaemonIpcServer(options = {}) {
|
|
|
15
15
|
} = options;
|
|
16
16
|
|
|
17
17
|
const sockets = new Set();
|
|
18
|
+
const socketListeners = new Map();
|
|
19
|
+
function detachSocket(socket) {
|
|
20
|
+
sockets.delete(socket);
|
|
21
|
+
const listeners = socketListeners.get(socket);
|
|
22
|
+
if (listeners) {
|
|
23
|
+
socket.removeListener("close", listeners.close);
|
|
24
|
+
socket.removeListener("error", listeners.error);
|
|
25
|
+
socketListeners.delete(socket);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
function attachSocket(socket) {
|
|
29
|
+
if (!socket || socket.destroyed || typeof socket.on !== "function" || socketListeners.has(socket)) return;
|
|
30
|
+
const listeners = {
|
|
31
|
+
close: () => detachSocket(socket),
|
|
32
|
+
error: (err) => log(`ipc socket error: ${err && err.message ? err.message : String(err || "unknown error")}`),
|
|
33
|
+
};
|
|
34
|
+
sockets.add(socket);
|
|
35
|
+
socketListeners.set(socket, listeners);
|
|
36
|
+
socket.on("close", listeners.close);
|
|
37
|
+
socket.on("error", listeners.error);
|
|
38
|
+
}
|
|
18
39
|
const sendToSockets = (payload) => {
|
|
19
40
|
const line = `${JSON.stringify(payload)}\n`;
|
|
20
41
|
for (const sock of sockets) {
|
|
@@ -54,13 +75,9 @@ function createDaemonIpcServer(options = {}) {
|
|
|
54
75
|
}, statusIntervalMs);
|
|
55
76
|
|
|
56
77
|
const server = net.createServer((socket) => {
|
|
57
|
-
|
|
58
|
-
socket.on("close", () => sockets.delete(socket));
|
|
59
|
-
socket.on("error", (err) => {
|
|
60
|
-
log(`ipc socket error: ${err && err.message ? err.message : String(err || "unknown error")}`);
|
|
61
|
-
});
|
|
78
|
+
attachSocket(socket);
|
|
62
79
|
let buffer = "";
|
|
63
|
-
socket.on("data",
|
|
80
|
+
socket.on("data", (data) => {
|
|
64
81
|
buffer += data.toString("utf8");
|
|
65
82
|
const lines = buffer.split(/\r?\n/);
|
|
66
83
|
buffer = lines.pop() || "";
|
|
@@ -69,9 +86,7 @@ function createDaemonIpcServer(options = {}) {
|
|
|
69
86
|
const items = parseJsonLines(line);
|
|
70
87
|
for (const req of items) {
|
|
71
88
|
if (!req || typeof req !== "object") continue;
|
|
72
|
-
|
|
73
|
-
await handleRequest(req, socket);
|
|
74
|
-
} catch (err) {
|
|
89
|
+
Promise.resolve().then(() => handleRequest(req, socket)).catch((err) => {
|
|
75
90
|
const message = err && err.message ? err.message : String(err || "request failed");
|
|
76
91
|
const requestType = String(req.type || "unknown");
|
|
77
92
|
log(`ipc request failed type=${requestType}: ${err && err.stack ? err.stack : message}`);
|
|
@@ -84,7 +99,7 @@ function createDaemonIpcServer(options = {}) {
|
|
|
84
99
|
} catch {
|
|
85
100
|
// ignore failed error replies
|
|
86
101
|
}
|
|
87
|
-
}
|
|
102
|
+
});
|
|
88
103
|
}
|
|
89
104
|
}
|
|
90
105
|
});
|
|
@@ -100,6 +115,11 @@ function createDaemonIpcServer(options = {}) {
|
|
|
100
115
|
|
|
101
116
|
function stop() {
|
|
102
117
|
clearInterval(statusSyncInterval);
|
|
118
|
+
for (const socket of [...sockets]) {
|
|
119
|
+
socket.destroy?.();
|
|
120
|
+
detachSocket(socket);
|
|
121
|
+
}
|
|
122
|
+
sockets.clear();
|
|
103
123
|
try {
|
|
104
124
|
server.close();
|
|
105
125
|
} catch {
|
|
@@ -114,6 +134,8 @@ function createDaemonIpcServer(options = {}) {
|
|
|
114
134
|
return {
|
|
115
135
|
server,
|
|
116
136
|
sockets,
|
|
137
|
+
attachSocket,
|
|
138
|
+
detachSocket,
|
|
117
139
|
sendToSockets,
|
|
118
140
|
listen,
|
|
119
141
|
stop,
|
|
@@ -37,23 +37,32 @@ function codexConfigPath(options = {}) {
|
|
|
37
37
|
return path.join(codexHome || path.join(os.homedir(), ".codex"), "config.toml");
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
-
function buildCodexManagedBlock(connection) {
|
|
40
|
+
function buildCodexManagedBlock(connection, authentication = {}) {
|
|
41
41
|
const authorization = tomlString(`Bearer ${connection.token}`);
|
|
42
|
+
const authLines = (name) => authentication[name]?.lines
|
|
43
|
+
|| [`http_headers = { Authorization = ${authorization} }`];
|
|
44
|
+
const authTables = (name) => (authentication[name]?.tables || []).flatMap((table) => [
|
|
45
|
+
"",
|
|
46
|
+
`[mcp_servers.${name}.${table.suffix}]`,
|
|
47
|
+
table.body,
|
|
48
|
+
]);
|
|
42
49
|
return [
|
|
43
50
|
MANAGED_BLOCK_START,
|
|
44
51
|
"[mcp_servers.ufoo]",
|
|
45
52
|
`url = ${tomlString(connection.endpoint)}`,
|
|
46
|
-
|
|
53
|
+
...authLines("ufoo"),
|
|
47
54
|
`tool_timeout_sec = ${CODEX_STANDARD_TOOL_TIMEOUT_SECONDS}`,
|
|
48
55
|
'disabled_tools = ["wait_for_message"]',
|
|
49
56
|
"enabled = true",
|
|
57
|
+
...authTables("ufoo"),
|
|
50
58
|
"",
|
|
51
59
|
"[mcp_servers.ufoo_wait]",
|
|
52
60
|
`url = ${tomlString(connection.endpoint)}`,
|
|
53
|
-
|
|
61
|
+
...authLines("ufoo_wait"),
|
|
54
62
|
`tool_timeout_sec = ${CODEX_WAIT_TOOL_TIMEOUT_SECONDS}`,
|
|
55
63
|
'enabled_tools = ["wait_for_message"]',
|
|
56
64
|
"enabled = true",
|
|
65
|
+
...authTables("ufoo_wait"),
|
|
57
66
|
"",
|
|
58
67
|
"[mcp_servers.ufoo_wait.tools.wait_for_message]",
|
|
59
68
|
'approval_mode = "approve"',
|
|
@@ -70,15 +79,51 @@ function removeManagedBlock(text = "") {
|
|
|
70
79
|
);
|
|
71
80
|
}
|
|
72
81
|
|
|
82
|
+
// Split only outside strings, comments, arrays and inline tables. A table-like
|
|
83
|
+
// line inside a multiline value is data, not a configuration section boundary.
|
|
84
|
+
function tomlStatements(text = "") {
|
|
85
|
+
const statements = [];
|
|
86
|
+
let start = 0;
|
|
87
|
+
let quote = "";
|
|
88
|
+
let comment = false;
|
|
89
|
+
let depth = 0;
|
|
90
|
+
for (let index = 0; index < text.length; index += 1) {
|
|
91
|
+
const char = text[index];
|
|
92
|
+
if (quote) {
|
|
93
|
+
if (quote[0] === '"' && char === "\\") { index += 1; continue; }
|
|
94
|
+
if (text.startsWith(quote, index)) { index += quote.length - 1; quote = ""; }
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
if (!comment) {
|
|
98
|
+
if (char === "#") comment = true;
|
|
99
|
+
else if (char === '"' || char === "'") {
|
|
100
|
+
quote = text.startsWith(char.repeat(3), index) ? char.repeat(3) : char;
|
|
101
|
+
index += quote.length - 1;
|
|
102
|
+
} else if (char === "[" || char === "{") depth += 1;
|
|
103
|
+
else if (char === "]" || char === "}") depth -= 1;
|
|
104
|
+
}
|
|
105
|
+
if (char === "\n") {
|
|
106
|
+
comment = false;
|
|
107
|
+
if (!quote && depth === 0) {
|
|
108
|
+
statements.push({ start, end: index + 1, text: text.slice(start, index + 1) });
|
|
109
|
+
start = index + 1;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
if (start < text.length) statements.push({ start, end: text.length, text: text.slice(start) });
|
|
114
|
+
return statements;
|
|
115
|
+
}
|
|
116
|
+
|
|
73
117
|
function findTomlSections(text = "") {
|
|
74
118
|
const sections = [];
|
|
75
|
-
const
|
|
76
|
-
|
|
77
|
-
|
|
119
|
+
for (const statement of tomlStatements(text)) {
|
|
120
|
+
const match = statement.text.match(/^[ \t]*(\[\[?)([^\r\n]+?)(\]\]?)[ \t]*(?:#.*)?\r?\n?$/);
|
|
121
|
+
if (!match || match[1].length !== match[3].length) continue;
|
|
78
122
|
sections.push({
|
|
79
|
-
header: match[
|
|
80
|
-
|
|
81
|
-
|
|
123
|
+
header: match[2].trim(),
|
|
124
|
+
array: match[1].length === 2,
|
|
125
|
+
start: statement.start,
|
|
126
|
+
contentStart: statement.end,
|
|
82
127
|
});
|
|
83
128
|
}
|
|
84
129
|
return sections.map((section, index) => ({
|
|
@@ -87,6 +132,27 @@ function findTomlSections(text = "") {
|
|
|
87
132
|
}));
|
|
88
133
|
}
|
|
89
134
|
|
|
135
|
+
function collectCodexAuthentication(text, name) {
|
|
136
|
+
const prefix = `(?:mcp_servers\\.${name}|mcp_servers\\."${name}")`;
|
|
137
|
+
const mainPattern = new RegExp(`^${prefix}$`);
|
|
138
|
+
const tablePattern = new RegExp(`^${prefix}\\.((?:http_headers|env_http_headers|oauth)(?:\\..*)?)$`);
|
|
139
|
+
const keyPattern = /^[ \t]*(?:"(http_headers|env_http_headers|http_headers_helper|bearer_token_env_var|auth)"|'(http_headers|env_http_headers|http_headers_helper|bearer_token_env_var|auth)'|(http_headers|env_http_headers|http_headers_helper|bearer_token_env_var|auth))[ \t]*=/;
|
|
140
|
+
const lines = [];
|
|
141
|
+
const tables = [];
|
|
142
|
+
for (const section of findTomlSections(text)) {
|
|
143
|
+
if (section.array) continue;
|
|
144
|
+
const body = text.slice(section.contentStart, section.end);
|
|
145
|
+
if (mainPattern.test(section.header)) {
|
|
146
|
+
for (const statement of tomlStatements(body)) {
|
|
147
|
+
if (keyPattern.test(statement.text)) lines.push(statement.text.trimEnd());
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
const match = section.header.match(tablePattern);
|
|
151
|
+
if (match) tables.push({ suffix: match[1], body: body.trimEnd() });
|
|
152
|
+
}
|
|
153
|
+
return lines.length || tables.length ? { lines, tables } : null;
|
|
154
|
+
}
|
|
155
|
+
|
|
90
156
|
function isUfooMainSection(header = "") {
|
|
91
157
|
return /^(?:mcp_servers\.ufoo|mcp_servers\."ufoo")$/.test(String(header || ""));
|
|
92
158
|
}
|
|
@@ -101,6 +167,8 @@ function removeLegacyUfooTransportSections(text = "") {
|
|
|
101
167
|
.filter((section) => (
|
|
102
168
|
isUfooMainSection(section.header)
|
|
103
169
|
|| isUfooStdioEnvSection(section.header)
|
|
170
|
+
|| /^(?:mcp_servers\.ufoo|mcp_servers\."ufoo")\.(?:http_headers|env_http_headers|oauth)(?:\.|$)/
|
|
171
|
+
.test(section.header)
|
|
104
172
|
|| /^(?:mcp_servers\.ufoo_wait|mcp_servers\."ufoo_wait")(?:\.|$)/
|
|
105
173
|
.test(String(section.header || ""))
|
|
106
174
|
))
|
|
@@ -115,18 +183,10 @@ function removeLegacyUfooTransportSections(text = "") {
|
|
|
115
183
|
|
|
116
184
|
function removeRetiredUfooSkillConfigBlocks(text = "") {
|
|
117
185
|
const source = String(text || "");
|
|
118
|
-
const tables =
|
|
119
|
-
const tablePattern = /^\s*(\[{1,2}[^\]\r\n]+\]{1,2})\s*(?:#.*)?$/gm;
|
|
120
|
-
let match;
|
|
121
|
-
while ((match = tablePattern.exec(source)) !== null) {
|
|
122
|
-
tables.push({
|
|
123
|
-
header: match[1],
|
|
124
|
-
start: match.index,
|
|
125
|
-
});
|
|
126
|
-
}
|
|
186
|
+
const tables = findTomlSections(source);
|
|
127
187
|
const ranges = [];
|
|
128
188
|
for (let index = 0; index < tables.length; index += 1) {
|
|
129
|
-
if (tables[index].header !== "
|
|
189
|
+
if (!tables[index].array || tables[index].header !== "skills.config") continue;
|
|
130
190
|
const start = tables[index].start;
|
|
131
191
|
const end = index + 1 < tables.length ? tables[index + 1].start : source.length;
|
|
132
192
|
const block = source.slice(start, end);
|
|
@@ -148,11 +208,19 @@ function removeRetiredUfooSkillConfigBlocks(text = "") {
|
|
|
148
208
|
}
|
|
149
209
|
|
|
150
210
|
function renderCodexConfig(existing, connection) {
|
|
211
|
+
// Authentication belongs to the existing server configuration. Preserve it
|
|
212
|
+
// instead of redefining a nested header table as an inline value or replacing
|
|
213
|
+
// a host-managed credential source with the daemon's current token.
|
|
214
|
+
const ufoo = collectCodexAuthentication(existing, "ufoo");
|
|
215
|
+
const ufooWait = collectCodexAuthentication(existing, "ufoo_wait") || ufoo;
|
|
151
216
|
const withoutManaged = removeManagedBlock(existing);
|
|
152
217
|
const withoutLegacy = removeLegacyUfooTransportSections(withoutManaged);
|
|
153
218
|
const withoutRetiredSkills = removeRetiredUfooSkillConfigBlocks(withoutLegacy);
|
|
154
219
|
const trimmed = withoutRetiredSkills.trimEnd();
|
|
155
|
-
return `${trimmed ? `${trimmed}\n\n` : ""}${buildCodexManagedBlock(connection
|
|
220
|
+
return `${trimmed ? `${trimmed}\n\n` : ""}${buildCodexManagedBlock(connection, {
|
|
221
|
+
...(ufoo ? { ufoo } : {}),
|
|
222
|
+
...(ufooWait ? { ufoo_wait: ufooWait } : {}),
|
|
223
|
+
})}\n`;
|
|
156
224
|
}
|
|
157
225
|
|
|
158
226
|
function configureCodexMcp(options = {}) {
|
|
@@ -162,9 +230,23 @@ function configureCodexMcp(options = {}) {
|
|
|
162
230
|
const existing = fs.existsSync(target) ? fs.readFileSync(target, "utf8") : "";
|
|
163
231
|
const next = renderCodexConfig(existing, connection);
|
|
164
232
|
if (options.dryRun === true) {
|
|
233
|
+
const ufoo = collectCodexAuthentication(existing, "ufoo");
|
|
234
|
+
const ufooWait = collectCodexAuthentication(existing, "ufoo_wait") || ufoo;
|
|
235
|
+
const redactAuth = (auth) => ({
|
|
236
|
+
lines: auth.lines.map((statement) => {
|
|
237
|
+
const key = statement.slice(0, statement.indexOf("=")).trim();
|
|
238
|
+
const value = /^(?:["']?)(?:http_headers|env_http_headers)["']?$/.test(key)
|
|
239
|
+
? '{ "<redacted>" = "<redacted>" }' : '"<redacted>"';
|
|
240
|
+
return `${key} = ${value}`;
|
|
241
|
+
}),
|
|
242
|
+
tables: auth.tables.map((table) => ({ ...table, body: "# Existing authentication retained; values redacted." })),
|
|
243
|
+
});
|
|
165
244
|
const managedBlock = buildCodexManagedBlock({
|
|
166
245
|
...connection,
|
|
167
246
|
token: "<redacted>",
|
|
247
|
+
}, {
|
|
248
|
+
...(ufoo ? { ufoo: redactAuth(ufoo) } : {}),
|
|
249
|
+
...(ufooWait ? { ufoo_wait: redactAuth(ufooWait) } : {}),
|
|
168
250
|
});
|
|
169
251
|
return {
|
|
170
252
|
ok: true,
|
|
@@ -205,6 +287,16 @@ function configureCodexMcp(options = {}) {
|
|
|
205
287
|
};
|
|
206
288
|
}
|
|
207
289
|
|
|
290
|
+
function inspectCodexMcpConfig(options = {}) {
|
|
291
|
+
const target = codexConfigPath(options);
|
|
292
|
+
if (!fs.existsSync(target)) return { configured: false, changed: false, target };
|
|
293
|
+
const existing = fs.readFileSync(target, "utf8");
|
|
294
|
+
const configured = findTomlSections(existing).some((section) => isUfooMainSection(section.header));
|
|
295
|
+
if (!configured) return { configured: false, changed: false, target };
|
|
296
|
+
const connection = options.connection || readConnectionFiles(options.projectRoot || resolveGlobalControllerProjectRoot());
|
|
297
|
+
return { configured: true, changed: renderCodexConfig(existing, connection) !== existing, target };
|
|
298
|
+
}
|
|
299
|
+
|
|
208
300
|
function runMcpConfigureCli(host, options = {}) {
|
|
209
301
|
const normalized = String(host || "").trim().toLowerCase();
|
|
210
302
|
if (normalized !== "codex") {
|
|
@@ -237,6 +329,7 @@ module.exports = {
|
|
|
237
329
|
buildCodexManagedBlock,
|
|
238
330
|
codexConfigPath,
|
|
239
331
|
configureCodexMcp,
|
|
332
|
+
inspectCodexMcpConfig,
|
|
240
333
|
findTomlSections,
|
|
241
334
|
removeLegacyUfooTransportSections,
|
|
242
335
|
removeManagedBlock,
|
|
@@ -211,16 +211,18 @@ class GlobalMcpHttpServer {
|
|
|
211
211
|
? request.params.arguments
|
|
212
212
|
: {};
|
|
213
213
|
const requestKey = `${extra.sessionId || "no-session"}:${String(extra.requestId)}`;
|
|
214
|
+
const controller = new AbortController();
|
|
214
215
|
this.activeRequests.set(requestKey, {
|
|
215
216
|
tool: name,
|
|
216
217
|
started_at: new Date().toISOString(),
|
|
218
|
+
controller,
|
|
217
219
|
});
|
|
218
220
|
try {
|
|
219
221
|
const result = await invokeTool(name, args, {
|
|
220
222
|
projectRuntimeGateway: this.projectRuntimeGateway,
|
|
221
223
|
validateProjectRoot: this.validateProjectRoot,
|
|
222
224
|
toolCallId: extra.requestId,
|
|
223
|
-
signal: extra.signal,
|
|
225
|
+
signal: AbortSignal.any([extra.signal, controller.signal]),
|
|
224
226
|
getMcpHttpStatus: () => this.getStatus(),
|
|
225
227
|
});
|
|
226
228
|
return createMcpContent(result);
|
|
@@ -283,10 +285,21 @@ class GlobalMcpHttpServer {
|
|
|
283
285
|
session = this.createSession();
|
|
284
286
|
await session.protocolServer.connect(session.transport);
|
|
285
287
|
} else if (!session) {
|
|
286
|
-
rpcError(res, 400, "Bad Request: no valid MCP session");
|
|
288
|
+
rpcError(res, sessionId ? 404 : 400, "Bad Request: no valid MCP session");
|
|
287
289
|
return;
|
|
288
290
|
}
|
|
289
|
-
|
|
291
|
+
const requestKey = `${session.transport.sessionId}:${String(body.id)}`;
|
|
292
|
+
const onDisconnect = () => {
|
|
293
|
+
if (!res.writableEnded) this.activeRequests.get(requestKey)?.controller.abort();
|
|
294
|
+
};
|
|
295
|
+
res.once("close", onDisconnect);
|
|
296
|
+
try {
|
|
297
|
+
await session.transport.handleRequest(req, res, body);
|
|
298
|
+
} finally {
|
|
299
|
+
// handleRequest can return before a streamed response ends. Keep the
|
|
300
|
+
// close listener until then; a finished response is not cancellation.
|
|
301
|
+
if (res.writableEnded) res.removeListener("close", onDisconnect);
|
|
302
|
+
}
|
|
290
303
|
return;
|
|
291
304
|
}
|
|
292
305
|
|
|
@@ -295,12 +308,13 @@ class GlobalMcpHttpServer {
|
|
|
295
308
|
return;
|
|
296
309
|
}
|
|
297
310
|
|
|
298
|
-
rpcError(res, sessionId ?
|
|
311
|
+
rpcError(res, sessionId ? 404 : 405, sessionId
|
|
299
312
|
? "Bad Request: no valid MCP session"
|
|
300
313
|
: "Method not allowed");
|
|
301
314
|
}
|
|
302
315
|
|
|
303
316
|
async handleHttpRequest(req, res) {
|
|
317
|
+
if (this.stopping) { jsonResponse(res, 503, { error: "MCP server is stopping" }); return; }
|
|
304
318
|
this.httpRequestCount += 1;
|
|
305
319
|
const requestUrl = new URL(req.url || "/", `http://${req.headers.host || "localhost"}`);
|
|
306
320
|
if (requestUrl.pathname === "/health") {
|
|
@@ -390,7 +404,15 @@ class GlobalMcpHttpServer {
|
|
|
390
404
|
if (this.server) {
|
|
391
405
|
const server = this.server;
|
|
392
406
|
this.server = null;
|
|
393
|
-
await new Promise((resolve) =>
|
|
407
|
+
await new Promise((resolve) => {
|
|
408
|
+
// Node 18 does not close idle keep-alive sockets in server.close().
|
|
409
|
+
// Sessions are already cancelled; bound shutdown even if a client
|
|
410
|
+
// leaves an HTTP stream or partially written request open.
|
|
411
|
+
const deadline = setTimeout(() => server.closeAllConnections?.(), 1000);
|
|
412
|
+
deadline.unref();
|
|
413
|
+
server.close(() => { clearTimeout(deadline); resolve(); });
|
|
414
|
+
server.closeIdleConnections?.();
|
|
415
|
+
});
|
|
394
416
|
}
|
|
395
417
|
try {
|
|
396
418
|
if (fs.existsSync(this.endpointPath)) fs.unlinkSync(this.endpointPath);
|
|
@@ -23,6 +23,7 @@ const {
|
|
|
23
23
|
assertToolAllowedForCallerTier,
|
|
24
24
|
} = require("../../tools/registry");
|
|
25
25
|
const { CALLER_TIERS } = require("../../tools/types");
|
|
26
|
+
const { projectPathExists } = require("../projects/registry");
|
|
26
27
|
const {
|
|
27
28
|
MCP_PROTOCOL_VERSION,
|
|
28
29
|
MCP_WAIT_FOR_MESSAGE_DEFAULT_TIMEOUT_SECONDS,
|
|
@@ -88,7 +89,7 @@ const CUSTOM_TOOL_DEFINITIONS = Object.freeze([
|
|
|
88
89
|
},
|
|
89
90
|
{
|
|
90
91
|
name: "publish_activity_state",
|
|
91
|
-
description: "Publish
|
|
92
|
+
description: "Publish an external Agent's activity state. Wrapper-managed activity belongs to its host.",
|
|
92
93
|
input_schema: {
|
|
93
94
|
type: "object",
|
|
94
95
|
required: ["project_root", "subscriber", "agent_handle", "activity_state"],
|
|
@@ -138,7 +139,7 @@ const CUSTOM_TOOL_DEFINITIONS = Object.freeze([
|
|
|
138
139
|
},
|
|
139
140
|
{
|
|
140
141
|
name: "wait_for_message",
|
|
141
|
-
description: "Keep
|
|
142
|
+
description: "Keep an external Agent's MCP receive call pending until messages arrive after after_seq, or until cancellation/timeout. Wrapper-managed identities already have host delivery and cannot arm this wait.",
|
|
142
143
|
input_schema: {
|
|
143
144
|
type: "object",
|
|
144
145
|
required: ["project_root", "subscriber", "agent_handle"],
|
|
@@ -323,7 +324,8 @@ async function suppressConsoleToStderr(fn) {
|
|
|
323
324
|
|
|
324
325
|
function listRegisteredProjectRows() {
|
|
325
326
|
return listProjectRuntimes({ validate: true, cleanupTmp: true })
|
|
326
|
-
.filter((row) => !isGlobalControllerProjectRoot(row && row.project_root)
|
|
327
|
+
.filter((row) => !isGlobalControllerProjectRoot(row && row.project_root)
|
|
328
|
+
&& projectPathExists(row.project_root));
|
|
327
329
|
}
|
|
328
330
|
|
|
329
331
|
function resolveRegisteredProjectRoot(args = {}, options = {}) {
|
|
@@ -406,7 +408,7 @@ async function ensureGlobalControllerDaemon(options = {}) {
|
|
|
406
408
|
await suppressConsoleToStderr(() => init.init({
|
|
407
409
|
targets: "context,bus",
|
|
408
410
|
project: root,
|
|
409
|
-
|
|
411
|
+
globalController: true,
|
|
410
412
|
}));
|
|
411
413
|
}
|
|
412
414
|
|
|
@@ -474,7 +476,8 @@ async function handleMcpStatus(ctx = {}) {
|
|
|
474
476
|
auto_start: ctx.autoStart !== false,
|
|
475
477
|
http,
|
|
476
478
|
project_count: projects.length,
|
|
477
|
-
projects,
|
|
479
|
+
projects: projects.slice(0, 100),
|
|
480
|
+
projects_truncated: projects.length > 100,
|
|
478
481
|
};
|
|
479
482
|
}
|
|
480
483
|
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
|
|
3
3
|
const fs = require("fs");
|
|
4
|
+
const { Agent } = require("undici");
|
|
4
5
|
|
|
5
6
|
const { getUfooPaths } = require("../../coordination/state/paths");
|
|
6
7
|
const {
|
|
@@ -13,6 +14,13 @@ const {
|
|
|
13
14
|
|
|
14
15
|
const DEFAULT_ENDPOINT_WAIT_MS = 5000;
|
|
15
16
|
const DEFAULT_ENDPOINT_POLL_MS = 50;
|
|
17
|
+
const DEFAULT_REQUEST_TIMEOUT_MS = 610000;
|
|
18
|
+
// A disconnected write may already have committed. Only queue reads and other
|
|
19
|
+
// read-only operations can be replayed after an ambiguous transport failure.
|
|
20
|
+
const REPLAYABLE_TOOLS = new Set([
|
|
21
|
+
"read_project_registry", "read_bus_summary", "read_prompt_history", "read_open_decisions",
|
|
22
|
+
"list_agents", "ufoo_mcp_status", "poll_inbox", "wait_for_message",
|
|
23
|
+
]);
|
|
16
24
|
const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "::1", "[::1]"]);
|
|
17
25
|
|
|
18
26
|
function sleep(ms) {
|
|
@@ -56,11 +64,23 @@ class McpStdioProxy {
|
|
|
56
64
|
this.autoStart = options.autoStart !== false;
|
|
57
65
|
this.ensureDaemon = options.ensureDaemon || (async () => {});
|
|
58
66
|
this.fetch = options.fetch || globalThis.fetch;
|
|
67
|
+
// Undici's default headers/body deadlines also apply to fetch. Resident
|
|
68
|
+
// MCP receives must not be ended by that hidden transport timer.
|
|
69
|
+
this.dispatcher = options.dispatcher || (!options.fetch
|
|
70
|
+
? new Agent({ headersTimeout: 0, bodyTimeout: 0, connect: { timeout: DEFAULT_ENDPOINT_WAIT_MS } })
|
|
71
|
+
: null);
|
|
72
|
+
this.ownsDispatcher = Boolean(this.dispatcher && !options.dispatcher);
|
|
59
73
|
this.endpoint = options.endpoint ? validateEndpoint(options.endpoint) : "";
|
|
74
|
+
this.managedConnection = !options.endpoint;
|
|
60
75
|
this.token = String(options.token || "");
|
|
61
76
|
this.endpointWaitMs = Number(options.endpointWaitMs) || DEFAULT_ENDPOINT_WAIT_MS;
|
|
62
77
|
this.endpointPollMs = Number(options.endpointPollMs) || DEFAULT_ENDPOINT_POLL_MS;
|
|
78
|
+
this.requestTimeoutMs = Number(options.requestTimeoutMs) || DEFAULT_REQUEST_TIMEOUT_MS;
|
|
63
79
|
this.sessionId = "";
|
|
80
|
+
this.protocolVersion = "";
|
|
81
|
+
this.initializeParams = null;
|
|
82
|
+
this.generation = 0;
|
|
83
|
+
this.recovering = null;
|
|
64
84
|
this.startup = null;
|
|
65
85
|
this.initializing = null;
|
|
66
86
|
this.activeRequests = new Map();
|
|
@@ -118,11 +138,18 @@ class McpStdioProxy {
|
|
|
118
138
|
"content-type": "application/json",
|
|
119
139
|
};
|
|
120
140
|
if (this.sessionId) headers["mcp-session-id"] = this.sessionId;
|
|
141
|
+
if (this.protocolVersion) headers["mcp-protocol-version"] = this.protocolVersion;
|
|
142
|
+
const residentWait = request.method === "tools/call"
|
|
143
|
+
&& request.params?.name === "wait_for_message"
|
|
144
|
+
&& Number(request.params?.arguments?.timeout_seconds || 0) === 0;
|
|
145
|
+
const timeout = residentWait ? null : AbortSignal.timeout(this.requestTimeoutMs);
|
|
146
|
+
const signal = timeout ? AbortSignal.any([controller.signal, timeout]) : controller.signal;
|
|
121
147
|
const response = await this.fetch(this.endpoint, {
|
|
122
148
|
method: "POST",
|
|
123
149
|
headers,
|
|
124
150
|
body: JSON.stringify(request),
|
|
125
|
-
signal
|
|
151
|
+
signal,
|
|
152
|
+
...(this.dispatcher ? { dispatcher: this.dispatcher } : {}),
|
|
126
153
|
});
|
|
127
154
|
const nextSessionId = response.headers.get("mcp-session-id");
|
|
128
155
|
if (nextSessionId) this.sessionId = nextSessionId;
|
|
@@ -130,7 +157,9 @@ class McpStdioProxy {
|
|
|
130
157
|
const text = await response.text();
|
|
131
158
|
if (!text) {
|
|
132
159
|
if (response.ok) return null;
|
|
133
|
-
|
|
160
|
+
const err = new Error(`Global MCP returned HTTP ${response.status}`);
|
|
161
|
+
err.status = response.status;
|
|
162
|
+
throw err;
|
|
134
163
|
}
|
|
135
164
|
let payload;
|
|
136
165
|
try {
|
|
@@ -138,22 +167,105 @@ class McpStdioProxy {
|
|
|
138
167
|
} catch {
|
|
139
168
|
throw new Error(`Global MCP returned invalid JSON (HTTP ${response.status})`);
|
|
140
169
|
}
|
|
170
|
+
if (!response.ok) {
|
|
171
|
+
const err = new Error(payload.error?.message || `Global MCP returned HTTP ${response.status}`);
|
|
172
|
+
err.status = response.status;
|
|
173
|
+
err.code = "UFOO_MCP_HTTP_ERROR";
|
|
174
|
+
throw err;
|
|
175
|
+
}
|
|
176
|
+
if (request.method === "initialize" && payload.result) {
|
|
177
|
+
this.initializeParams = request.params;
|
|
178
|
+
this.protocolVersion = payload.result.protocolVersion;
|
|
179
|
+
}
|
|
141
180
|
return payload;
|
|
142
181
|
}
|
|
143
182
|
|
|
183
|
+
async recover(generation) {
|
|
184
|
+
if (this.recovering) return this.recovering;
|
|
185
|
+
if (generation !== this.generation) return;
|
|
186
|
+
if (!this.initializeParams || this.closed) throw new Error("MCP session is not initialized");
|
|
187
|
+
const controller = new AbortController();
|
|
188
|
+
const timer = setTimeout(() => controller.abort(), this.endpointWaitMs);
|
|
189
|
+
this.recoveryController = controller;
|
|
190
|
+
this.recovering = (async () => {
|
|
191
|
+
this.sessionId = "";
|
|
192
|
+
if (this.managedConnection) {
|
|
193
|
+
this.endpoint = "";
|
|
194
|
+
this.token = "";
|
|
195
|
+
this.startup = null;
|
|
196
|
+
}
|
|
197
|
+
const request = { jsonrpc: "2.0", id: "ufoo-proxy-reinitialize", method: "initialize", params: this.initializeParams };
|
|
198
|
+
let response;
|
|
199
|
+
// An idle HTTP keep-alive socket can fail once after a listener restart.
|
|
200
|
+
const deadline = Date.now() + this.endpointWaitMs;
|
|
201
|
+
while (!controller.signal.aborted) {
|
|
202
|
+
try {
|
|
203
|
+
response = await this.post(request, controller);
|
|
204
|
+
break;
|
|
205
|
+
} catch (err) {
|
|
206
|
+
if (controller.signal.aborted || Date.now() >= deadline
|
|
207
|
+
|| (err.status && ![401, 502, 503].includes(err.status))) throw err;
|
|
208
|
+
if (this.managedConnection) {
|
|
209
|
+
this.endpoint = "";
|
|
210
|
+
this.token = "";
|
|
211
|
+
this.startup = null;
|
|
212
|
+
}
|
|
213
|
+
await sleep(this.endpointPollMs);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
if (!response?.result) throw new Error(response?.error?.message || "MCP reinitialization failed");
|
|
217
|
+
await this.post({ jsonrpc: "2.0", method: "notifications/initialized" }, controller);
|
|
218
|
+
this.generation += 1;
|
|
219
|
+
})();
|
|
220
|
+
try {
|
|
221
|
+
await this.recovering;
|
|
222
|
+
} finally {
|
|
223
|
+
clearTimeout(timer);
|
|
224
|
+
this.recoveryController = null;
|
|
225
|
+
this.recovering = null;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
async postWithRecovery(request, controller) {
|
|
230
|
+
if (this.recovering) await this.recovering;
|
|
231
|
+
const generation = this.generation;
|
|
232
|
+
try {
|
|
233
|
+
return await this.post(request, controller);
|
|
234
|
+
} catch (err) {
|
|
235
|
+
if (controller.signal.aborted || this.closed || request.method === "initialize") throw err;
|
|
236
|
+
const rejectedSession = err.status === 404
|
|
237
|
+
|| (err.status === 400 && /no valid MCP session/i.test(err.message))
|
|
238
|
+
|| (err.status === 401 && this.managedConnection);
|
|
239
|
+
const disconnected = !err.status && err instanceof TypeError;
|
|
240
|
+
if (!rejectedSession && !disconnected) throw err;
|
|
241
|
+
const replayable = rejectedSession || ["ping", "tools/list"].includes(request.method)
|
|
242
|
+
|| (request.method === "tools/call" && REPLAYABLE_TOOLS.has(request.params?.name));
|
|
243
|
+
if (!replayable) {
|
|
244
|
+
err.code = "UFOO_MCP_OUTCOME_UNKNOWN";
|
|
245
|
+
err.message = `Connection lost; ${request.params?.name || request.method} may have completed. Check its result before retrying.`;
|
|
246
|
+
try { await this.recover(generation); } catch { /* Preserve the uncertain write outcome even if recovery failed. */ }
|
|
247
|
+
throw err;
|
|
248
|
+
}
|
|
249
|
+
await this.recover(generation);
|
|
250
|
+
controller.signal.throwIfAborted();
|
|
251
|
+
return this.post(request, controller);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
144
255
|
async forward(request) {
|
|
256
|
+
if (this.closed) return null;
|
|
145
257
|
const hasId = Object.prototype.hasOwnProperty.call(request || {}, "id");
|
|
146
258
|
const id = hasId ? request.id : undefined;
|
|
147
259
|
const method = String((request && request.method) || "");
|
|
148
|
-
if (method !== "initialize" && this.initializing) {
|
|
149
|
-
await this.initializing;
|
|
150
|
-
}
|
|
151
|
-
|
|
152
260
|
const controller = new AbortController();
|
|
153
261
|
if (hasId) this.activeRequests.set(id, controller);
|
|
154
|
-
|
|
155
|
-
|
|
262
|
+
if (method === "notifications/cancelled") {
|
|
263
|
+
this.activeRequests.get(request.params?.requestId)?.abort();
|
|
264
|
+
}
|
|
156
265
|
try {
|
|
266
|
+
if (method !== "initialize" && this.initializing) await this.initializing;
|
|
267
|
+
const operation = this.postWithRecovery(request, controller);
|
|
268
|
+
if (method === "initialize") this.initializing = operation;
|
|
157
269
|
const response = await operation;
|
|
158
270
|
if (response) this.writeMessage(response);
|
|
159
271
|
return response;
|
|
@@ -212,20 +324,25 @@ class McpStdioProxy {
|
|
|
212
324
|
async close() {
|
|
213
325
|
if (this.closed) return;
|
|
214
326
|
this.closed = true;
|
|
327
|
+
this.recoveryController?.abort();
|
|
215
328
|
for (const controller of this.activeRequests.values()) controller.abort();
|
|
216
329
|
this.activeRequests.clear();
|
|
217
|
-
if (!this.endpoint || !this.token || !this.sessionId) return;
|
|
218
330
|
try {
|
|
219
|
-
await this.fetch(this.endpoint, {
|
|
331
|
+
if (this.endpoint && this.token && this.sessionId) await this.fetch(this.endpoint, {
|
|
220
332
|
method: "DELETE",
|
|
221
333
|
headers: {
|
|
222
334
|
accept: "application/json, text/event-stream",
|
|
223
335
|
authorization: `Bearer ${this.token}`,
|
|
224
336
|
"mcp-session-id": this.sessionId,
|
|
337
|
+
"mcp-protocol-version": this.protocolVersion,
|
|
225
338
|
},
|
|
339
|
+
signal: AbortSignal.timeout(this.endpointWaitMs),
|
|
340
|
+
...(this.dispatcher ? { dispatcher: this.dispatcher } : {}),
|
|
226
341
|
});
|
|
227
342
|
} catch {
|
|
228
343
|
// The adapter is disposable; the server will also close abandoned sessions.
|
|
344
|
+
} finally {
|
|
345
|
+
if (this.ownsDispatcher) await this.dispatcher.destroy();
|
|
229
346
|
}
|
|
230
347
|
}
|
|
231
348
|
}
|
|
@@ -25,7 +25,7 @@ function normalizeAutoNicknamePrefix(agentType = "") {
|
|
|
25
25
|
if (normalized === "agy") return "agy";
|
|
26
26
|
if (normalized === "grok") return "grok";
|
|
27
27
|
if (normalized === "kimi" || normalized === "kimi-cli" || normalized === "kimi-code") return "kimi";
|
|
28
|
-
if (normalized === "
|
|
28
|
+
if (normalized === "ucode") return "ucode";
|
|
29
29
|
return "";
|
|
30
30
|
}
|
|
31
31
|
|