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
|
@@ -6,7 +6,7 @@ const net = require("net");
|
|
|
6
6
|
const path = require("path");
|
|
7
7
|
const EventBus = require("../../coordination/bus");
|
|
8
8
|
const { isMismatchedAutoNickname } = require("../../coordination/bus/nickname");
|
|
9
|
-
const { isAgentPidAlive } = require("../../coordination/bus/utils");
|
|
9
|
+
const { isAgentPidAlive, normalizeAgentTypeAlias } = require("../../coordination/bus/utils");
|
|
10
10
|
const { showBanner } = require("../../ui/format/banner");
|
|
11
11
|
const AgentNotifier = require("./notifier");
|
|
12
12
|
const { ActivityDetector } = require("../activity/activityDetector");
|
|
@@ -14,6 +14,7 @@ const { createActivityStatePublisher } = require("../activity/activityStatePubli
|
|
|
14
14
|
const { reconcileDetectorOwnedActivity } = require("../activity/activityReconcile");
|
|
15
15
|
const { detectLaunchEnvironment } = require("./launchEnvironment");
|
|
16
16
|
const { getUfooPaths } = require("../../coordination/state/paths");
|
|
17
|
+
const { updateAgentsData } = require("../../coordination/state/agentsStore");
|
|
17
18
|
const {
|
|
18
19
|
resolveDaemonEndpoint,
|
|
19
20
|
routeDaemonRequest,
|
|
@@ -30,6 +31,21 @@ const {
|
|
|
30
31
|
persistConversationId,
|
|
31
32
|
} = require("./agyConversation");
|
|
32
33
|
|
|
34
|
+
function setLauncherReady(projectRoot, subscriber, ready) {
|
|
35
|
+
try {
|
|
36
|
+
const file = getUfooPaths(projectRoot).agentsFile;
|
|
37
|
+
if (!fs.existsSync(file)) return false;
|
|
38
|
+
return updateAgentsData(file, (data) => {
|
|
39
|
+
const meta = data.agents && data.agents[subscriber];
|
|
40
|
+
if (!meta || meta.status === "inactive") return false;
|
|
41
|
+
meta.launcher_ready = ready;
|
|
42
|
+
return true;
|
|
43
|
+
});
|
|
44
|
+
} catch {
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
33
49
|
function connectSocket(sockPath) {
|
|
34
50
|
return new Promise((resolve, reject) => {
|
|
35
51
|
const client = net.createConnection(sockPath, () => resolve(client));
|
|
@@ -176,7 +192,7 @@ function findPreviousSession(cwd, agentType, tty, tmuxPane) {
|
|
|
176
192
|
if (!meta) continue;
|
|
177
193
|
|
|
178
194
|
// 必须是同类型 agent
|
|
179
|
-
if (meta.agent_type !== agentType) continue;
|
|
195
|
+
if (normalizeAgentTypeAlias(meta.agent_type) !== normalizeAgentTypeAlias(agentType)) continue;
|
|
180
196
|
|
|
181
197
|
// tmux 模式:必须匹配 tmux_pane(更精确)
|
|
182
198
|
if (tmuxPane) {
|
|
@@ -370,7 +386,7 @@ class AgentLauncher {
|
|
|
370
386
|
if (!subscriberId) return null;
|
|
371
387
|
const parts = subscriberId.split(":");
|
|
372
388
|
if (parts.length !== 2) return null;
|
|
373
|
-
if (parts[0] !== this.agentType) return null;
|
|
389
|
+
if (normalizeAgentTypeAlias(parts[0]) !== normalizeAgentTypeAlias(this.agentType)) return null;
|
|
374
390
|
try {
|
|
375
391
|
const bus = new EventBus(this.cwd);
|
|
376
392
|
bus.loadBusData();
|
|
@@ -380,11 +396,12 @@ class AgentLauncher {
|
|
|
380
396
|
if (Number.isFinite(pidValue) && pidValue > 0 && !isAgentPidAlive(pidValue)) {
|
|
381
397
|
return null;
|
|
382
398
|
}
|
|
383
|
-
if (meta.agent_type && meta.agent_type !== this.agentType) return null;
|
|
399
|
+
if (meta.agent_type && normalizeAgentTypeAlias(meta.agent_type) !== normalizeAgentTypeAlias(this.agentType)) return null;
|
|
384
400
|
return {
|
|
385
401
|
subscriberId,
|
|
386
402
|
sessionId: parts[1],
|
|
387
403
|
nickname: meta.nickname || process.env.UFOO_NICKNAME || "",
|
|
404
|
+
agentHandle: process.env.UFOO_AGENT_HANDLE || "",
|
|
388
405
|
preRegistered: true,
|
|
389
406
|
};
|
|
390
407
|
} catch {
|
|
@@ -567,6 +584,7 @@ class AgentLauncher {
|
|
|
567
584
|
resolve({
|
|
568
585
|
subscriberId: payload.subscriberId,
|
|
569
586
|
nickname: payload.nickname || nickname || "",
|
|
587
|
+
agentHandle: payload.agentHandle || "",
|
|
570
588
|
sessionId: (payload.subscriberId || "").split(":")[1] || "",
|
|
571
589
|
preRegistered: false,
|
|
572
590
|
});
|
|
@@ -640,6 +658,7 @@ class AgentLauncher {
|
|
|
640
658
|
const monitorStartedAt = Date.now();
|
|
641
659
|
detector.onReady(() => {
|
|
642
660
|
stopReadyMonitor();
|
|
661
|
+
setLauncherReady(this.cwd, subscriberId, true);
|
|
643
662
|
notifier.markLauncherReady();
|
|
644
663
|
notifier.updateActivityState("ready");
|
|
645
664
|
});
|
|
@@ -672,12 +691,14 @@ class AgentLauncher {
|
|
|
672
691
|
|
|
673
692
|
child.on("error", (err) => {
|
|
674
693
|
stopReadyMonitor();
|
|
694
|
+
void options.nativeMessages?.close();
|
|
675
695
|
console.error(`[${this.command}] Failed to start:`, err.message);
|
|
676
696
|
process.exit(1);
|
|
677
697
|
});
|
|
678
698
|
|
|
679
699
|
child.on("exit", async (code, signal) => {
|
|
680
700
|
stopReadyMonitor();
|
|
701
|
+
await options.nativeMessages?.close();
|
|
681
702
|
// 清理 bus 状态
|
|
682
703
|
try {
|
|
683
704
|
const bus = new EventBus(this.cwd);
|
|
@@ -701,9 +722,21 @@ class AgentLauncher {
|
|
|
701
722
|
* 启动 agent
|
|
702
723
|
*/
|
|
703
724
|
async launch(args) {
|
|
725
|
+
let nativeMessages = null;
|
|
704
726
|
// 保存用户/group 显式传入的 nickname(在 session 复用覆盖前)
|
|
705
727
|
this._originalNickname = process.env.UFOO_NICKNAME || "";
|
|
706
728
|
try {
|
|
729
|
+
let useNativeMessages = require("./nativeMessages").resolveNativeMessageMode({ agentType: this.agentType, args });
|
|
730
|
+
let nativeCapabilities = null;
|
|
731
|
+
if (useNativeMessages) {
|
|
732
|
+
nativeCapabilities = require("./nativeCapabilities").probeNativeCapabilities({ agentType: this.agentType, command: this.command });
|
|
733
|
+
if (!nativeCapabilities.supported) {
|
|
734
|
+
const detail = `Native messages unavailable: ${nativeCapabilities.reason}; update ${this.command} or use --no-native-messages`;
|
|
735
|
+
if (process.env.UFOO_NATIVE_MESSAGES === "1") throw new Error(detail);
|
|
736
|
+
console.error(`[ufoo] ${detail}. Using legacy delivery for this launch.`);
|
|
737
|
+
useNativeMessages = false;
|
|
738
|
+
}
|
|
739
|
+
}
|
|
707
740
|
// 1. 确保初始化
|
|
708
741
|
await this.ensureInit();
|
|
709
742
|
|
|
@@ -719,11 +752,39 @@ class AgentLauncher {
|
|
|
719
752
|
const sessionId = result.sessionId || (subscriberId.split(":")[1] || "");
|
|
720
753
|
const finalNickname = result.nickname || nickname || "";
|
|
721
754
|
|
|
755
|
+
if (["codex", "claude-code"].includes(this.agentType)) {
|
|
756
|
+
setLauncherReady(this.cwd, subscriberId, false);
|
|
757
|
+
}
|
|
758
|
+
|
|
722
759
|
// 4. 更新环境变量(供子进程/后续使用)
|
|
723
760
|
if (subscriberId) process.env.UFOO_SUBSCRIBER_ID = subscriberId;
|
|
761
|
+
// Never inherit the launching Agent's capability for a new identity.
|
|
762
|
+
if (result.agentHandle) process.env.UFOO_AGENT_HANDLE = result.agentHandle;
|
|
763
|
+
else delete process.env.UFOO_AGENT_HANDLE;
|
|
724
764
|
if (finalNickname) process.env.UFOO_NICKNAME = finalNickname;
|
|
725
765
|
process.env.UFOO_AGENT_TYPE = this.agentType;
|
|
726
766
|
|
|
767
|
+
if (["codex", "claude-code"].includes(this.agentType)) {
|
|
768
|
+
// A resumed host may retain the previous launch's receiver metadata.
|
|
769
|
+
// Select the new transport before asynchronous receiver startup.
|
|
770
|
+
require("./nativeMessages").setNativeMetadata(this.cwd, subscriberId, {
|
|
771
|
+
native_delivery: useNativeMessages ? (this.agentType === "codex" ? "codex_queue" : "claude_channel") : null,
|
|
772
|
+
native_delivery_ready: false,
|
|
773
|
+
native_delivery_instance: null,
|
|
774
|
+
native_delivery_version: nativeCapabilities?.version || "",
|
|
775
|
+
native_delivery_diagnostic: nativeCapabilities?.reason || "",
|
|
776
|
+
});
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
if (useNativeMessages) {
|
|
780
|
+
nativeMessages = await require("./nativeMessages").prepareNativeMessages({
|
|
781
|
+
agentType: this.agentType, command: this.command, args,
|
|
782
|
+
projectRoot: this.cwd, subscriber: subscriberId,
|
|
783
|
+
});
|
|
784
|
+
args = nativeMessages.args;
|
|
785
|
+
Object.assign(process.env, nativeMessages.env || {});
|
|
786
|
+
}
|
|
787
|
+
|
|
727
788
|
// 5. 显示 banner(ucode 自带 TUI banner,这里避免重复)
|
|
728
789
|
if (shouldShowLaunchBanner(this.agentType)) {
|
|
729
790
|
showBanner({
|
|
@@ -734,8 +795,8 @@ class AgentLauncher {
|
|
|
734
795
|
});
|
|
735
796
|
}
|
|
736
797
|
|
|
737
|
-
// 6. 启动消息通知监听器(
|
|
738
|
-
const shouldStartNotifier = String(this.agentType || "").trim().toLowerCase()
|
|
798
|
+
// 6. 启动消息通知监听器(ucode 自行消费内部 bus 队列)
|
|
799
|
+
const shouldStartNotifier = !(String(this.agentType || "").trim().toLowerCase() === "ucode");
|
|
739
800
|
let notifier = null;
|
|
740
801
|
if (shouldStartNotifier) {
|
|
741
802
|
notifier = new AgentNotifier(this.cwd, subscriberId);
|
|
@@ -874,19 +935,26 @@ class AgentLauncher {
|
|
|
874
935
|
}
|
|
875
936
|
|
|
876
937
|
if (startupBootstrapText && wrapper.pty) {
|
|
877
|
-
|
|
938
|
+
if (nativeMessages) {
|
|
939
|
+
try { await nativeMessages.send({ command: startupBootstrapText, deliveryId: `startup-bootstrap:${sessionId}` }); }
|
|
940
|
+
catch (err) { console.error(`[ufoo] Native startup bootstrap failed: ${err.message}`); }
|
|
941
|
+
} else await injectPtyCommand(wrapper, this.agentType, startupBootstrapText, "startup-bootstrap");
|
|
878
942
|
}
|
|
879
943
|
|
|
944
|
+
setLauncherReady(this.cwd, subscriberId, true);
|
|
880
945
|
await notifyDaemonAgentReady(daemonEndpoint, subscriberId, wrapper.pty ? wrapper.pty.pid : 0);
|
|
881
946
|
});
|
|
947
|
+
nativeMessages?.onReady?.(() => readyDetector.confirmNativeReady());
|
|
882
948
|
|
|
883
|
-
//
|
|
949
|
+
// Elapsed time cannot prove that a host can accept input. Preserve
|
|
950
|
+
// queued work and report a slow startup instead of injecting blindly.
|
|
884
951
|
const forceReadyTimer = setTimeout(() => {
|
|
885
|
-
readyDetector.
|
|
952
|
+
if (!readyDetector.ready) console.error(`[ufoo] Waiting for ${this.command} to become ready; queued work is retained.`);
|
|
886
953
|
}, 10000);
|
|
887
954
|
|
|
888
955
|
// 设置退出回调(复用清理逻辑)
|
|
889
956
|
wrapper.onExit = async ({ exitCode, signal }) => {
|
|
957
|
+
await nativeMessages?.close();
|
|
890
958
|
// 清理 timers
|
|
891
959
|
clearTimeout(forceReadyTimer);
|
|
892
960
|
clearInterval(activityReconcileTimer);
|
|
@@ -996,13 +1064,24 @@ class AgentLauncher {
|
|
|
996
1064
|
const req = JSON.parse(line);
|
|
997
1065
|
if (req.type === "inject" && req.command) {
|
|
998
1066
|
const normalizedAgentType = String(this.agentType || "").trim().toLowerCase();
|
|
999
|
-
if (normalizedAgentType === "
|
|
1000
|
-
client.write(JSON.stringify({ ok: false, error: "inject disabled for
|
|
1067
|
+
if (normalizedAgentType === "ucode") {
|
|
1068
|
+
client.write(JSON.stringify({ ok: false, error: "inject disabled for ucode (internal bus loop)" }) + "\n");
|
|
1001
1069
|
continue;
|
|
1002
1070
|
}
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1071
|
+
if (nativeMessages) {
|
|
1072
|
+
const reply = (result) => {
|
|
1073
|
+
if (!client.destroyed) client.write(JSON.stringify(result) + "\n");
|
|
1074
|
+
};
|
|
1075
|
+
void nativeMessages.send(req).then((receipt) => {
|
|
1076
|
+
reply({ ok: true, ...receipt });
|
|
1077
|
+
}).catch((err) => {
|
|
1078
|
+
reply({ ok: false, error: err.message, code: err.code });
|
|
1079
|
+
});
|
|
1080
|
+
} else {
|
|
1081
|
+
// 注入命令到PTY(带延迟确保输入完成)
|
|
1082
|
+
void injectPtyCommand(wrapper, this.agentType, req.command, "inject");
|
|
1083
|
+
client.write(JSON.stringify({ ok: true }) + "\n");
|
|
1084
|
+
}
|
|
1006
1085
|
} else if (req.type === PTY_SOCKET_MESSAGE_TYPES.RAW && req.data) {
|
|
1007
1086
|
// Raw PTY write (no Enter appended) - for TTY view passthrough
|
|
1008
1087
|
wrapper.write(req.data);
|
|
@@ -1094,14 +1173,17 @@ class AgentLauncher {
|
|
|
1094
1173
|
process.on("SIGTERM", () => handleTermSignal("SIGTERM"));
|
|
1095
1174
|
process.on("SIGINT", () => handleTermSignal("SIGINT"));
|
|
1096
1175
|
} catch (err) {
|
|
1176
|
+
if (nativeMessages) throw err;
|
|
1097
1177
|
console.error(`[PTY] Failed to start, falling back to spawn:`, err.message);
|
|
1098
1178
|
this._spawnDirect(args, subscriberId, { notifier });
|
|
1099
1179
|
}
|
|
1100
1180
|
} else {
|
|
1181
|
+
if (nativeMessages) throw new Error("Native messages require an interactive PTY launch; remove UFOO_DISABLE_PTY or use a terminal");
|
|
1101
1182
|
// 非PTY环境:tmux、internal、管道、显式禁用等
|
|
1102
1183
|
this._spawnDirect(args, subscriberId, { notifier });
|
|
1103
1184
|
}
|
|
1104
1185
|
} catch (err) {
|
|
1186
|
+
await nativeMessages?.close();
|
|
1105
1187
|
console.error(`[${this.command}] Error:`, err.message);
|
|
1106
1188
|
process.exit(1);
|
|
1107
1189
|
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
const { spawnSync } = require("child_process");
|
|
2
|
+
|
|
3
|
+
// These are the oldest versions verified by our real-CLI smoke tests, not a
|
|
4
|
+
// claim about the vendor's first release of each experimental API.
|
|
5
|
+
const TESTED_BASELINES = { codex: "0.160.1", "claude-code": "2.1.204" };
|
|
6
|
+
const cache = new Map();
|
|
7
|
+
|
|
8
|
+
function atLeast(version, baseline) {
|
|
9
|
+
const left = version.split(".").map(Number);
|
|
10
|
+
const right = baseline.split(".").map(Number);
|
|
11
|
+
for (let i = 0; i < 3; i++) {
|
|
12
|
+
if (left[i] !== right[i]) return left[i] > right[i];
|
|
13
|
+
}
|
|
14
|
+
return true;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function probeNativeCapabilities({ agentType, command, env = process.env, spawnSyncImpl = spawnSync } = {}) {
|
|
18
|
+
const baseline = TESTED_BASELINES[agentType];
|
|
19
|
+
if (!baseline) return { supported: false, reason: "unsupported_provider" };
|
|
20
|
+
const executable = command || (agentType === "codex" ? "codex" : "claude");
|
|
21
|
+
const key = `${agentType}:${executable}:${env.PATH}`;
|
|
22
|
+
const cached = cache.get(key);
|
|
23
|
+
if (spawnSyncImpl === spawnSync && cached && Date.now() - cached.at < 60000) return cached.result;
|
|
24
|
+
const output = spawnSyncImpl(executable, ["--version"], {
|
|
25
|
+
env, encoding: "utf8", timeout: 4000, maxBuffer: 128 * 1024, stdio: ["ignore", "pipe", "ignore"],
|
|
26
|
+
});
|
|
27
|
+
const version = String(output?.stdout || "").match(/\b(\d+\.\d+\.\d+)\b/)?.[1] || "";
|
|
28
|
+
let result = { supported: output?.status === 0 && Boolean(version) && atLeast(version, baseline), version, baseline };
|
|
29
|
+
if (!result.supported) result.reason = output?.error?.code === "ENOENT" ? "cli_missing" : `requires_tested_version_${baseline}`;
|
|
30
|
+
if (result.supported && agentType === "codex") {
|
|
31
|
+
const help = spawnSyncImpl(executable, ["--help"], { env, encoding: "utf8", timeout: 4000, maxBuffer: 128 * 1024, stdio: ["ignore", "pipe", "ignore"] });
|
|
32
|
+
if (help?.status !== 0 || !String(help.stdout).includes("--remote") || !String(help.stdout).includes("app-server")) {
|
|
33
|
+
result = { ...result, supported: false, reason: "missing_remote_app_server" };
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
if (spawnSyncImpl === spawnSync) cache.set(key, { at: Date.now(), result });
|
|
37
|
+
return result;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
module.exports = { TESTED_BASELINES, probeNativeCapabilities };
|
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const fs = require("fs");
|
|
4
|
+
const os = require("os");
|
|
5
|
+
const path = require("path");
|
|
6
|
+
const { version } = require("../../../package.json");
|
|
7
|
+
const { submissionId, withNativeReceipts } = require("../../coordination/bus/nativeReceipts");
|
|
8
|
+
const net = require("net");
|
|
9
|
+
const http = require("http");
|
|
10
|
+
const { spawn } = require("child_process");
|
|
11
|
+
const WebSocket = require("ws");
|
|
12
|
+
const { getUfooPaths } = require("../../coordination/state/paths");
|
|
13
|
+
const { loadAgentsData, updateAgentsData } = require("../../coordination/state/agentsStore");
|
|
14
|
+
const { persistProviderSession } = require("../../runtime/daemon/providerSessions");
|
|
15
|
+
|
|
16
|
+
function nativeError(message, code = "native_not_ready") {
|
|
17
|
+
return Object.assign(new Error(message), { code });
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const CODEX_COMMANDS_WITHOUT_CHANNELS = new Set([
|
|
21
|
+
"agents", "exec", "e", "review", "login", "logout", "mcp", "plugin",
|
|
22
|
+
"app-server", "remote-control", "app", "completion", "update", "doctor",
|
|
23
|
+
"sandbox", "debug", "apply", "a", "queue", "archive", "delete",
|
|
24
|
+
"migrate-rollouts", "unarchive", "cloud", "exec-server", "features", "help",
|
|
25
|
+
]);
|
|
26
|
+
const CLAUDE_COMMANDS_WITHOUT_CHANNELS = new Set([
|
|
27
|
+
"agents", "auth", "mcp", "plugin", "plugins", "doctor", "install",
|
|
28
|
+
"setup-token", "update", "upgrade", "gateway", "auto-mode", "project", "ultrareview",
|
|
29
|
+
]);
|
|
30
|
+
const CODEX_VALUE_FLAGS = new Set([
|
|
31
|
+
"-c", "--config", "--enable", "--disable", "--remote", "--remote-auth-token-env",
|
|
32
|
+
"-i", "--image", "-m", "--model", "-p", "--profile", "-s", "--sandbox",
|
|
33
|
+
"-C", "--cd", "--add-dir", "-a", "--ask-for-approval", "--local-provider",
|
|
34
|
+
]);
|
|
35
|
+
const CLAUDE_VALUE_FLAGS = new Set([
|
|
36
|
+
"--add-dir", "--agent", "--agents", "--allowedTools", "--allowed-tools",
|
|
37
|
+
"--append-system-prompt", "--append-system-prompt-file", "--betas", "-d", "--debug",
|
|
38
|
+
"--debug-file", "--disallowedTools", "--disallowed-tools", "--effort",
|
|
39
|
+
"--fallback-model", "--file", "--input-format", "--json-schema", "--max-budget-usd",
|
|
40
|
+
"--mcp-config", "--model", "-n", "--name", "--output-format", "--permission-mode",
|
|
41
|
+
"--plugin-dir", "--plugin-url", "--prompt-suggestions", "-r", "--resume",
|
|
42
|
+
"--remote-control", "--remote-control-session-name-prefix", "--session-id",
|
|
43
|
+
"--setting-sources", "--settings", "--system-prompt", "--system-prompt-file",
|
|
44
|
+
"--tools", "-w", "--worktree",
|
|
45
|
+
]);
|
|
46
|
+
|
|
47
|
+
function isInteractiveNativeCommand(agentType, args = []) {
|
|
48
|
+
const separator = args.indexOf("--");
|
|
49
|
+
const options = separator < 0 ? args : args.slice(0, separator);
|
|
50
|
+
if (options.some((arg) => ["--help", "-h", "--version", "-v", "-V"].includes(arg))) return false;
|
|
51
|
+
if (agentType === "codex" && options.some((arg) => /^--remote(?:=|$)/.test(arg))) return false;
|
|
52
|
+
if (agentType === "claude-code" && options.some((arg) => /^(?:-p$|--print(?:=|$)|--input-format(?:=|$)|--safe-mode$)/.test(arg))) return false;
|
|
53
|
+
const valueFlags = agentType === "codex" ? CODEX_VALUE_FLAGS : CLAUDE_VALUE_FLAGS;
|
|
54
|
+
const commands = agentType === "codex" ? CODEX_COMMANDS_WITHOUT_CHANNELS : CLAUDE_COMMANDS_WITHOUT_CHANNELS;
|
|
55
|
+
for (let i = 0; i < options.length; i += 1) {
|
|
56
|
+
if (valueFlags.has(options[i])) { i += 1; continue; }
|
|
57
|
+
if (!String(options[i]).startsWith("-")) return !commands.has(options[i]);
|
|
58
|
+
}
|
|
59
|
+
return true;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function resolveNativeMessageMode({ agentType, args = [], env = process.env,
|
|
63
|
+
stdinIsTTY = process.stdin.isTTY, stdoutIsTTY = process.stdout.isTTY,
|
|
64
|
+
platform = process.platform } = {}) {
|
|
65
|
+
if (!["codex", "claude-code"].includes(agentType) || env.UFOO_NATIVE_MESSAGES === "0") return false;
|
|
66
|
+
if (platform === "win32" || env.UFOO_INTERNAL_AGENT || env.UFOO_DISABLE_PTY === "1") return false;
|
|
67
|
+
if (env.UFOO_FORCE_PTY !== "1" && !(stdinIsTTY && stdoutIsTTY)) return false;
|
|
68
|
+
return isInteractiveNativeCommand(agentType, args);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function stopChild(child) {
|
|
72
|
+
if (child.exitCode !== null) return Promise.resolve();
|
|
73
|
+
return new Promise((resolve) => {
|
|
74
|
+
let killTimer;
|
|
75
|
+
const timer = setTimeout(() => {
|
|
76
|
+
child.kill("SIGKILL");
|
|
77
|
+
killTimer = setTimeout(resolve, 200);
|
|
78
|
+
}, 500);
|
|
79
|
+
child.once("close", () => { clearTimeout(timer); clearTimeout(killTimer); resolve(); });
|
|
80
|
+
child.kill("SIGTERM");
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function setNativeMetadata(projectRoot, subscriber, patch) {
|
|
85
|
+
const file = getUfooPaths(projectRoot).agentsFile;
|
|
86
|
+
updateAgentsData(file, (data) => {
|
|
87
|
+
const meta = data.agents[subscriber];
|
|
88
|
+
if (!meta || meta.status !== "active") throw nativeError("Native receiver has no active host identity");
|
|
89
|
+
Object.assign(meta, patch);
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Claude's variadic options must be extended in place: repeating them can
|
|
94
|
+
// replace configs/channels the caller already supplied.
|
|
95
|
+
function appendVariadic(args, flag, value) {
|
|
96
|
+
const result = [...args];
|
|
97
|
+
const index = result.findIndex((arg) => arg === flag || String(arg).startsWith(`${flag}=`));
|
|
98
|
+
if (index < 0) {
|
|
99
|
+
const separator = result.indexOf("--");
|
|
100
|
+
result.splice(separator < 0 ? result.length : separator, 0, flag, value);
|
|
101
|
+
} else {
|
|
102
|
+
if (result[index] !== flag) result.splice(index, 1, flag, String(result[index]).slice(flag.length + 1));
|
|
103
|
+
let end = index + 1;
|
|
104
|
+
while (end < result.length && !String(result[end]).startsWith("-")) end += 1;
|
|
105
|
+
result.splice(end, 0, value);
|
|
106
|
+
}
|
|
107
|
+
return result;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
class CodexRpc {
|
|
111
|
+
constructor(url, options = {}) {
|
|
112
|
+
this.url = url;
|
|
113
|
+
this.timeoutMs = options.timeoutMs || 10000;
|
|
114
|
+
this.nextId = 0;
|
|
115
|
+
this.pending = new Map();
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async connect() {
|
|
119
|
+
this.ws = new WebSocket(this.url, { handshakeTimeout: this.timeoutMs });
|
|
120
|
+
this.ws.on("message", (raw) => {
|
|
121
|
+
let message;
|
|
122
|
+
try { message = JSON.parse(raw.toString()); } catch { return; }
|
|
123
|
+
const pending = this.pending.get(message.id);
|
|
124
|
+
if (!pending) return;
|
|
125
|
+
clearTimeout(pending.timer);
|
|
126
|
+
this.pending.delete(message.id);
|
|
127
|
+
if (message.error) pending.reject(Object.assign(nativeError(message.error.message), { remoteRejected: true }));
|
|
128
|
+
else pending.resolve(message.result);
|
|
129
|
+
});
|
|
130
|
+
this.ws.on("error", () => {});
|
|
131
|
+
this.ws.on("close", () => {
|
|
132
|
+
for (const pending of this.pending.values()) {
|
|
133
|
+
clearTimeout(pending.timer);
|
|
134
|
+
pending.reject(nativeError("Codex connection closed", "native_outcome_unknown"));
|
|
135
|
+
}
|
|
136
|
+
this.pending.clear();
|
|
137
|
+
});
|
|
138
|
+
await new Promise((resolve, reject) => {
|
|
139
|
+
this.ws.once("open", resolve);
|
|
140
|
+
this.ws.once("error", reject);
|
|
141
|
+
});
|
|
142
|
+
await this.call("initialize", { clientInfo: { name: "ufoo", version }, capabilities: { experimentalApi: true } });
|
|
143
|
+
this.ws.send(JSON.stringify({ method: "initialized", params: {} }));
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
call(method, params) {
|
|
147
|
+
if (this.ws?.readyState !== WebSocket.OPEN) return Promise.reject(nativeError("Codex receiver is disconnected"));
|
|
148
|
+
const id = ++this.nextId;
|
|
149
|
+
return new Promise((resolve, reject) => {
|
|
150
|
+
const timer = setTimeout(() => {
|
|
151
|
+
this.pending.delete(id);
|
|
152
|
+
reject(nativeError(`Codex ${method} response timed out`, "native_outcome_unknown"));
|
|
153
|
+
}, this.timeoutMs);
|
|
154
|
+
this.pending.set(id, { resolve, reject, timer });
|
|
155
|
+
this.ws.send(JSON.stringify({ id, method, params }), (err) => {
|
|
156
|
+
if (!err) return;
|
|
157
|
+
clearTimeout(timer);
|
|
158
|
+
this.pending.delete(id);
|
|
159
|
+
reject(nativeError(err.message, "native_outcome_unknown"));
|
|
160
|
+
});
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
close() { this.ws?.terminate(); }
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async function startCodexHost({ command = "codex", args = [], projectRoot, subscriber, directory, env = process.env, spawnImpl = spawn }) {
|
|
168
|
+
const remote = `unix://${path.join(directory, "codex.sock")}`;
|
|
169
|
+
if (!isInteractiveNativeCommand("codex", args)) throw nativeError("Native messages require an interactive Codex session without --remote");
|
|
170
|
+
// Forward config overrides to the host; model/session flags remain on the TUI.
|
|
171
|
+
const configArgs = [];
|
|
172
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
173
|
+
if (["-c", "--config", "--enable", "--disable"].includes(args[i])) { configArgs.push(args[i], args[++i]); }
|
|
174
|
+
else if (String(args[i]).startsWith("--config=")) configArgs.push(args[i]);
|
|
175
|
+
}
|
|
176
|
+
const child = spawnImpl(command, ["app-server", "--listen", remote, ...configArgs], {
|
|
177
|
+
cwd: projectRoot, env, stdio: ["ignore", "ignore", "pipe"],
|
|
178
|
+
});
|
|
179
|
+
let startupError;
|
|
180
|
+
child.on("error", (err) => { startupError = err; });
|
|
181
|
+
// Consume diagnostics without logging credentials or mixing JSON into the TUI.
|
|
182
|
+
child.stderr?.resume();
|
|
183
|
+
const tuiSocket = path.join(directory, "codex-tui.sock");
|
|
184
|
+
const tuiRemote = `unix://${tuiSocket}`;
|
|
185
|
+
const bridge = http.createServer();
|
|
186
|
+
const wss = new WebSocket.Server({ server: bridge });
|
|
187
|
+
let threadId = "";
|
|
188
|
+
let connected = false;
|
|
189
|
+
let ready = false;
|
|
190
|
+
const readyCallbacks = new Set();
|
|
191
|
+
const setReady = () => {
|
|
192
|
+
ready = connected && Boolean(threadId) && child.exitCode === null && !closing;
|
|
193
|
+
const meta = loadAgentsData(getUfooPaths(projectRoot).agentsFile).agents[subscriber];
|
|
194
|
+
if (meta?.status === "active" && meta.native_delivery_instance === remote) {
|
|
195
|
+
setNativeMetadata(projectRoot, subscriber, { native_delivery_ready: ready });
|
|
196
|
+
}
|
|
197
|
+
if (ready) { for (const callback of readyCallbacks) callback(); readyCallbacks.clear(); }
|
|
198
|
+
};
|
|
199
|
+
let closing = false;
|
|
200
|
+
const close = async () => {
|
|
201
|
+
if (closing) return;
|
|
202
|
+
closing = true;
|
|
203
|
+
connected = false;
|
|
204
|
+
setReady();
|
|
205
|
+
for (const ws of wss.clients) ws.terminate();
|
|
206
|
+
await new Promise((resolve) => wss.close(resolve));
|
|
207
|
+
if (bridge.listening) await new Promise((resolve) => bridge.close(resolve));
|
|
208
|
+
await stopChild(child);
|
|
209
|
+
};
|
|
210
|
+
try {
|
|
211
|
+
const deadline = Date.now() + 10000;
|
|
212
|
+
do {
|
|
213
|
+
if (startupError || child.exitCode !== null) throw startupError || nativeError("Codex app-server exited during startup");
|
|
214
|
+
if (fs.existsSync(path.join(directory, "codex.sock"))) break;
|
|
215
|
+
await new Promise((resolve) => setTimeout(resolve, 25));
|
|
216
|
+
} while (Date.now() < deadline);
|
|
217
|
+
if (!fs.existsSync(path.join(directory, "codex.sock"))) throw nativeError("Codex app-server socket did not become available");
|
|
218
|
+
setNativeMetadata(projectRoot, subscriber, { native_delivery: "codex_queue", native_delivery_ready: false, native_delivery_instance: remote });
|
|
219
|
+
child.once("exit", () => { connected = false; setReady(); });
|
|
220
|
+
wss.on("connection", (frontend) => {
|
|
221
|
+
if (connected || closing) { frontend.close(1008, "A TUI is already attached"); return; }
|
|
222
|
+
connected = true;
|
|
223
|
+
const requests = new Map();
|
|
224
|
+
const upstream = new WebSocket(`ws+unix://${path.join(directory, "codex.sock")}:/`);
|
|
225
|
+
const buffered = [];
|
|
226
|
+
const forward = (data, binary) => {
|
|
227
|
+
if (upstream.readyState === WebSocket.OPEN) upstream.send(data, { binary });
|
|
228
|
+
else buffered.push({ data, binary });
|
|
229
|
+
};
|
|
230
|
+
frontend.on("message", (data, binary) => {
|
|
231
|
+
try {
|
|
232
|
+
const message = JSON.parse(data.toString());
|
|
233
|
+
if (["thread/start", "thread/resume", "thread/fork"].includes(message.method)) {
|
|
234
|
+
requests.set(message.id, { ephemeral: message.params?.ephemeral === true });
|
|
235
|
+
}
|
|
236
|
+
} catch { /* forward frames unchanged */ }
|
|
237
|
+
forward(data, binary);
|
|
238
|
+
});
|
|
239
|
+
upstream.on("open", () => { for (const item of buffered) upstream.send(item.data, { binary: item.binary }); buffered.length = 0; });
|
|
240
|
+
upstream.on("message", (data, binary) => {
|
|
241
|
+
let boundThread = false;
|
|
242
|
+
try {
|
|
243
|
+
const message = JSON.parse(data.toString());
|
|
244
|
+
if (requests.has(message.id)) {
|
|
245
|
+
const request = requests.get(message.id);
|
|
246
|
+
requests.delete(message.id);
|
|
247
|
+
const id = message.result?.thread?.id;
|
|
248
|
+
// The TUI also starts temporary structured-output threads. They
|
|
249
|
+
// cannot receive queued work and must not replace its user thread.
|
|
250
|
+
if (id && !request.ephemeral && message.result.thread.ephemeral !== true) {
|
|
251
|
+
if (!persistProviderSession(projectRoot, subscriber, { sessionId: id, source: "codex-native-app-server" })) {
|
|
252
|
+
throw nativeError("Cannot bind this Codex thread to the host identity");
|
|
253
|
+
}
|
|
254
|
+
threadId = id;
|
|
255
|
+
boundThread = true;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
} catch (err) {
|
|
259
|
+
if (err.code === "native_not_ready") { frontend.close(1008, err.message); upstream.terminate(); return; }
|
|
260
|
+
}
|
|
261
|
+
if (frontend.readyState === WebSocket.OPEN) frontend.send(data, { binary }, (err) => { if (!err && boundThread) setReady(); });
|
|
262
|
+
});
|
|
263
|
+
frontend.on("error", () => {});
|
|
264
|
+
upstream.on("error", () => frontend.terminate());
|
|
265
|
+
frontend.once("close", () => { connected = false; setReady(); upstream.terminate(); });
|
|
266
|
+
upstream.once("close", () => frontend.terminate());
|
|
267
|
+
});
|
|
268
|
+
await new Promise((resolve, reject) => { bridge.once("error", reject); bridge.listen(tuiSocket, resolve); });
|
|
269
|
+
fs.chmodSync(tuiSocket, 0o600);
|
|
270
|
+
// Observe the actual TUI's thread response without changing any frames.
|
|
271
|
+
// Precreating a thread then resuming it fails before its first user turn:
|
|
272
|
+
// Codex has not materialized that thread's rollout yet.
|
|
273
|
+
return {
|
|
274
|
+
args: ["--remote", tuiRemote, ...args],
|
|
275
|
+
onReady(callback) { if (ready) callback(); else readyCallbacks.add(callback); },
|
|
276
|
+
async send(request) {
|
|
277
|
+
if (!ready) throw nativeError("Codex TUI has not confirmed host readiness");
|
|
278
|
+
const receiver = new CodexRpc(`ws+unix://${path.join(directory, "codex.sock")}:/`);
|
|
279
|
+
let submitted = false;
|
|
280
|
+
try {
|
|
281
|
+
await receiver.connect();
|
|
282
|
+
submitted = true;
|
|
283
|
+
const result = await receiver.call("thread/queue/add", {
|
|
284
|
+
threadId,
|
|
285
|
+
input: [{ type: "text", text: request.command, text_elements: [] }],
|
|
286
|
+
clientUserMessageId: submissionId(`${subscriber}:${request.deliveryId}`),
|
|
287
|
+
});
|
|
288
|
+
if (!result?.queuedSubmission) throw nativeError("Codex returned no queue acceptance", "native_outcome_unknown");
|
|
289
|
+
return { queued: true, thread_id: threadId };
|
|
290
|
+
} catch (err) {
|
|
291
|
+
if (!submitted) throw nativeError(`Codex receiver unavailable: ${err.message}`);
|
|
292
|
+
throw err;
|
|
293
|
+
} finally { receiver.close(); }
|
|
294
|
+
},
|
|
295
|
+
close,
|
|
296
|
+
};
|
|
297
|
+
} catch (err) { await close(); throw err; }
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
function sendChannel(socketPath, request) {
|
|
301
|
+
return new Promise((resolve, reject) => {
|
|
302
|
+
const client = net.createConnection(socketPath);
|
|
303
|
+
let buffer = "";
|
|
304
|
+
let sent = false;
|
|
305
|
+
let settled = false;
|
|
306
|
+
const finish = (err, result) => {
|
|
307
|
+
if (settled) return;
|
|
308
|
+
settled = true;
|
|
309
|
+
clearTimeout(timer);
|
|
310
|
+
client.destroy();
|
|
311
|
+
if (err) reject(err); else resolve(result);
|
|
312
|
+
};
|
|
313
|
+
const timer = setTimeout(() => finish(nativeError("Claude channel response timed out", sent ? "native_outcome_unknown" : "native_not_ready")), 4000);
|
|
314
|
+
client.once("connect", () => { sent = true; client.write(`${JSON.stringify(request)}\n`); });
|
|
315
|
+
client.on("data", (chunk) => {
|
|
316
|
+
buffer += chunk;
|
|
317
|
+
if (!buffer.includes("\n")) return;
|
|
318
|
+
try {
|
|
319
|
+
const result = JSON.parse(buffer.slice(0, buffer.indexOf("\n")));
|
|
320
|
+
finish(result.ok ? null : nativeError(result.error, result.code), result);
|
|
321
|
+
} catch (err) { finish(nativeError(err.message, "native_outcome_unknown")); }
|
|
322
|
+
});
|
|
323
|
+
client.once("error", (err) => finish(nativeError(err.message, sent ? "native_outcome_unknown" : "native_not_ready")));
|
|
324
|
+
client.once("end", () => { if (!buffer.includes("\n")) finish(nativeError("Claude channel closed without a receipt", "native_outcome_unknown")); });
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
async function prepareNativeMessages({ agentType, command, args, projectRoot, subscriber, env = process.env }) {
|
|
329
|
+
if (process.platform === "win32") throw nativeError("Native message sockets currently require macOS or Linux");
|
|
330
|
+
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "ufn-"));
|
|
331
|
+
fs.chmodSync(directory, 0o700);
|
|
332
|
+
let backend;
|
|
333
|
+
try {
|
|
334
|
+
if (agentType === "codex") {
|
|
335
|
+
backend = await startCodexHost({ command, args, projectRoot, subscriber, directory, env });
|
|
336
|
+
} else if (agentType === "claude-code") {
|
|
337
|
+
if (args.some((arg) => /^(?:-p$|--print(?:=|$)|--input-format(?:=|$)|--safe-mode$)/.test(arg))) throw nativeError("Claude channels require an interactive session with MCP enabled");
|
|
338
|
+
const channelSocket = path.join(directory, "claude.sock");
|
|
339
|
+
setNativeMetadata(projectRoot, subscriber, { native_delivery: "claude_channel", native_delivery_ready: false, native_delivery_instance: channelSocket });
|
|
340
|
+
const config = JSON.stringify({ mcpServers: { ufoo_channel: {
|
|
341
|
+
command: process.execPath,
|
|
342
|
+
args: [path.resolve(__dirname, "../../../bin/ufoo.js"), "mcp", "channel"],
|
|
343
|
+
} } });
|
|
344
|
+
backend = {
|
|
345
|
+
args: appendVariadic(appendVariadic(args, "--mcp-config", config), "--dangerously-load-development-channels", "server:ufoo_channel"),
|
|
346
|
+
env: { UFOO_NATIVE_CHANNEL_SOCK: channelSocket },
|
|
347
|
+
send: (request) => sendChannel(channelSocket, request),
|
|
348
|
+
close: async () => {},
|
|
349
|
+
};
|
|
350
|
+
} else throw nativeError(`Native messages are not supported for ${agentType}`);
|
|
351
|
+
|
|
352
|
+
backend.send = withNativeReceipts({ projectRoot, subscriber, send: backend.send });
|
|
353
|
+
const originalClose = backend.close;
|
|
354
|
+
backend.close = async () => {
|
|
355
|
+
await originalClose();
|
|
356
|
+
fs.rmSync(directory, { recursive: true, force: true });
|
|
357
|
+
};
|
|
358
|
+
return backend;
|
|
359
|
+
} catch (err) { fs.rmSync(directory, { recursive: true, force: true }); throw err; }
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
module.exports = { CodexRpc, startCodexHost, prepareNativeMessages, resolveNativeMessageMode, setNativeMetadata, submissionId, sendChannel, nativeError };
|