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
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const fs = require("fs");
|
|
4
|
+
const path = require("path");
|
|
5
|
+
const { createResourceLease } = require("../../agents/runtime/tasks/resourceLease");
|
|
6
|
+
|
|
7
|
+
function createWorkspaceAccess({ projectRoot, externalWriters = () => [] } = {}) {
|
|
8
|
+
const root = fs.realpathSync(projectRoot);
|
|
9
|
+
const key = (workspaceRoot) => fs.realpathSync(workspaceRoot || root);
|
|
10
|
+
const stores = new Map();
|
|
11
|
+
function storeFor(workspaceRoot) {
|
|
12
|
+
const workspace = key(workspaceRoot);
|
|
13
|
+
if (!stores.has(workspace)) stores.set(workspace, createResourceLease({ file: path.join(workspace, ".ufoo", "agent", "runtime", "workspace-leases.json") }));
|
|
14
|
+
return stores.get(workspace);
|
|
15
|
+
}
|
|
16
|
+
// All hosts accessing the same directory use its lease, including a native
|
|
17
|
+
// ucode opened directly in a linked worktree.
|
|
18
|
+
const leases = Object.freeze(Object.fromEntries(["acquire", "release", "run"].map((method) => [method,
|
|
19
|
+
(args, ...rest) => storeFor(args.key)[method]({ ...args, key: key(args.key) }, ...rest)])));
|
|
20
|
+
return Object.freeze({
|
|
21
|
+
leases,
|
|
22
|
+
async run(context, operation) {
|
|
23
|
+
if (!["write", "edit", "bash"].includes(context.tool)) return operation();
|
|
24
|
+
const workspace = key(context.workspaceRoot);
|
|
25
|
+
const writers = workspace === root ? externalWriters(context) : [];
|
|
26
|
+
if (writers.length) return { ok: false, code: "workspace_busy", error: "Workers own or may write this workspace. Delegate to them, wait, read files, or use an isolated worktree. Do not close workers to bypass this lease.", owners: writers };
|
|
27
|
+
return leases.run({ key: workspace, ownerId: context.taskRunId || context.sessionId || `process-${process.pid}`, signal: context.signal }, operation);
|
|
28
|
+
},
|
|
29
|
+
async runTask(context, operation) {
|
|
30
|
+
const workspace = key(context.workspaceRoot);
|
|
31
|
+
return leases.run({ key: workspace, ownerId: context.taskRunId, signal: context.signal, wait: true }, operation);
|
|
32
|
+
},
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
module.exports = { createWorkspaceAccess };
|
|
@@ -1,10 +1,3 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
|
|
3
|
-
module.exports =
|
|
4
|
-
...require("./flags"),
|
|
5
|
-
...require("./gateRouter"),
|
|
6
|
-
...require("./launchRouting"),
|
|
7
|
-
...require("./routerFastPath"),
|
|
8
|
-
...require("./routerFinalize"),
|
|
9
|
-
...require("./shadowGuard"),
|
|
10
|
-
};
|
|
3
|
+
module.exports = require("./launchRouting");
|
|
@@ -35,7 +35,7 @@ function normalizeLaunchAgentForNickname(agent = "") {
|
|
|
35
35
|
if (raw === "claude" || raw === "claude-code" || raw === "uclaude") return "claude";
|
|
36
36
|
if (raw === "codex" || raw === "ucodex") return "codex";
|
|
37
37
|
if (raw === "grok" || raw === "ugrok" || raw === "grok-build" || raw === "xai") return "grok";
|
|
38
|
-
if (raw === "
|
|
38
|
+
if (raw === "ucode") return "ucode";
|
|
39
39
|
return "";
|
|
40
40
|
}
|
|
41
41
|
|
|
@@ -9,7 +9,9 @@ function resolveSoloAgentType(config = {}, requestedAgent = "") {
|
|
|
9
9
|
if (requested === "claude" || requested === "uclaude" || requested === "claude-code") return "claude";
|
|
10
10
|
if (requested === "codex" || requested === "ucodex" || requested === "openai") return "codex";
|
|
11
11
|
if (requested === "grok" || requested === "ugrok" || requested === "grok-build" || requested === "xai") return "grok";
|
|
12
|
-
if (requested === "ucode"
|
|
12
|
+
if (requested === "ucode") return "ucode";
|
|
13
|
+
|
|
14
|
+
if (requested) return "";
|
|
13
15
|
|
|
14
16
|
const provider = asTrimmedString(config && config.agentProvider).toLowerCase();
|
|
15
17
|
if (provider === "claude-cli") return "claude";
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const INTERNAL_AGENT_TYPES = Object.freeze(["codex", "claude", "ucode"]);
|
|
4
|
+
|
|
5
|
+
function normalizeInternalAgentType(value = "") {
|
|
6
|
+
const type = String(value || "").trim().toLowerCase();
|
|
7
|
+
if (type === "claude-code") return "claude";
|
|
8
|
+
return INTERNAL_AGENT_TYPES.includes(type) ? type : "";
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function isInternalAgentMeta(meta = {}) {
|
|
12
|
+
if (!meta || String(meta.launch_mode || meta.launchMode || "").trim().toLowerCase() !== "internal") return false;
|
|
13
|
+
return Boolean(normalizeInternalAgentType(meta.agent_type || meta.type || String(meta.id || "").split(":")[0]));
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function isInternalDashboardEvent(data = {}, getMeta = () => null) {
|
|
17
|
+
const agentId = data.event === "activity_state_changed"
|
|
18
|
+
? data.subscriber || data.publisher
|
|
19
|
+
: data.report?.agent_id || data.publisher;
|
|
20
|
+
if (agentId === "ufoo-agent" || String(agentId || "").endsWith(":ufoo-agent")) {
|
|
21
|
+
return !data.target || data.target === "ufoo-agent" || isInternalAgentMeta(getMeta(data.target));
|
|
22
|
+
}
|
|
23
|
+
return isInternalAgentMeta(getMeta(agentId));
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
module.exports = { INTERNAL_AGENT_TYPES, normalizeInternalAgentType, isInternalAgentMeta, isInternalDashboardEvent };
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
const IPC_REQUEST_TYPES = {
|
|
4
4
|
STATUS: "status",
|
|
5
5
|
PROMPT: "prompt",
|
|
6
|
+
AGENT_RUNTIME: "agent_runtime",
|
|
6
7
|
CRON: "cron",
|
|
7
8
|
BUS_SEND: "bus_send",
|
|
8
9
|
BUS_WATCH: "bus_watch",
|
|
@@ -30,6 +31,8 @@ const IPC_REQUEST_TYPES = {
|
|
|
30
31
|
const IPC_RESPONSE_TYPES = {
|
|
31
32
|
STATUS: "status",
|
|
32
33
|
RESPONSE: "response",
|
|
34
|
+
RUNTIME_EVENT: "runtime_event",
|
|
35
|
+
RUNTIME_RESULT: "runtime_result",
|
|
33
36
|
BUS: "bus",
|
|
34
37
|
ERROR: "error",
|
|
35
38
|
BUS_SEND_OK: "bus_send_ok",
|
|
@@ -9,10 +9,18 @@
|
|
|
9
9
|
|
|
10
10
|
const PROTOCOL = "ufoo-ui/1";
|
|
11
11
|
|
|
12
|
-
// Capability advertised by clients that can render
|
|
13
|
-
//
|
|
14
|
-
// "multi" | "side"). "side" is not a user-facing mode name.
|
|
12
|
+
// Capability advertised by clients that can render internal agent panes.
|
|
13
|
+
// window.set.mode is main | side | multi, independently of pane membership.
|
|
15
14
|
const MULTI_FRAMES_CAPABILITY = "multi-frames-v1";
|
|
15
|
+
const WINDOW_MODES_CAPABILITY = "window-modes-v1";
|
|
16
|
+
|
|
17
|
+
// Internal input uses an explicit agent_id and complete input/cursor draft.
|
|
18
|
+
// multi.raw.input_revision increases per child edit; submit=true commits that
|
|
19
|
+
// same draft. multi.pane.frame echoes input_revision, separately from transcript
|
|
20
|
+
// revision. Older echoes must not overwrite local edits. Frame entries are
|
|
21
|
+
// semantic and remain valid across viewport revisions. Ready/resync replays all
|
|
22
|
+
// visible pane frames, including quiet agents. input.submit.input_target=main
|
|
23
|
+
// explicitly clears a previous footer target; unresolved targets never fall back.
|
|
16
24
|
|
|
17
25
|
const KINDS = Object.freeze([
|
|
18
26
|
"hello",
|
|
@@ -31,8 +39,6 @@ const COMMAND_NAMES = Object.freeze([
|
|
|
31
39
|
"agent.select",
|
|
32
40
|
"agent.open",
|
|
33
41
|
"agent.close",
|
|
34
|
-
"agent.view.submit",
|
|
35
|
-
"agent.view.exit",
|
|
36
42
|
"project.switch",
|
|
37
43
|
"project.close",
|
|
38
44
|
"project.return_controller",
|
|
@@ -41,13 +47,16 @@ const COMMAND_NAMES = Object.freeze([
|
|
|
41
47
|
"command.execute",
|
|
42
48
|
"interaction.respond",
|
|
43
49
|
"settings.set",
|
|
44
|
-
"
|
|
50
|
+
"settings.open",
|
|
45
51
|
"ui.resync.request",
|
|
46
52
|
"app.exit",
|
|
47
|
-
"
|
|
53
|
+
"window.set",
|
|
54
|
+
"window.cycle",
|
|
48
55
|
"multi.focus",
|
|
49
56
|
"multi.viewport",
|
|
50
57
|
"multi.raw",
|
|
58
|
+
"multi.scroll",
|
|
59
|
+
"multi.expand",
|
|
51
60
|
]);
|
|
52
61
|
|
|
53
62
|
const EVENT_NAMES = Object.freeze([
|
|
@@ -75,18 +84,14 @@ const EVENT_NAMES = Object.freeze([
|
|
|
75
84
|
"tool.group",
|
|
76
85
|
"settings.snapshot",
|
|
77
86
|
"prompt.apply_paste",
|
|
87
|
+
"prompt.set_text",
|
|
88
|
+
"prompt.restore",
|
|
78
89
|
"prompt.set_prefix",
|
|
79
90
|
"attachments.set",
|
|
80
91
|
"usage.set",
|
|
81
|
-
"agent.view.open",
|
|
82
|
-
"agent.view.append",
|
|
83
|
-
"agent.view.status",
|
|
84
|
-
"agent.view.close",
|
|
85
|
-
"ui.suspend.prepare",
|
|
86
|
-
"ui.resume",
|
|
87
92
|
"connection.set",
|
|
88
93
|
"error",
|
|
89
|
-
"
|
|
94
|
+
"window.set",
|
|
90
95
|
"multi.pane.frame",
|
|
91
96
|
]);
|
|
92
97
|
|
|
@@ -131,9 +136,6 @@ function validateEnvelope(raw) {
|
|
|
131
136
|
if (!KINDS.includes(String(raw.kind || ""))) {
|
|
132
137
|
errors.push(`invalid kind "${raw.kind}"`);
|
|
133
138
|
}
|
|
134
|
-
if (raw.kind === "command" && raw.name && !COMMAND_NAMES.includes(String(raw.name))) {
|
|
135
|
-
// Additive: unknown commands are soft-fail for forward compat.
|
|
136
|
-
}
|
|
137
139
|
if (raw.payload != null && typeof raw.payload !== "object") {
|
|
138
140
|
errors.push("payload must be an object");
|
|
139
141
|
}
|
|
@@ -181,6 +183,7 @@ function createSeqCounter(start = 0) {
|
|
|
181
183
|
module.exports = {
|
|
182
184
|
PROTOCOL,
|
|
183
185
|
MULTI_FRAMES_CAPABILITY,
|
|
186
|
+
WINDOW_MODES_CAPABILITY,
|
|
184
187
|
KINDS,
|
|
185
188
|
COMMAND_NAMES,
|
|
186
189
|
EVENT_NAMES,
|
|
@@ -0,0 +1,407 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const fs = require("fs");
|
|
4
|
+
const path = require("path");
|
|
5
|
+
const { createHash, randomUUID } = require("crypto");
|
|
6
|
+
const { stableStringify } = require("../../agents/runtime/core/stableJson");
|
|
7
|
+
const { resolveToolBudget, resolveTaskTimeoutMs } = require("../../agents/runtime/core/executionBudget");
|
|
8
|
+
const { spawnSync } = require("child_process");
|
|
9
|
+
const { createAgentRuntime, createRuntimeStore, createTaskScheduler } = require("../../agents/runtime");
|
|
10
|
+
const { createMainCapabilities, createGlobalCapabilities } = require("../../agents/capabilities");
|
|
11
|
+
const { createCodingCapability } = require("../../agents/capabilities/coding");
|
|
12
|
+
const { createMainPlanningCapability } = require("../../agents/capabilities/planning/main");
|
|
13
|
+
const { createSkillsCapability } = require("../../agents/capabilities/skills");
|
|
14
|
+
const { createAgentManagementService } = require("../../agents/capabilities/agentManagement/service");
|
|
15
|
+
const { executeControllerTool } = require("../../agents/controller/controllerToolExecutor");
|
|
16
|
+
const { TOOL_PERMISSIONS } = require("../../agents/capabilities/coordination");
|
|
17
|
+
const { getNativeTransport } = require("../../agents/providers/nativeTransport");
|
|
18
|
+
const { resolveRuntimeConfig } = require("../../agents/providers/runtimeConfig");
|
|
19
|
+
const { resolveUpstreamRuntime, normalizeProvider } = require("../../agents/providers/upstreamRuntime");
|
|
20
|
+
const { loadConfig, defaultAgentModelForProvider, sameModelProvider } = require("../../config");
|
|
21
|
+
const mainProfile = require("../../agents/profiles/main");
|
|
22
|
+
const globalProfile = require("../../agents/profiles/globalRouter");
|
|
23
|
+
const { buildMainAgentPrompt, buildCodingTaskPrompt } = require("../../agents/prompts/mainAgent");
|
|
24
|
+
const { resolveUserInteraction, parseUserInteractionInput } = require("../../code/context/userInteraction");
|
|
25
|
+
const { materializeAnswerToolResult } = require("../../code/protocol");
|
|
26
|
+
const { createWorkspaceAccess } = require("../../coordination/state/workspaceAccess");
|
|
27
|
+
const { buildCachedMemoryPrefix } = require("../../coordination/memory");
|
|
28
|
+
const { readBusSummaryHandler } = require("../../tools/handlers/readBusSummary");
|
|
29
|
+
const { isInternalAgentMeta } = require("../contracts/agentMode");
|
|
30
|
+
const { getUfooPaths } = require("../../coordination/state/paths");
|
|
31
|
+
const { loadAgentsData } = require("../../coordination/state/agentsStore");
|
|
32
|
+
const { readOpenDecisionsHandler } = require("../../tools/handlers/readOpenDecisions");
|
|
33
|
+
const { listProjectRuntimes, isGlobalControllerProjectRoot } = require("../projects");
|
|
34
|
+
const { canonicalProjectRoot, buildProjectId } = require("../projects/projectId");
|
|
35
|
+
const { resolveWorkspacePath } = require("../../code/tools/common");
|
|
36
|
+
const { listControllerInboxEntries } = require("../../coordination/report/store");
|
|
37
|
+
const { redactSecrets } = require("../privacy/redactor");
|
|
38
|
+
const { createContextManager } = require("../../agents/runtime/context/compaction");
|
|
39
|
+
const { replayHistory } = require("../../agents/runtime/context/replayHistory");
|
|
40
|
+
|
|
41
|
+
const hash = (value) => createHash("sha256").update(value).digest("hex").slice(0, 32);
|
|
42
|
+
const safeId = (value) => /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,100}$/.test(value || "");
|
|
43
|
+
const MAIN_GRANTS = ["workspace.read", "workspace.write", "workspace.execute", "interaction.request", "coordination.read", "coordination.write", "agents.manage", "memory.write", "tasks.accept", "tasks.execute", "groups.manage", "schedules.manage"];
|
|
44
|
+
|
|
45
|
+
function resolveTaskWorkspace(projectRoot, requested = "") {
|
|
46
|
+
const target = canonicalProjectRoot(requested || projectRoot);
|
|
47
|
+
if (target === projectRoot) return target;
|
|
48
|
+
const top = spawnSync("git", ["rev-parse", "--show-toplevel"], { cwd: projectRoot, encoding: "utf8", timeout: 3000 });
|
|
49
|
+
if (top.status !== 0 || canonicalProjectRoot(top.stdout.trim()) !== projectRoot) throw new Error("task workspace is outside the project grant");
|
|
50
|
+
const result = spawnSync("git", ["worktree", "list", "--porcelain", "-z"], { cwd: projectRoot, encoding: "utf8", timeout: 3000 });
|
|
51
|
+
const roots = result.status === 0 ? result.stdout.split("\0").filter((item) => item.startsWith("worktree ")).map((item) => canonicalProjectRoot(item.slice(9))) : [];
|
|
52
|
+
if (!roots.includes(target)) throw new Error("task workspace must be a verified worktree of this project");
|
|
53
|
+
return target;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Project-owned runtime instances. A client disconnect never owns their cancellation. */
|
|
57
|
+
function createAgentHost({ projectRoot, provider, model, ports = {}, onEvent = () => {}, log = () => {},
|
|
58
|
+
resolveProvider = resolveUpstreamRuntime, transportFactory = getNativeTransport, maxConcurrent = 2, contextPolicy = {} } = {}) {
|
|
59
|
+
const root = canonicalProjectRoot(projectRoot);
|
|
60
|
+
const projectId = buildProjectId(root);
|
|
61
|
+
const global = isGlobalControllerProjectRoot(root);
|
|
62
|
+
const sessions = new Map();
|
|
63
|
+
const children = new Map();
|
|
64
|
+
const stores = new Map();
|
|
65
|
+
const scheduler = createTaskScheduler({ maxConcurrent });
|
|
66
|
+
const conversationScheduler = createTaskScheduler({ maxConcurrent: 2, maxQueued: 128 });
|
|
67
|
+
const control = createRuntimeStore({ workspaceRoot: root, namespace: "main-control", sessionId: "control", redact: redactSecrets });
|
|
68
|
+
let closed = false;
|
|
69
|
+
const publicEvent = (event) => {
|
|
70
|
+
const safe = { ...event };
|
|
71
|
+
delete safe.args;
|
|
72
|
+
if (safe.result) safe.result = safe.type === "tool.completed"
|
|
73
|
+
? { ok: safe.result.ok, code: safe.result.code, error: safe.result.error, toolCallId: safe.toolCallId }
|
|
74
|
+
: { text: safe.result.text, usage: safe.result.usage, executionState: { pendingUserInteraction: safe.result.executionState?.pendingUserInteraction || null } };
|
|
75
|
+
return redactSecrets({ version: 1, projectId, projectRoot: root, agentId: "ufoo-agent", global, ...safe });
|
|
76
|
+
};
|
|
77
|
+
const publish = (event) => { try { const pending = onEvent(publicEvent(event)); if (pending && pending.catch) pending.catch((error) => log(error.message)); } catch (error) { log(error.message); } };
|
|
78
|
+
const jobs = () => control.read().capabilityState["task-execution"]?.value?.jobs || {};
|
|
79
|
+
function updateJobs(mutator) {
|
|
80
|
+
control.transaction((state) => {
|
|
81
|
+
const value = state.capabilityState["task-execution"]?.value || { jobs: {} };
|
|
82
|
+
mutator(value.jobs);
|
|
83
|
+
return [{ type: "capability.state_committed", capabilityId: "task-execution", version: 1, value }];
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
function validateEvidence(evidence, context, after = "") {
|
|
87
|
+
const store = stores.get(context.sessionId);
|
|
88
|
+
return Array.isArray(evidence) && evidence.length > 0 && store && evidence.every((id) => store.events().some((event) =>
|
|
89
|
+
event.type === "tool.completed" && event.toolCallId === id && event.taskRunId === context.taskRunId
|
|
90
|
+
&& event.toolName === "bash" && event.result?.ok === true && (!after || event.time >= after)));
|
|
91
|
+
}
|
|
92
|
+
const workspaceAccess = createWorkspaceAccess({ projectRoot: root, externalWriters(context) {
|
|
93
|
+
const tasks = Object.values(management.snapshot().tasks);
|
|
94
|
+
const pending = tasks.filter((task) => ["planning", "awaiting_registration"].includes(task.status) && !task.workerId).map((task) => task.taskId);
|
|
95
|
+
return [...pending, ...readBusSummaryHandler({ projectRoot: root, internalAgentsOnly: true }).active_agents.filter((agent) => {
|
|
96
|
+
if (agent.id === context.agentId || agent.id === "ufoo-agent") return false;
|
|
97
|
+
const assigned = tasks.filter((task) => task.workerId === agent.id);
|
|
98
|
+
return !assigned.length || assigned.some((task) => ["planning", "queued", "delivered", "delivery_uncertain", "running"].includes(task.status))
|
|
99
|
+
|| ["working", "starting", "running"].includes(agent.activity_state);
|
|
100
|
+
}).map((agent) => agent.id)];
|
|
101
|
+
} });
|
|
102
|
+
const management = createAgentManagementService({ store: control,
|
|
103
|
+
resolveTarget(target) {
|
|
104
|
+
const matches = readBusSummaryHandler({ projectRoot: root, internalAgentsOnly: true }).active_agents.filter((agent) => agent.id !== "ufoo-agent"
|
|
105
|
+
&& [agent.id, agent.nickname, agent.scoped_nickname, agent.display_nickname].includes(target));
|
|
106
|
+
return matches.length === 1 ? matches[0].id : "";
|
|
107
|
+
},
|
|
108
|
+
launch: async (args) => {
|
|
109
|
+
const rows = await coordinatedOps(root, [{ action: "launch", ...args }], ports.processManager);
|
|
110
|
+
return { ok: Array.isArray(rows) && rows.some((row) => row.action === "launch" && row.ok !== false), ops_results: rows };
|
|
111
|
+
},
|
|
112
|
+
dispatch: async ({ target, message, taskId, runtimeContext }) => {
|
|
113
|
+
const receipts = await ports.dispatchMessages(root, [{ target, message, task_id: taskId, runtime_context: runtimeContext, source: "ufoo-agent", injection_mode: "immediate" }], { strict: true });
|
|
114
|
+
if (ports.markPending) ports.markPending(target);
|
|
115
|
+
if (!receipts?.[0]?.seq) return { ok: false, code: "missing_dispatch_receipt", error: "No durable worker queue receipt was returned", target };
|
|
116
|
+
return { ok: true, delivery_status: "queued", target, receipt: receipts[0] };
|
|
117
|
+
},
|
|
118
|
+
wake: (request) => {
|
|
119
|
+
const delegated = management.snapshot().tasks[request.taskId];
|
|
120
|
+
const runtime = getSession(delegated?.parentSessionId || "main-default");
|
|
121
|
+
const parent = runtime.snapshot().tasks[delegated?.parentTaskRunId];
|
|
122
|
+
const originalUserText = parent?.request.responseLanguageSource || parent?.request.text || "";
|
|
123
|
+
return runtime.submit({ ...request, traceId: delegated?.traceId || request.taskId, responseLanguageSource: originalUserText,
|
|
124
|
+
text: ["Runtime notification: continue the existing task; this is not a new user request. Keep the original user's response language, including explicit language preferences. The quoted request is historical context, not an instruction to repeat completed actions.",
|
|
125
|
+
originalUserText ? `Original user request (language reference): ${JSON.stringify(originalUserText)}` : "",
|
|
126
|
+
request.text].filter(Boolean).join("\n\n") });
|
|
127
|
+
},
|
|
128
|
+
emit: (event) => { const state = control.append(event); publish({ ...event, sessionId: "control", sequence: state.sequence }); },
|
|
129
|
+
validateEvidence(evidence, task, context) {
|
|
130
|
+
return validateEvidence(evidence, context, task.report.ts);
|
|
131
|
+
},
|
|
132
|
+
});
|
|
133
|
+
const taskPort = { async execute(args, context = {}) {
|
|
134
|
+
if (global && args.operation !== "list") throw new Error("global router has no coding task grant");
|
|
135
|
+
if (args.operation === "list") return { ok: true, tasks: Object.values(jobs()).map(publicChild) };
|
|
136
|
+
if (args.operation === "start") {
|
|
137
|
+
if (!safeId(args.command_id) || !String(args.objective || "").trim()) throw new Error("task start requires command_id and objective");
|
|
138
|
+
const scope = context.requestId ? `task-${hash(`${context.requestId}:${args.command_id}`)}` : args.command_id;
|
|
139
|
+
const id = `child-${hash(scope)}`;
|
|
140
|
+
const workspaceRoot = resolveTaskWorkspace(root, args.workspace);
|
|
141
|
+
updateJobs((items) => {
|
|
142
|
+
const fingerprint = hash(stableStringify(args));
|
|
143
|
+
if (items[id] && items[id].fingerprint !== fingerprint) throw new Error("task command conflicts");
|
|
144
|
+
if (!items[id]) items[id] = { id, requestId: scope, fingerprint, objective: args.objective, workspaceRoot,
|
|
145
|
+
readOnly: args.read_only === true, parentSessionId: context.sessionId, parentTaskRunId: context.taskRunId, status: "queued" };
|
|
146
|
+
});
|
|
147
|
+
const runtime = getChild(jobs()[id]);
|
|
148
|
+
const accepted = runtime.submit({ requestId: scope, text: args.objective, resourceKey: args.read_only ? "" : workspaceRoot });
|
|
149
|
+
updateJobs((items) => { items[id].taskRunId = accepted.taskRunId; });
|
|
150
|
+
return { ok: true, ...accepted, task: publicChild(jobs()[id]) };
|
|
151
|
+
}
|
|
152
|
+
const job = Object.values(jobs()).find((item) => item.taskRunId === args.task_run_id || item.id === args.task_run_id);
|
|
153
|
+
if (!job && args.operation === "inspect") {
|
|
154
|
+
for (const [sessionId, runtime] of sessions) {
|
|
155
|
+
const task = runtime.snapshot().tasks[args.task_run_id];
|
|
156
|
+
if (task) return { ok: true, task: { taskRunId: task.taskRunId, sessionId, status: task.status, error: task.error,
|
|
157
|
+
summary: task.result?.text?.slice(-6000) || "", effects: task.effects, interaction: task.result?.executionState?.pendingUserInteraction || null } };
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
if (!job) throw new Error("task not found in this project");
|
|
161
|
+
const runtime = getChild(job);
|
|
162
|
+
if (args.operation === "cancel") return { ok: true, ...runtime.cancel({ taskRunId: job.taskRunId, reason: args.reason }) };
|
|
163
|
+
if (["accept", "reject"].includes(args.operation)) {
|
|
164
|
+
const task = runtime.snapshot().tasks[job.taskRunId];
|
|
165
|
+
if (job.review === "accepted") return { ok: true, task: publicChild(job) };
|
|
166
|
+
if (task?.status !== "completed" || !String(args.reason || "").trim()) throw new Error("review requires a completed task and a reason");
|
|
167
|
+
if (args.operation === "accept" && !validateEvidence(args.evidence, context, job.completedAt)) throw new Error("acceptance requires successful main validation toolCallIds after completion");
|
|
168
|
+
updateJobs((items) => { items[job.id].review = args.operation === "accept" ? "accepted" : "rejected";
|
|
169
|
+
items[job.id].reviewReason = args.reason; items[job.id].evidence = args.evidence || []; });
|
|
170
|
+
}
|
|
171
|
+
return { ok: true, task: publicChild(jobs()[job.id]) };
|
|
172
|
+
} };
|
|
173
|
+
async function coordinatedOps(project, ops, manager) {
|
|
174
|
+
ops = ops.map((op) => op.action === "launch" ? { ...op, internal_only: true } : op);
|
|
175
|
+
if (!ops.some((op) => op.action === "launch")) return ports.handleOps(project, ops, manager);
|
|
176
|
+
const ownerId = `launch-${randomUUID()}`;
|
|
177
|
+
const result = await workspaceAccess.leases.run({ key: root, ownerId }, () => ports.handleOps(project, ops, manager, { leaseOwnerId: ownerId }));
|
|
178
|
+
if (result?.code === "workspace_busy") throw Object.assign(new Error("coding task owns this workspace; launch after it finishes or use an isolated worktree"), { code: "workspace_busy" });
|
|
179
|
+
return result;
|
|
180
|
+
}
|
|
181
|
+
function publicChild(job) {
|
|
182
|
+
const runtime = children.get(job.id);
|
|
183
|
+
const task = runtime && runtime.snapshot().tasks[job.taskRunId];
|
|
184
|
+
return { id: job.id, taskRunId: job.taskRunId, objective: job.objective, workspaceRoot: job.workspaceRoot,
|
|
185
|
+
status: job.review || task?.status || job.status, executionStatus: task?.status || job.status,
|
|
186
|
+
sessionId: job.id, interaction: task?.result?.executionState?.pendingUserInteraction || null,
|
|
187
|
+
reviewReason: job.reviewReason || "", summary: task?.result?.text?.slice(-6000) || job.summary || "", error: task?.error || "" };
|
|
188
|
+
}
|
|
189
|
+
function makeRuntime({ sessionId, namespace, profile, capabilities, host, workspaceRoot = root, child = null }) {
|
|
190
|
+
const productConfig = loadConfig(root);
|
|
191
|
+
const store = createRuntimeStore({ workspaceRoot: root, namespace, sessionId, redact: redactSecrets });
|
|
192
|
+
const contextManager = createContextManager({ policy: contextPolicy, store: {
|
|
193
|
+
sourceRef: store.journal,
|
|
194
|
+
load: () => store.read().contextCheckpoint || null,
|
|
195
|
+
commit(checkpoint, sourceBatch, expectedVersion) {
|
|
196
|
+
let committed = false;
|
|
197
|
+
store.transaction(state => {
|
|
198
|
+
if ((state.contextCheckpoint?.version || 0) !== expectedVersion) return [];
|
|
199
|
+
committed = true;
|
|
200
|
+
return [{ type: "context.checkpoint", checkpoint, sourceBatch }];
|
|
201
|
+
});
|
|
202
|
+
return committed;
|
|
203
|
+
},
|
|
204
|
+
} });
|
|
205
|
+
const previousBinding = store.read().binding;
|
|
206
|
+
const configuredProvider = normalizeProvider(provider || productConfig.agentProvider || "ucode");
|
|
207
|
+
const useCodingConfig = previousBinding?.codingConfig ?? configuredProvider === "ucode";
|
|
208
|
+
const selectedProvider = useCodingConfig ? "" : previousBinding?.provider || configuredProvider;
|
|
209
|
+
const modelRevision = Number(productConfig.agentModelRevision) || 0;
|
|
210
|
+
const changedModel = !useCodingConfig && modelRevision > (Number(previousBinding?.modelRevision) || 0)
|
|
211
|
+
&& sameModelProvider(productConfig.agentProvider, selectedProvider);
|
|
212
|
+
const selectedModel = (changedModel ? productConfig.agentModel : "") || previousBinding?.model || model || (useCodingConfig ? "" : productConfig.agentModel || defaultAgentModelForProvider(selectedProvider));
|
|
213
|
+
const config = resolveRuntimeConfig({ workspaceRoot: root, provider: selectedProvider, model: selectedModel, useCodingConfig });
|
|
214
|
+
const transport = transportFactory(config.transport);
|
|
215
|
+
const binding = { provider: selectedProvider || config.provider, model: config.model, transport: config.transport, codingConfig: useCodingConfig,
|
|
216
|
+
modelRevision: changedModel || !previousBinding ? modelRevision : previousBinding.modelRevision || 0 };
|
|
217
|
+
store.transaction((state) => {
|
|
218
|
+
if (state.binding && (state.binding.provider !== binding.provider || state.binding.transport !== binding.transport)) throw Object.assign(new Error("coding gateway changed; restore its configuration or use /session new"), { code: "session_provider_pinned" });
|
|
219
|
+
return !state.binding || changedModel ? [{ type: "runtime.binding", binding }] : [];
|
|
220
|
+
});
|
|
221
|
+
stores.set(sessionId, store);
|
|
222
|
+
let runtime;
|
|
223
|
+
const prepare = async (request, task, resumed = false) => {
|
|
224
|
+
const currentConfig = loadConfig(root);
|
|
225
|
+
const revision = Number(currentConfig.agentModelRevision) || 0;
|
|
226
|
+
if (!useCodingConfig && revision > (Number(store.read().binding?.modelRevision) || 0)
|
|
227
|
+
&& sameModelProvider(currentConfig.agentProvider, selectedProvider)) {
|
|
228
|
+
config.model = currentConfig.agentModel;
|
|
229
|
+
store.append({ type: "runtime.binding", binding: { ...binding, model: config.model, modelRevision: revision } });
|
|
230
|
+
}
|
|
231
|
+
const resolved = useCodingConfig && config.apiKey && config.apiKeySource !== "kimi-credential"
|
|
232
|
+
? { ...config, auth: { apiKey: config.apiKey } }
|
|
233
|
+
: await resolveProvider({ projectRoot: root, provider: selectedProvider || config.provider, model: config.model });
|
|
234
|
+
if (useCodingConfig) resolved.baseUrl = config.baseUrl;
|
|
235
|
+
const expected = resolved.transport === "codex-responses" ? "openai-responses" : resolved.transport;
|
|
236
|
+
if (expected !== config.transport) throw new Error("provider transport changed; start a new session");
|
|
237
|
+
const context = child ? [] : [readBusSummaryHandler({ projectRoot: root, internalAgentsOnly: true }), readOpenDecisionsHandler({ projectRoot: root }, { limit: 20 }),
|
|
238
|
+
{ memory: buildCachedMemoryPrefix(root, { limit: 30, maxTokens: 1500 }).prefix || "" }, { delegatedTasks: Object.values(management.snapshot().tasks).slice(-30) }];
|
|
239
|
+
if (!child) {
|
|
240
|
+
const registered = loadAgentsData(getUfooPaths(root).agentsFile).agents;
|
|
241
|
+
context.push({ requestMeta: request.requestMeta || {}, reports: listControllerInboxEntries(root, "ufoo-agent", { num: 30 })
|
|
242
|
+
.filter((report) => isInternalAgentMeta(registered[report.agent_id])) });
|
|
243
|
+
}
|
|
244
|
+
const sources = await runtime.buildContext({ workspaceRoot, prompt: request.text, promptText: request.text });
|
|
245
|
+
const skillSource = sources.find((source) => source.capabilityId === "skills")?.value;
|
|
246
|
+
const skillBlocks = (skillSource?.blocks || []).join("\n\n").slice(0, 65536);
|
|
247
|
+
context.push(...sources.filter((source) => source.capabilityId !== "skills"));
|
|
248
|
+
if (skillSource) context.push({ skills: { active: skillSource.activeSkills, warnings: skillSource.warnings } });
|
|
249
|
+
const instructionFile = path.join(workspaceRoot, "AGENTS.md");
|
|
250
|
+
const instructions = fs.existsSync(instructionFile) ? fs.readFileSync(instructionFile, "utf8").slice(0, 16000) : "";
|
|
251
|
+
const history = child ? [] : replayHistory(store.events(), task.taskRunId);
|
|
252
|
+
const attachments = (request.attachments || []).map((attachment) => resolveWorkspacePath(workspaceRoot, typeof attachment === "string" ? attachment : attachment.path).resolved);
|
|
253
|
+
return { workspaceRoot, sessionId, projectId, agentId: child ? child.id : "ufoo-agent", artifactNamespace: namespace,
|
|
254
|
+
model: resolved.model, provider: resolved.provider === "claude" ? "anthropic" : resolved.provider,
|
|
255
|
+
baseUrl: resolved.baseUrl, apiKey: resolved.auth?.apiKey || "", requestHeaders: resolved.auth?.headers || {},
|
|
256
|
+
accountId: resolved.credential?.accountId || "", requestProfile: resolved.requestProfile || "",
|
|
257
|
+
thinkingLevel: currentConfig.agentThinking || "medium",
|
|
258
|
+
requestKind: child ? "coding-task" : request.report ? "worker-report" : request.parentTaskRunId ? "task-result" : "user",
|
|
259
|
+
prompt: resumed ? "" : request.text + (attachments.length ? `\n\nWorkspace attachments (read with read/read_image): ${JSON.stringify(attachments)}` : ""), historyMessages: history,
|
|
260
|
+
systemPrompt: child ? buildCodingTaskPrompt({ workspaceRoot, instructions, skillBlocks, toolNames: runtime.tools.names() }) : buildMainAgentPrompt({ global, workspaceRoot, skillBlocks, toolNames: runtime.tools.names(), promptSections: runtime.promptSections, context, instructions: global ? "" : instructions }),
|
|
261
|
+
timeoutMs: resolveTaskTimeoutMs(), toolBudget: resolveToolBudget(),
|
|
262
|
+
contextManager,
|
|
263
|
+
};
|
|
264
|
+
};
|
|
265
|
+
runtime = createAgentRuntime({ profile, capabilities, transport,
|
|
266
|
+
host: { ...host, projectId, agentId: child ? child.id : "ufoo-agent", sessionStore: store, prepareRequest: prepare,
|
|
267
|
+
validateAnswer(task, answer) {
|
|
268
|
+
const parsed = parseUserInteractionInput(task.result.executionState.pendingUserInteraction, typeof answer === "string" ? answer : JSON.stringify(answer));
|
|
269
|
+
if (!parsed.ok) throw new Error(parsed.error);
|
|
270
|
+
},
|
|
271
|
+
async resumeRequest(task, answer) {
|
|
272
|
+
const previous = JSON.parse(JSON.stringify(task.result));
|
|
273
|
+
const resolved = resolveUserInteraction(previous.executionState, typeof answer === "string" ? answer : JSON.stringify(answer));
|
|
274
|
+
if (!resolved.ok) throw new Error(resolved.error);
|
|
275
|
+
const paired = materializeAnswerToolResult(previous.messages, resolved.resume, resolved.answer);
|
|
276
|
+
if (!paired.ok) throw new Error(paired.error);
|
|
277
|
+
return { ...await prepare(task.request, task, true), historyMessages: previous.messages, historyOffset: previous.historyOffset,
|
|
278
|
+
executionState: previous.executionState, resume: true };
|
|
279
|
+
},
|
|
280
|
+
eventSink(event) {
|
|
281
|
+
publish({ ...event, sessionId });
|
|
282
|
+
if (child && ["task.completed", "task.failed", "task.cancelled"].includes(event.type)) {
|
|
283
|
+
updateJobs((items) => { const item = items[child.id]; item.status = event.type.split(".")[1]; item.completedAt = event.time || new Date().toISOString(); item.summary = String(event.result?.text || event.error || "").slice(-6000); item.pendingWake = `child-result-${hash(`${child.id}:${event.taskRunId}`)}`; });
|
|
284
|
+
flushChildWakes();
|
|
285
|
+
}
|
|
286
|
+
}, onError: (error) => log(error.message) },
|
|
287
|
+
});
|
|
288
|
+
return runtime;
|
|
289
|
+
}
|
|
290
|
+
function getSession(sessionId = "main-default") {
|
|
291
|
+
if (closed || !safeId(sessionId)) throw new Error("invalid or closed main session");
|
|
292
|
+
if (sessions.has(sessionId)) return sessions.get(sessionId);
|
|
293
|
+
const host = { grantedPermissions: global ? ["coordination.read"] : MAIN_GRANTS, workspaceAccess,
|
|
294
|
+
taskScheduler: conversationScheduler,
|
|
295
|
+
projectRouting: { list: () => listProjectRuntimes({ validate: true }) },
|
|
296
|
+
coordination: { ...ports, internalAgentsOnly: true, handleOps: coordinatedOps, projectRoot: root, agentManagement: management, taskScheduler: taskPort } };
|
|
297
|
+
host.coordination.execute = (ctx, call) => {
|
|
298
|
+
const permission = TOOL_PERMISSIONS[call.name];
|
|
299
|
+
const readOnly = ["manage_tasks", "manage_group", "resume_agents", "manage_cron"].includes(call.name)
|
|
300
|
+
&& ["list", "ls", "inspect", "status", "validate"].includes(call.arguments.operation);
|
|
301
|
+
const invoke = async () => {
|
|
302
|
+
const result = await executeControllerTool(ctx, call);
|
|
303
|
+
if (result.ok === false && result.error?.code === "tool_execution_failed") throw Object.assign(new Error(result.error.message), { code: "uncertain_effect" });
|
|
304
|
+
return result;
|
|
305
|
+
};
|
|
306
|
+
return permission && permission !== "coordination.read" && !readOnly
|
|
307
|
+
? management.commands.execute({ commandId: `tool-${hash(stableStringify({ request: ctx.requestId, name: call.name, args: call.arguments }))}`, kind: call.name, args: call.arguments }, invoke)
|
|
308
|
+
: invoke();
|
|
309
|
+
};
|
|
310
|
+
const runtime = makeRuntime({ sessionId, namespace: global ? "global-router" : "main", profile: global ? globalProfile : mainProfile,
|
|
311
|
+
host, capabilities: global ? createGlobalCapabilities(host) : createMainCapabilities(host) });
|
|
312
|
+
sessions.set(sessionId, runtime);
|
|
313
|
+
return runtime;
|
|
314
|
+
}
|
|
315
|
+
function getChild(job) {
|
|
316
|
+
if (children.has(job.id)) return children.get(job.id);
|
|
317
|
+
const grants = job.readOnly ? ["workspace.read"] : ["workspace.read", "workspace.write", "workspace.execute", "interaction.request"];
|
|
318
|
+
const coding = createCodingCapability({ workspaceAccess });
|
|
319
|
+
coding.tools = coding.tools.filter((tool) => tool.permissions.every((permission) => grants.includes(permission)));
|
|
320
|
+
const capabilities = [coding, createSkillsCapability(), ...(job.readOnly ? [] : [createMainPlanningCapability()])];
|
|
321
|
+
const host = { grantedPermissions: grants, taskScheduler: { schedule(options, work) {
|
|
322
|
+
return scheduler.schedule(options, (signal) => job.readOnly ? work(signal)
|
|
323
|
+
: workspaceAccess.runTask({ workspaceRoot: job.workspaceRoot, taskRunId: options.id, signal }, () => work(signal)).then((result) => {
|
|
324
|
+
if (result.ok === false) throw Object.assign(new Error(result.error), { code: result.code });
|
|
325
|
+
return result;
|
|
326
|
+
}));
|
|
327
|
+
} } };
|
|
328
|
+
const runtime = makeRuntime({ sessionId: job.id, namespace: "main-task", profile: { id: job.readOnly ? "coding-read-only" : "coding-task", capabilities: capabilities.map((cap) => cap.id) },
|
|
329
|
+
capabilities, host, workspaceRoot: job.workspaceRoot, child: job });
|
|
330
|
+
children.set(job.id, runtime);
|
|
331
|
+
return runtime;
|
|
332
|
+
}
|
|
333
|
+
function flushChildWakes() {
|
|
334
|
+
for (const job of Object.values(jobs())) {
|
|
335
|
+
if (!job.pendingWake) continue;
|
|
336
|
+
getSession(job.parentSessionId || "main-default").submit({ requestId: job.pendingWake,
|
|
337
|
+
text: `Independent task ${job.taskRunId} is ${job.status}. Summary: ${job.summary}. Review the outcome and continue the parent objective.`, parentTaskRunId: job.parentTaskRunId });
|
|
338
|
+
updateJobs((items) => { if (items[job.id].pendingWake === job.pendingWake) items[job.id].pendingWake = ""; });
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
function resolveRuntime(sessionId = "main-default") {
|
|
342
|
+
const job = jobs()[sessionId];
|
|
343
|
+
return job ? getChild(job) : getSession(sessionId);
|
|
344
|
+
}
|
|
345
|
+
return Object.freeze({
|
|
346
|
+
getSession, resolveRuntime, taskPort, management, publicEvent, workspaceAccess, projectRoot: root,
|
|
347
|
+
findRuntime({ taskRunId, interactionId, sessionId } = {}) {
|
|
348
|
+
for (const runtime of [...sessions.values(), ...children.values()]) if (Object.values(runtime.snapshot().tasks).some((task) => taskRunId ? task.taskRunId === taskRunId : interactionId && [task.interactionId, task.answeredInteractionId].includes(interactionId))) return runtime;
|
|
349
|
+
return resolveRuntime(sessionId);
|
|
350
|
+
},
|
|
351
|
+
submit: (request, sessionId) => getSession(sessionId).submit(request),
|
|
352
|
+
async runPrompt({ prompt, requestId = randomUUID(), sessionId = "main-default", requestMeta = {} }) {
|
|
353
|
+
const runtime = getSession(sessionId);
|
|
354
|
+
const accepted = runtime.submit({ requestId, text: prompt, requestMeta });
|
|
355
|
+
const task = await runtime.wait(accepted.taskRunId);
|
|
356
|
+
if (["failed", "cancelled", "interrupted"].includes(task.status)) return { ok: false, error: task.error, taskRunId: task.taskRunId };
|
|
357
|
+
let payload = { reply: typeof task.result?.finalText === "string" ? task.result.finalText : task.result?.text || "", dispatch: [], ops: [] };
|
|
358
|
+
if (global) {
|
|
359
|
+
try { payload = JSON.parse(payload.reply); } catch { return { ok: false, error: "global router returned invalid JSON" }; }
|
|
360
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload) || typeof payload.reply !== "string") return { ok: false, error: "global router returned an invalid payload" };
|
|
361
|
+
if (payload.project_route) {
|
|
362
|
+
const target = canonicalProjectRoot(payload.project_route.project_root);
|
|
363
|
+
const registered = listProjectRuntimes({ validate: true }).some((project) => {
|
|
364
|
+
try { return canonicalProjectRoot(project.project_root) === target; } catch { return false; }
|
|
365
|
+
});
|
|
366
|
+
if (!registered || target === root) return { ok: false, error: "global router selected a project outside the registry grant" };
|
|
367
|
+
}
|
|
368
|
+
payload.dispatch = [];
|
|
369
|
+
payload.ops = [];
|
|
370
|
+
}
|
|
371
|
+
payload.runtime = { ...accepted, status: task.status, sessionId, interaction: task.result?.executionState?.pendingUserInteraction || null };
|
|
372
|
+
return { ok: true, payload };
|
|
373
|
+
},
|
|
374
|
+
snapshot: () => ({ sessions: [...sessions].map(([sessionId, runtime]) => ({ sessionId, sequence: runtime.snapshot().sequence,
|
|
375
|
+
tasks: Object.values(runtime.snapshot().tasks).map((task) => ({ taskRunId: task.taskRunId, requestId: task.request.requestId, status: task.status, error: task.error, interaction: task.result?.executionState?.pendingUserInteraction || null })) })),
|
|
376
|
+
children: Object.values(jobs()).map(publicChild), delegated: Object.values(management.snapshot().tasks), scheduler: scheduler.snapshot(), conversations: conversationScheduler.snapshot(),
|
|
377
|
+
uncertainReceipts: Object.values(control.read().commands).filter((command) => command.status === "uncertain").map(({ commandId, kind, time }) => ({ commandId, kind, time })) }),
|
|
378
|
+
async recover() {
|
|
379
|
+
const directory = path.join(root, ".ufoo", "agent", global ? "global-router" : "main", "runtimes");
|
|
380
|
+
if (fs.existsSync(directory)) for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
|
|
381
|
+
if (entry.isDirectory() && safeId(entry.name)) {
|
|
382
|
+
try { getSession(entry.name); } catch (error) { log(`session ${entry.name} recovery: ${error.message}`); }
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
for (const job of Object.values(jobs())) {
|
|
386
|
+
try {
|
|
387
|
+
const runtime = getChild(job);
|
|
388
|
+
const accepted = runtime.submit({ requestId: job.requestId, text: job.objective, resourceKey: job.readOnly ? "" : job.workspaceRoot });
|
|
389
|
+
const task = runtime.snapshot().tasks[accepted.taskRunId];
|
|
390
|
+
updateJobs((items) => {
|
|
391
|
+
const item = items[job.id]; item.taskRunId = accepted.taskRunId;
|
|
392
|
+
if (["completed", "failed", "cancelled", "interrupted"].includes(task.status) && item.status !== task.status) {
|
|
393
|
+
item.status = task.status; item.summary = String(task.result?.text || task.error || "").slice(-6000);
|
|
394
|
+
item.completedAt = runtime.events().findLast((event) => event.taskRunId === task.taskRunId && event.type === `task.${task.status}`)?.time || new Date().toISOString();
|
|
395
|
+
item.pendingWake = `child-result-${hash(`${job.id}:${task.taskRunId}`)}`;
|
|
396
|
+
}
|
|
397
|
+
});
|
|
398
|
+
} catch (error) { log(`child ${job.id} recovery: ${error.message}`); }
|
|
399
|
+
}
|
|
400
|
+
for (const report of listControllerInboxEntries(root, "ufoo-agent", { num: 1000 })) await management.report(report);
|
|
401
|
+
await management.flushWakes(); flushChildWakes();
|
|
402
|
+
},
|
|
403
|
+
async close() { closed = true; await Promise.allSettled([...sessions.values(), ...children.values()].map((runtime) => runtime.close())); await scheduler.close(); await conversationScheduler.close(); },
|
|
404
|
+
});
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
module.exports = { createAgentHost, resolveTaskWorkspace };
|