u-foo 4.0.0 → 4.0.2
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 +90 -30
- package/README.zh-CN.md +76 -26
- package/SKILLS/ufoo/SKILL.md +25 -1
- package/SKILLS/ufoo-bus/SKILL.md +25 -2
- package/bin/ucode.js +4 -0
- package/bin/ufoo.js +3 -3
- 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 +6 -6
- package/src/agents/activity/activityDetector.js +1 -1
- package/src/agents/capabilities/agentManagement/service.js +40 -13
- package/src/agents/capabilities/coordination/index.js +1 -1
- package/src/agents/capabilities/taskReports/index.js +1 -1
- package/src/agents/controller/controllerToolExecutor.js +36 -20
- package/src/agents/controller/index.js +1 -6
- package/src/agents/internal/internalRunner.js +90 -56
- package/src/agents/launch/index.js +0 -1
- package/src/agents/launch/launcher.js +38 -29
- package/src/agents/launch/launcherReadiness.js +35 -0
- package/src/agents/launch/notifier.js +2 -2
- package/src/agents/launch/ptyWrapper.js +5 -2
- package/src/agents/launch/readyDetector.js +2 -2
- package/src/agents/profiles/main.js +1 -1
- package/src/agents/prompts/cooperation.js +14 -0
- package/src/agents/prompts/defaultBootstrap.js +1 -1
- package/src/agents/prompts/groupBootstrap.js +23 -7
- package/src/agents/prompts/mainAgent.js +11 -2
- package/src/agents/prompts/native/system.js +4 -1
- package/src/agents/prompts/native/ufoo.js +11 -3
- package/src/agents/prompts/promptProfiles.js +2 -0
- package/src/agents/prompts/reporting.js +16 -0
- package/src/agents/providers/claudeEventTranslator.js +3 -0
- package/src/agents/providers/claudeThreadProvider.js +3 -2
- package/src/agents/providers/clientIdentity.js +75 -0
- package/src/agents/providers/codexEventTranslator.js +23 -2
- package/src/agents/providers/codexThreadProvider.js +15 -6
- 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 +58 -40
- package/src/agents/providers/runtimeConfig.js +10 -8
- package/src/agents/providers/thinkingLevels.js +10 -36
- package/src/agents/providers/transports/responsesProtocol.js +11 -6
- package/src/agents/providers/upstreamRuntime.js +135 -0
- package/src/agents/runtime/context/checkpointStore.js +38 -0
- package/src/agents/runtime/context/compaction.js +151 -0
- package/src/agents/runtime/context/contextBudget.js +93 -0
- package/src/agents/runtime/context/replayHistory.js +28 -0
- package/src/agents/runtime/context/runtimeStore.js +2 -1
- package/src/agents/runtime/core/agentLoop.js +99 -18
- package/src/agents/runtime/core/executionBudget.js +36 -0
- package/src/agents/runtime/createAgentRuntime.js +16 -4
- package/src/agents/runtime/prompts/responseLanguage.js +12 -0
- package/src/agents/runtime/protocol/runObservation.js +24 -0
- package/src/agents/runtime/protocol/traceContext.js +9 -0
- package/src/app/chat/ChatController.js +26 -53
- package/src/app/chat/agentDirectory.js +1 -16
- package/src/app/chat/bootstrap.js +1 -2
- package/src/app/chat/commandExecutor.js +93 -285
- package/src/app/chat/commands.js +32 -45
- package/src/app/chat/daemonMessageRouter.js +0 -45
- package/src/app/chat/historyStore.js +12 -48
- package/src/app/chat/inputSubmitHandler.js +7 -33
- package/src/app/chat/internalAgentLogHistory.js +19 -60
- package/src/app/chat/multiWindow/paneManager.js +10 -3
- package/src/app/chat/streamState.js +0 -4
- package/src/app/cli/features/init.js +5 -5
- package/src/app/cli/metricsCommands.js +68 -0
- package/src/app/cli/run.js +42 -3
- package/src/app/cli/traceCommands.js +36 -0
- package/src/code/agent.js +18 -13
- package/src/code/busConsumer.js +1 -3
- package/src/code/commands.js +1 -1
- package/src/code/context/assembler.js +7 -8
- package/src/code/context/stateCommit.js +2 -1
- package/src/code/internalThread.js +10 -3
- 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 +55 -17
- package/src/code/providers/modelsCatalog.js +1 -317
- package/src/code/repl.js +4 -11
- package/src/code/sessionStore.js +3 -3
- package/src/code/taskDecomposer.js +18 -0
- package/src/code/toolBudget.js +1 -17
- package/src/config.js +22 -72
- package/src/coordination/bus/index.js +12 -3
- package/src/coordination/bus/inject.js +2 -2
- package/src/coordination/bus/message.js +15 -1
- package/src/coordination/bus/nickname.js +1 -1
- package/src/coordination/bus/subscriber.js +3 -2
- package/src/coordination/bus/utils.js +1 -1
- package/src/coordination/history/agentPerformance.js +279 -0
- package/src/coordination/history/agentTrace.js +249 -0
- package/src/coordination/state/workspaceAccess.js +1 -1
- 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 +11 -2
- package/src/runtime/contracts/uiProtocol.js +18 -19
- package/src/runtime/daemon/agentHost.js +57 -25
- package/src/runtime/daemon/agentRecoveryGroups.js +70 -0
- package/src/runtime/daemon/busBridge.js +1 -1
- package/src/runtime/daemon/controlPlaneService.js +1 -1
- package/src/runtime/daemon/groupOrchestrator.js +20 -5
- package/src/runtime/daemon/groupStatus.js +20 -0
- package/src/runtime/daemon/index.js +19 -44
- package/src/runtime/daemon/mcpHttpServer.js +39 -10
- package/src/runtime/daemon/mcpServer.js +1 -1
- package/src/runtime/daemon/nicknameScope.js +1 -1
- package/src/runtime/daemon/ops.js +46 -23
- package/src/runtime/daemon/projectRuntimeGateway.js +2 -0
- package/src/runtime/daemon/promptRequest.js +92 -589
- package/src/runtime/daemon/status.js +5 -6
- package/src/tools/controllerSchemas.js +6 -2
- package/src/tools/handlers/tier2.js +4 -2
- package/src/tools/registry.js +4 -0
- package/src/tools/schemaFixtures.js +26 -2
- package/src/tools/tier0/readAgentMetrics.js +14 -0
- package/src/tools/tier0/readAgentTrace.js +12 -0
- package/src/ui/agentSettingsController.js +107 -0
- package/src/ui/agentSurface.js +1 -1
- package/src/ui/dashboardBridge.js +1 -1
- package/src/ui/format/banner.js +1 -4
- 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/rustChatHost.js +191 -206
- package/src/ui/rustMultiSession.js +77 -36
- package/src/ui/rustUcodeHost.js +6 -1
- package/src/ui/settingsBridge.js +33 -16
- 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 -336
- package/src/agents/controller/ufooAgent.js +0 -830
- package/src/agents/launch/ptyRunner.js +0 -1135
- package/src/agents/providers/controllerJsonTransport.js +0 -28
- package/src/agents/providers/upstreamTransport.js +0 -698
- package/src/app/chat/agentBar.js +0 -135
- package/src/app/chat/agentSockets.js +0 -225
- package/src/app/chat/dashboardView.js +0 -405
- package/src/app/chat/rawKeyMap.js +0 -42
- package/src/app/chat/settingsController.js +0 -111
- package/src/coordination/history/controllerSummary.js +0 -23
- 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/executionPaths.js +0 -30
- package/src/runtime/daemon/promptLoop.js +0 -136
- package/src/runtime/privacy/shadowDiff.js +0 -174
|
@@ -3,9 +3,12 @@
|
|
|
3
3
|
const { createHash } = require("crypto");
|
|
4
4
|
const { createCommandStore } = require("../../runtime");
|
|
5
5
|
const { stableStringify } = require("../../runtime/core/stableJson");
|
|
6
|
+
const { REPORTING_GUIDANCE } = require("../../prompts/reporting");
|
|
7
|
+
const { normalizeInternalAgentType } = require("../../../runtime/contracts/agentMode");
|
|
6
8
|
|
|
7
9
|
const digest = (value) => createHash("sha256").update(value).digest("hex").slice(0, 24);
|
|
8
10
|
const empty = () => ({ tasks: {} });
|
|
11
|
+
const reject = (code, error) => ({ ok: false, code, error });
|
|
9
12
|
|
|
10
13
|
/** Project host ports own launching/delivery; this adapter records business associations. */
|
|
11
14
|
function createAgentManagementService({ store, launch, dispatch, wake = async () => {}, emit = () => {}, validateEvidence = null, resolveTarget = (target) => target } = {}) {
|
|
@@ -18,6 +21,19 @@ function createAgentManagementService({ store, launch, dispatch, wake = async ()
|
|
|
18
21
|
return [{ type: "capability.state_committed", capabilityId: "agent-management", version: 1, value: state }];
|
|
19
22
|
});
|
|
20
23
|
}
|
|
24
|
+
function failed(taskId, stage, result) {
|
|
25
|
+
const failure = { ...result, ok: false, taskId };
|
|
26
|
+
update((state) => {
|
|
27
|
+
const task = state.tasks[taskId];
|
|
28
|
+
task.lastError = { code: failure.code || `${stage}_failed`, error: failure.error || `${stage} failed`, stage };
|
|
29
|
+
task.updatedAt = new Date().toISOString();
|
|
30
|
+
// An uncertain side effect must still be reconciled through its command
|
|
31
|
+
// receipt. A confirmed failure cannot remain a queued/running task.
|
|
32
|
+
if (failure.code !== "uncertain_effect") task.status = failure.code === "awaiting_registration" ? "awaiting_registration" : "failed";
|
|
33
|
+
});
|
|
34
|
+
emit({ type: "delegation.failed", taskId, stage, code: failure.code, error: failure.error });
|
|
35
|
+
return failure;
|
|
36
|
+
}
|
|
21
37
|
async function flushWakes() {
|
|
22
38
|
for (const task of Object.values(read().tasks)) {
|
|
23
39
|
if (!task.pendingWake) continue;
|
|
@@ -40,41 +56,47 @@ function createAgentManagementService({ store, launch, dispatch, wake = async ()
|
|
|
40
56
|
},
|
|
41
57
|
async delegate(args, context = {}) {
|
|
42
58
|
const id = String(args.command_id || "");
|
|
43
|
-
if (!/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,100}$/.test(id))
|
|
44
|
-
if (!String(args.objective || "").trim())
|
|
45
|
-
if (!args.target && !args.agent)
|
|
59
|
+
if (!/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,100}$/.test(id)) return reject("invalid_arguments", "delegate_task requires safe command_id");
|
|
60
|
+
if (!String(args.objective || "").trim()) return reject("invalid_arguments", "delegate_task requires objective");
|
|
61
|
+
if (!args.target && !args.agent) return reject("invalid_arguments", "delegate_task requires an existing target or an agent type to create");
|
|
62
|
+
if (!args.target && !normalizeInternalAgentType(args.agent)) return reject("invalid_arguments", "delegate_task supports internal codex, claude or ucode workers only");
|
|
46
63
|
const scope = context.requestId ? `${context.requestId}:${id}` : id;
|
|
47
64
|
const commandId = `delegate-${digest(scope)}`;
|
|
48
65
|
const taskId = `delegated-${digest(scope)}`;
|
|
49
66
|
const fingerprint = digest(stableStringify(args));
|
|
50
67
|
const target = args.target ? resolveTarget(args.target) : "";
|
|
51
|
-
if (args.target && !target)
|
|
68
|
+
if (args.target && !target) return reject("invalid_target", "delegation target is not an active project worker. To create one, omit target and pass agent plus optional nickname.");
|
|
52
69
|
update((state) => {
|
|
53
70
|
const existing = state.tasks[taskId];
|
|
54
71
|
if (existing && existing.fingerprint !== fingerprint) throw Object.assign(new Error("delegation command conflicts"), { code: "command_conflict" });
|
|
55
72
|
if (!existing) state.tasks[taskId] = { taskId, fingerprint, objective: args.objective,
|
|
73
|
+
commandIds: [`${commandId}:launch`, `${commandId}:dispatch`],
|
|
56
74
|
acceptanceCriteria: args.acceptance_criteria || [], parentTaskRunId: context.taskRunId || "",
|
|
57
|
-
parentSessionId: context.sessionId || "",
|
|
75
|
+
parentSessionId: context.sessionId || "", traceId: context.traceId || context.taskId || context.taskRunId || taskId,
|
|
76
|
+
parentRequestId: context.requestId || "", createdAt: new Date().toISOString(), status: "planning", workerId: String(target), reportIds: [] };
|
|
58
77
|
});
|
|
59
78
|
let task = read().tasks[taskId];
|
|
79
|
+
if (["failed", "awaiting_registration"].includes(task.status)) return { ok: false, task: { ...task }, ...task.lastError };
|
|
60
80
|
if (task.status !== "planning") return { ok: true, task: { ...task } };
|
|
61
81
|
if (!task.workerId) {
|
|
62
82
|
const nickname = args.nickname || `worker-${digest(scope).slice(0, 12)}`;
|
|
63
83
|
const result = await commands.execute({ commandId: `${commandId}:launch`, kind: "launch_agent", args: { agent: args.agent, nickname } }, () => launch({ agent: args.agent, nickname, count: 1 }));
|
|
64
|
-
if (!result || result.ok === false) return
|
|
84
|
+
if (!result || result.ok === false) return failed(taskId, "launch", result);
|
|
65
85
|
const rows = Array.isArray(result.ops_results) ? result.ops_results : [result];
|
|
66
86
|
const workerId = rows.map((row) => row.agent_id || row.subscriber_ids?.[0] || "").find(Boolean);
|
|
67
|
-
if (!workerId) return
|
|
87
|
+
if (!workerId) return failed(taskId, "launch", { code: "awaiting_registration", error: "Launch receipt has no concrete worker identity; reconcile before dispatch." });
|
|
68
88
|
update((state) => { state.tasks[taskId].workerId = workerId; });
|
|
69
89
|
task = read().tasks[taskId];
|
|
70
90
|
}
|
|
71
91
|
const message = [args.objective, `Task ID: ${taskId}`, "Controller: ufoo-agent. Report start/progress/done/error with this exact task ID and private scope.",
|
|
72
92
|
"Use ufoo report --task <id> --scope private --controller ufoo-agent, or MCP report_agent_status with task_id, scope=private, controller_id=ufoo-agent.",
|
|
93
|
+
REPORTING_GUIDANCE,
|
|
73
94
|
`Acceptance criteria: ${JSON.stringify(task.acceptanceCriteria)}`].join("\n\n");
|
|
74
95
|
const receipt = await commands.execute({ commandId: `${commandId}:dispatch`, kind: "dispatch_message", args: { target: task.workerId, message } },
|
|
75
|
-
() => dispatch({ target: task.workerId, message, taskId
|
|
76
|
-
|
|
77
|
-
|
|
96
|
+
() => dispatch({ target: task.workerId, message, taskId, runtimeContext: { traceId: task.traceId,
|
|
97
|
+
taskId, parentTaskRunId: task.parentTaskRunId, parentSessionId: task.parentSessionId, parentRequestId: task.parentRequestId } }));
|
|
98
|
+
if (!receipt || receipt.ok === false) return failed(taskId, "dispatch", receipt);
|
|
99
|
+
update((state) => { const entry = state.tasks[taskId]; if (entry.status === "planning") entry.status = "queued"; entry.queuedAt = new Date().toISOString(); entry.dispatchReceipt = receipt; });
|
|
78
100
|
emit({ type: "delegation.queued", taskId, workerId: task.workerId, parentTaskRunId: task.parentTaskRunId });
|
|
79
101
|
return { ok: true, task: read().tasks[taskId], deliveryStatus: "queued" };
|
|
80
102
|
},
|
|
@@ -86,9 +108,10 @@ function createAgentManagementService({ store, launch, dispatch, wake = async ()
|
|
|
86
108
|
update((state) => {
|
|
87
109
|
const current = state.tasks[entry.task_id];
|
|
88
110
|
current.reportIds.push(reportId);
|
|
89
|
-
if (current.status
|
|
111
|
+
if (["accepted", "rejected"].includes(current.status)) return;
|
|
90
112
|
if (current.report && ["done", "error"].includes(current.report.phase) && ["start", "progress"].includes(entry.phase)) return;
|
|
91
113
|
current.report = entry;
|
|
114
|
+
current.updatedAt = entry.ts || new Date().toISOString();
|
|
92
115
|
current.status = ["done", "error"].includes(entry.phase) ? "reported" : "running";
|
|
93
116
|
if (current.status === "reported") current.pendingWake = `report-${digest(`${current.taskId}:${reportId}`)}`;
|
|
94
117
|
});
|
|
@@ -96,14 +119,18 @@ function createAgentManagementService({ store, launch, dispatch, wake = async ()
|
|
|
96
119
|
return { matched: true, task: read().tasks[entry.task_id] };
|
|
97
120
|
},
|
|
98
121
|
accept({ task_id: taskId, outcome, reason, evidence = [] }, context = {}) {
|
|
99
|
-
if (!["accepted", "rejected"].includes(outcome))
|
|
122
|
+
if (!["accepted", "rejected"].includes(outcome)) return reject("invalid_arguments", "accept_task requires accepted or rejected outcome");
|
|
123
|
+
const existing = read().tasks[taskId];
|
|
124
|
+
if (!existing || existing.status !== "reported") return reject("invalid_task_state", "task has no unreviewed terminal report");
|
|
125
|
+
if (outcome === "accepted" && (!String(reason || "").trim() || !evidence.length || existing.report.phase !== "done")) return reject("acceptance_required", "acceptance requires a completed worker report, reason, and validation evidence");
|
|
126
|
+
if (outcome === "accepted" && (!validateEvidence || validateEvidence(evidence, existing, context) !== true)) return reject("invalid_evidence", "host did not verify the acceptance evidence");
|
|
100
127
|
update((state) => {
|
|
101
128
|
const task = state.tasks[taskId];
|
|
102
129
|
if (!task || task.status !== "reported") throw new Error("task has no unreviewed terminal report");
|
|
103
130
|
if (outcome === "accepted" && (!String(reason || "").trim() || !evidence.length || task.report.phase !== "done")) throw new Error("acceptance requires a completed worker report, reason, and validation evidence");
|
|
104
131
|
if (outcome === "accepted" && (!validateEvidence || validateEvidence(evidence, task, context) !== true)) throw new Error("host did not verify the acceptance evidence");
|
|
105
132
|
task.status = outcome;
|
|
106
|
-
task.acceptance = { outcome, reason, evidence };
|
|
133
|
+
task.acceptance = { outcome, reason, evidence, time: new Date().toISOString() };
|
|
107
134
|
});
|
|
108
135
|
return { ok: true, task: read().tasks[taskId] };
|
|
109
136
|
},
|
|
@@ -27,7 +27,7 @@ function createCoordinationCapability({ host, id = "coordination", toolNames = n
|
|
|
27
27
|
const invoke = ports.execute || executeControllerTool;
|
|
28
28
|
return invoke({ ...ports, projectRoot: context.workspaceRoot || ports.projectRoot,
|
|
29
29
|
subscriber: "ufoo-agent", turnId: context.turnId, taskId: context.taskId,
|
|
30
|
-
requestId: context.requestId, taskRunId: context.taskRunId, sessionId: context.sessionId },
|
|
30
|
+
requestId: context.requestId, taskRunId: context.taskRunId, sessionId: context.sessionId, traceId: context.traceId },
|
|
31
31
|
{ name: tool.name, arguments: args, id: context.toolCallId });
|
|
32
32
|
},
|
|
33
33
|
})),
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
const { createCoordinationCapability } = require("../coordination");
|
|
3
3
|
module.exports = { createTaskReportsCapability: (host) => ({
|
|
4
|
-
...createCoordinationCapability({ host, id: "task-reports", toolNames: ["read_task_reports", "accept_task"] }),
|
|
4
|
+
...createCoordinationCapability({ host, id: "task-reports", toolNames: ["read_task_reports", "read_agent_trace", "read_agent_metrics", "accept_task"] }),
|
|
5
5
|
requires: { ports: ["coordination"], capabilities: ["agent-management"] },
|
|
6
6
|
}) };
|
|
@@ -4,6 +4,8 @@ const EventBus = require("../../coordination/bus");
|
|
|
4
4
|
const { getToolDefinition, CALLER_TIERS } = require("../../tools");
|
|
5
5
|
const { dispatchMessageHandler } = require("../../tools/handlers/dispatchMessage");
|
|
6
6
|
const { ackBusHandler } = require("../../tools/handlers/ackBus");
|
|
7
|
+
const { isMetaActive } = require("../../coordination/bus/utils");
|
|
8
|
+
const { isInternalAgentMeta, normalizeInternalAgentType } = require("../../runtime/contracts/agentMode");
|
|
7
9
|
|
|
8
10
|
function normalizeObjectArgs(value) {
|
|
9
11
|
if (!value) return {};
|
|
@@ -33,6 +35,17 @@ function buildStructuredError(code, message, extra = {}) {
|
|
|
33
35
|
}
|
|
34
36
|
|
|
35
37
|
function resolveDispatchTargets(ctx, target) {
|
|
38
|
+
if (ctx.internalAgentsOnly) {
|
|
39
|
+
const eventBus = ctx.eventBus || new EventBus(ctx.projectRoot);
|
|
40
|
+
eventBus.loadBusData();
|
|
41
|
+
const agents = eventBus.busData.agents || {};
|
|
42
|
+
const targets = target === "broadcast"
|
|
43
|
+
? Object.keys(agents)
|
|
44
|
+
: eventBus.messageManager.resolveTarget(target);
|
|
45
|
+
const active = targets.filter((id) => id !== "ufoo-agent" && isInternalAgentMeta(agents[id]) && isMetaActive(agents[id]));
|
|
46
|
+
if (active.length) return active;
|
|
47
|
+
throw buildStructuredError("invalid_target", `dispatch_message target not found among active internal agents: ${target}`);
|
|
48
|
+
}
|
|
36
49
|
if (typeof ctx.resolveDispatchTargets === "function") {
|
|
37
50
|
const resolved = ctx.resolveDispatchTargets(target);
|
|
38
51
|
if (Array.isArray(resolved) && resolved.length > 0) return resolved;
|
|
@@ -56,22 +69,24 @@ function resolveDispatchTargets(ctx, target) {
|
|
|
56
69
|
}
|
|
57
70
|
|
|
58
71
|
async function handleDispatchMessage(ctx, args) {
|
|
72
|
+
const dispatch = async (target, message, publisher, options = {}) => {
|
|
73
|
+
const targets = resolveDispatchTargets(ctx, target);
|
|
74
|
+
const receipts = await ctx.dispatchMessages(ctx.projectRoot, (ctx.internalAgentsOnly ? targets : [target]).map((recipient) => ({
|
|
75
|
+
target: recipient,
|
|
76
|
+
message,
|
|
77
|
+
injection_mode: options.injectionMode || "immediate",
|
|
78
|
+
source: options.source || publisher,
|
|
79
|
+
})));
|
|
80
|
+
if (typeof ctx.markPending === "function" && target !== "broadcast") {
|
|
81
|
+
for (const recipient of ctx.internalAgentsOnly ? targets : [target]) ctx.markPending(recipient);
|
|
82
|
+
}
|
|
83
|
+
return { ...(receipts?.[0] || { seq: 0 }), targets: receipts?.length ? receipts.flatMap((receipt) => receipt.targets || []) : targets };
|
|
84
|
+
};
|
|
59
85
|
const eventBus = typeof ctx.dispatchMessages === "function"
|
|
60
86
|
? {
|
|
61
|
-
send:
|
|
62
|
-
resolveDispatchTargets(ctx, target);
|
|
63
|
-
if (target !== "broadcast" && typeof ctx.markPending === "function") {
|
|
64
|
-
ctx.markPending(target);
|
|
65
|
-
}
|
|
66
|
-
const receipts = await ctx.dispatchMessages(ctx.projectRoot, [{
|
|
67
|
-
target,
|
|
68
|
-
message,
|
|
69
|
-
injection_mode: options.injectionMode || "immediate",
|
|
70
|
-
source: options.source || publisher,
|
|
71
|
-
}]);
|
|
72
|
-
return receipts?.[0] || { seq: 0, targets: [target] };
|
|
73
|
-
},
|
|
87
|
+
send: dispatch,
|
|
74
88
|
broadcast: async (message, publisher, options = {}) => {
|
|
89
|
+
if (ctx.internalAgentsOnly) return dispatch("broadcast", message, publisher, options);
|
|
75
90
|
const receipts = await ctx.dispatchMessages(ctx.projectRoot, [{
|
|
76
91
|
target: "broadcast",
|
|
77
92
|
message,
|
|
@@ -125,20 +140,19 @@ async function handleLaunchAgent(ctx, args) {
|
|
|
125
140
|
throw buildStructuredError("tool_unavailable", "launch_agent hook is unavailable");
|
|
126
141
|
}
|
|
127
142
|
|
|
128
|
-
const agent =
|
|
143
|
+
const agent = normalizeInternalAgentType(args.agent);
|
|
129
144
|
if (!agent) {
|
|
130
|
-
throw buildStructuredError("invalid_arguments", "launch_agent requires
|
|
145
|
+
throw buildStructuredError("invalid_arguments", "launch_agent requires internal codex, claude or ucode");
|
|
131
146
|
}
|
|
132
147
|
|
|
133
148
|
const op = {
|
|
134
149
|
action: "launch",
|
|
150
|
+
internal_only: true,
|
|
135
151
|
agent,
|
|
136
152
|
count: normalizePositiveInt(args.count, 1),
|
|
137
153
|
};
|
|
138
154
|
if (args.nickname) op.nickname = String(args.nickname).trim();
|
|
139
155
|
if (args.prompt_profile) op.prompt_profile = String(args.prompt_profile).trim();
|
|
140
|
-
if (args.launch_scope) op.launch_scope = String(args.launch_scope).trim();
|
|
141
|
-
if (args.terminal_app) op.terminal_app = String(args.terminal_app).trim();
|
|
142
156
|
|
|
143
157
|
const opsResults = await ctx.handleOps(ctx.projectRoot, [op], ctx.processManager || null);
|
|
144
158
|
return {
|
|
@@ -199,11 +213,12 @@ async function executeControllerTool(ctx, toolCall = {}) {
|
|
|
199
213
|
});
|
|
200
214
|
}
|
|
201
215
|
|
|
216
|
+
const ok = result?.ok !== false;
|
|
202
217
|
observer.emit("tool_call_finished", {
|
|
203
218
|
tool_name: name,
|
|
204
219
|
tool_call_id: toolCallId,
|
|
205
220
|
turn_id: turnId,
|
|
206
|
-
ok
|
|
221
|
+
ok,
|
|
207
222
|
});
|
|
208
223
|
observer.audit({
|
|
209
224
|
source: "controller_loop",
|
|
@@ -211,16 +226,17 @@ async function executeControllerTool(ctx, toolCall = {}) {
|
|
|
211
226
|
tool_name: name,
|
|
212
227
|
tool_call_id: toolCallId,
|
|
213
228
|
turn_id: turnId,
|
|
214
|
-
ok
|
|
229
|
+
ok,
|
|
215
230
|
result,
|
|
216
231
|
});
|
|
217
232
|
|
|
218
233
|
return {
|
|
219
|
-
ok
|
|
234
|
+
ok,
|
|
220
235
|
name,
|
|
221
236
|
tool_call_id: toolCallId,
|
|
222
237
|
turn_id: turnId,
|
|
223
238
|
result,
|
|
239
|
+
...(!ok ? { error: buildStructuredError(result.code || "tool_rejected", typeof result.error === "string" ? result.error : result.error?.message || "tool rejected the request") } : {}),
|
|
224
240
|
};
|
|
225
241
|
} catch (err) {
|
|
226
242
|
const error = err && typeof err === "object" && err.code
|
|
@@ -7,10 +7,15 @@ const path = require("path");
|
|
|
7
7
|
const { getUfooPaths } = require("../../coordination/state/paths");
|
|
8
8
|
const { spawnSync } = require("child_process");
|
|
9
9
|
const EventBus = require("../../coordination/bus");
|
|
10
|
+
const { normalizeInternalAgentType } = require("../../runtime/contracts/agentMode");
|
|
10
11
|
const { readJSON } = require("../../coordination/bus/utils");
|
|
11
12
|
const { createActivityStatePublisher } = require("../activity/activityStatePublisher");
|
|
12
13
|
const { createActivityTracker } = require("../activity/activityTracker");
|
|
13
|
-
const {
|
|
14
|
+
const { normalizeTraceContext } = require("../runtime/protocol/traceContext");
|
|
15
|
+
const { buildRunObservation, observationFingerprint } = require("../runtime/protocol/runObservation");
|
|
16
|
+
const { getTaskIdFromEvent } = require("../../coordination/bus/messageMeta");
|
|
17
|
+
const { enqueueAgentReport } = require("../../runtime/daemon/reportControlBus");
|
|
18
|
+
const { loadConfig, defaultAgentModelForProvider, sameModelProvider } = require("../../config");
|
|
14
19
|
const { createCodexThreadProvider } = require("../providers/codexThreadProvider");
|
|
15
20
|
const { createClaudeThreadProvider } = require("../providers/claudeThreadProvider");
|
|
16
21
|
const { resolveClaudeUpstreamCredentials } = require("../providers/credentials/claude");
|
|
@@ -25,7 +30,13 @@ const {
|
|
|
25
30
|
buildDefaultStartupBootstrapPrompt,
|
|
26
31
|
isValueForCodexOption,
|
|
27
32
|
} = require("../prompts/defaultBootstrap");
|
|
28
|
-
const {
|
|
33
|
+
const {
|
|
34
|
+
hasSharedUfooProtocolPrompt,
|
|
35
|
+
INTERNAL_BUS_DELIVERY_GUIDANCE,
|
|
36
|
+
} = require("../prompts/groupBootstrap");
|
|
37
|
+
const { REPORTING_GUIDANCE } = require("../prompts/reporting");
|
|
38
|
+
const { RESPONSE_LANGUAGE_GUIDANCE } = require("../runtime/prompts/responseLanguage");
|
|
39
|
+
const { COOPERATION_GUIDANCE } = require("../prompts/cooperation");
|
|
29
40
|
const { buildPromptInjectionText } = require("../../coordination/bus/promptEnvelope");
|
|
30
41
|
|
|
31
42
|
function sleep(ms) {
|
|
@@ -149,6 +160,11 @@ function resolveInternalBootstrap({
|
|
|
149
160
|
promptText = [defaultPrompt, promptText.trim()].filter(Boolean).join("\n\n");
|
|
150
161
|
}
|
|
151
162
|
|
|
163
|
+
// Stored group/resume bootstraps may predate current runtime guidance.
|
|
164
|
+
if (!promptText.includes(REPORTING_GUIDANCE)) promptText = [promptText, REPORTING_GUIDANCE].join("\n\n");
|
|
165
|
+
if (!promptText.includes(INTERNAL_BUS_DELIVERY_GUIDANCE)) promptText = [promptText, INTERNAL_BUS_DELIVERY_GUIDANCE].join("\n\n");
|
|
166
|
+
if (!promptText.includes(RESPONSE_LANGUAGE_GUIDANCE)) promptText = [promptText, RESPONSE_LANGUAGE_GUIDANCE].join("\n\n");
|
|
167
|
+
if (!promptText.includes(COOPERATION_GUIDANCE)) promptText = [promptText, COOPERATION_GUIDANCE].join("\n\n");
|
|
152
168
|
return {
|
|
153
169
|
promptText,
|
|
154
170
|
extraArgs: nextArgs,
|
|
@@ -174,7 +190,7 @@ function readAgentsMap(projectRoot) {
|
|
|
174
190
|
|
|
175
191
|
function buildInternalPromptMessage(projectRoot, subscriber, evt = {}) {
|
|
176
192
|
const message = String((evt.data && evt.data.message) || "");
|
|
177
|
-
if (evt.
|
|
193
|
+
if (evt.__internalRawInput) return message;
|
|
178
194
|
return buildPromptInjectionText(evt, subscriber, readAgentsMap(projectRoot));
|
|
179
195
|
}
|
|
180
196
|
|
|
@@ -201,7 +217,8 @@ function createBusSender(projectRoot, subscriber) {
|
|
|
201
217
|
}
|
|
202
218
|
}
|
|
203
219
|
|
|
204
|
-
return { enqueue, flush, surface: surface.enqueue
|
|
220
|
+
return { enqueue, flush, surface: surface.enqueue,
|
|
221
|
+
report: report => enqueueAgentReport(projectRoot, { ...report, agent_id: subscriber, source: "runtime" }) };
|
|
205
222
|
}
|
|
206
223
|
|
|
207
224
|
function isChatUiSource(source = "") {
|
|
@@ -214,7 +231,7 @@ function isChatUiSource(source = "") {
|
|
|
214
231
|
|
|
215
232
|
function isUfooAgentDispatchSource(source = "") {
|
|
216
233
|
const value = String(source || "").trim();
|
|
217
|
-
return value === "ufoo-agent"
|
|
234
|
+
return value === "ufoo-agent";
|
|
218
235
|
}
|
|
219
236
|
|
|
220
237
|
function shouldStreamReplyToPublisher(projectRoot, publisher, evt = {}) {
|
|
@@ -235,7 +252,7 @@ function claimQueuedEvents(queueFile) {
|
|
|
235
252
|
return claims;
|
|
236
253
|
}
|
|
237
254
|
|
|
238
|
-
function
|
|
255
|
+
function parseInternalRawInput(message) {
|
|
239
256
|
if (typeof message !== "string" || !message.trim()) return null;
|
|
240
257
|
try {
|
|
241
258
|
const parsed = JSON.parse(message);
|
|
@@ -243,7 +260,7 @@ function parseAgentViewRawInput(message) {
|
|
|
243
260
|
return parsed.data;
|
|
244
261
|
}
|
|
245
262
|
} catch {
|
|
246
|
-
// Not a raw
|
|
263
|
+
// Not a raw internal-input envelope.
|
|
247
264
|
}
|
|
248
265
|
return null;
|
|
249
266
|
}
|
|
@@ -314,7 +331,8 @@ async function handleEvent(
|
|
|
314
331
|
extraArgs = [],
|
|
315
332
|
threadRuntime = null,
|
|
316
333
|
bootstrapText = "",
|
|
317
|
-
tracker = null
|
|
334
|
+
tracker = null,
|
|
335
|
+
signal = null
|
|
318
336
|
) {
|
|
319
337
|
if (!evt || !evt.data || !evt.data.message) return;
|
|
320
338
|
const memoryPrefix = buildMemoryPrefix(projectRoot);
|
|
@@ -325,9 +343,27 @@ async function handleEvent(
|
|
|
325
343
|
.join("\n\n");
|
|
326
344
|
const publisher = evt.publisher || "unknown";
|
|
327
345
|
const streamToPublisher = shouldStreamReplyToPublisher(projectRoot, publisher, evt);
|
|
328
|
-
const
|
|
329
|
-
|
|
330
|
-
|
|
346
|
+
const inherited = normalizeTraceContext(evt.data.runtime_context);
|
|
347
|
+
const taskId = getTaskIdFromEvent(evt) || inherited.taskId || `worker-${randomUUID()}`;
|
|
348
|
+
const runtimeContext = { ...inherited, taskId, traceId: inherited.traceId || taskId,
|
|
349
|
+
taskRunId: `worker-run-${randomUUID()}`, requestId: `bus-${evt.seq || randomUUID()}`, attemptId: `attempt-${randomUUID()}`,
|
|
350
|
+
requestKind: publisher === "ufoo-agent" && getTaskIdFromEvent(evt) ? "worker-task" : "bus-message" };
|
|
351
|
+
const emitSurface = event => busSender.surface?.({ ...runtimeContext, task_id: taskId, agentId: subscriber,
|
|
352
|
+
provider, model, sessionId: threadRuntime?.thread?.id || "", ...event });
|
|
353
|
+
const delegated = publisher === "ufoo-agent" && Boolean(getTaskIdFromEvent(evt));
|
|
354
|
+
const reportLifecycle = async (phase, error = "", meta = {}) => {
|
|
355
|
+
if (!delegated || typeof busSender.report !== "function") return;
|
|
356
|
+
await busSender.report({ task_id: taskId, phase, scope: "private", controller_id: "ufoo-agent", error,
|
|
357
|
+
meta: { ...runtimeContext, ...meta } });
|
|
358
|
+
};
|
|
359
|
+
emitSurface({ type: "task_started", message: evt.data.message, publisher, queueSequence: evt.seq });
|
|
360
|
+
if (provider !== "ucode") emitSurface({ type: "run_config", configuration: buildRunObservation({ provider, model,
|
|
361
|
+
executionKind: "sdk", systemPrompt: bootstrapText, prompt: evt.data.message,
|
|
362
|
+
requestKind: runtimeContext.requestKind,
|
|
363
|
+
engineFingerprint: observationFingerprint(handleThreadedEvent.toString()),
|
|
364
|
+
tools: threadRuntime?.toolRuntime?.tools || [],
|
|
365
|
+
thinkingLevel: String(threadRuntime?.thread?.threadOptions?.modelReasoningEffort || threadRuntime?.thread?.agentOptions?.effort || "") }) });
|
|
366
|
+
await reportLifecycle("start");
|
|
331
367
|
|
|
332
368
|
const emitStreamDelta = (delta) => {
|
|
333
369
|
const text = String(delta || "");
|
|
@@ -350,11 +386,15 @@ async function handleEvent(
|
|
|
350
386
|
threadRuntime,
|
|
351
387
|
tracker,
|
|
352
388
|
emitSurface,
|
|
389
|
+
runtimeContext,
|
|
390
|
+
reportLifecycle,
|
|
391
|
+
signal,
|
|
353
392
|
});
|
|
354
393
|
}
|
|
355
394
|
|
|
356
|
-
const errorText = `[internal:${agentType}] error:
|
|
395
|
+
const errorText = `[internal:${agentType}] error: ${threadRuntime?.error?.message || `agent runtime not initialized for provider ${provider}`}`;
|
|
357
396
|
emitSurface({ type: "task_failed", error: errorText });
|
|
397
|
+
await reportLifecycle("error", errorText);
|
|
358
398
|
// eslint-disable-next-line no-console
|
|
359
399
|
console.error(errorText);
|
|
360
400
|
if (streamToPublisher) {
|
|
@@ -364,6 +404,7 @@ async function handleEvent(
|
|
|
364
404
|
busSender.enqueue(publisher, errorText);
|
|
365
405
|
}
|
|
366
406
|
await busSender.flush();
|
|
407
|
+
return { ok: false, error: errorText };
|
|
367
408
|
}
|
|
368
409
|
|
|
369
410
|
function compactToolDetail(value = "", maxLength = 120) {
|
|
@@ -394,7 +435,7 @@ function toNonNegativeInt(value) {
|
|
|
394
435
|
}
|
|
395
436
|
|
|
396
437
|
// Normalizes provider usage payloads (claude/codex thread events) onto the
|
|
397
|
-
// metric fields
|
|
438
|
+
// metric fields used by provider usage summaries.
|
|
398
439
|
function normalizeTurnUsage(usage = null) {
|
|
399
440
|
const item = usage && typeof usage === "object" ? usage : {};
|
|
400
441
|
return {
|
|
@@ -426,18 +467,24 @@ async function handleThreadedEvent({
|
|
|
426
467
|
threadRuntime,
|
|
427
468
|
tracker = null,
|
|
428
469
|
emitSurface = () => {},
|
|
470
|
+
runtimeContext = {},
|
|
471
|
+
reportLifecycle = async () => {},
|
|
472
|
+
signal = null,
|
|
429
473
|
}) {
|
|
430
474
|
try {
|
|
431
475
|
const plainReplyParts = [];
|
|
476
|
+
let finalReply;
|
|
432
477
|
let turnUsage = null;
|
|
433
478
|
let stopReason = "";
|
|
434
479
|
let waitingForUser = false;
|
|
435
480
|
if (tracker && typeof tracker.notifyTurnStart === "function") {
|
|
436
481
|
tracker.notifyTurnStart();
|
|
437
482
|
}
|
|
438
|
-
|
|
483
|
+
const started = Date.now();
|
|
484
|
+
for await (const event of threadRuntime.thread.runStreamed(prompt, { ...(signal ? { signal } : {}), runtimeContext, ...(provider === "ucode" ? { userInput: userMessage } : {}) })) {
|
|
439
485
|
if (!event || typeof event !== "object") continue;
|
|
440
|
-
emitSurface(event
|
|
486
|
+
emitSurface(event.type === "tool_call" && event.args !== undefined
|
|
487
|
+
? { ...event, argumentFingerprint: observationFingerprint(event.args) } : event);
|
|
441
488
|
if (["usage", "turn_completed"].includes(event.type) && event.usage && provider !== "ucode") {
|
|
442
489
|
emitSurface({ type: "context_usage", meter: contextMeterForUsage(event.usage, model || threadRuntime.thread.model, provider) });
|
|
443
490
|
}
|
|
@@ -468,6 +515,7 @@ async function handleThreadedEvent({
|
|
|
468
515
|
} else if (event.type === "usage" && event.usage) {
|
|
469
516
|
turnUsage = normalizeTurnUsage(event.usage);
|
|
470
517
|
} else if (event.type === "turn_completed") {
|
|
518
|
+
if (typeof event.finalText === "string") finalReply = event.finalText;
|
|
471
519
|
if (event.usage) turnUsage = normalizeTurnUsage(event.usage);
|
|
472
520
|
if (event.stopReason) stopReason = String(event.stopReason);
|
|
473
521
|
} else if (event.type === "turn_failed") {
|
|
@@ -477,7 +525,9 @@ async function handleThreadedEvent({
|
|
|
477
525
|
if (typeof threadRuntime.syncProviderSessionId === "function") {
|
|
478
526
|
threadRuntime.syncProviderSessionId();
|
|
479
527
|
}
|
|
480
|
-
|
|
528
|
+
const reply = (finalReply === undefined ? plainReplyParts.join("") : finalReply).trim();
|
|
529
|
+
emitSurface({ type: waitingForUser ? "task_paused" : "task_completed", usage: turnUsage, durationMs: Date.now() - started,
|
|
530
|
+
finalTextCharacters: [...reply].length });
|
|
481
531
|
if (waitingForUser && tracker?.requestUserInput) tracker.requestUserInput("reply");
|
|
482
532
|
|
|
483
533
|
if (streamToPublisher) {
|
|
@@ -485,7 +535,8 @@ async function handleThreadedEvent({
|
|
|
485
535
|
if (turnUsage) doneEnvelope.usage = turnUsage;
|
|
486
536
|
busSender.enqueue(publisher, JSON.stringify(doneEnvelope));
|
|
487
537
|
} else {
|
|
488
|
-
|
|
538
|
+
// Live progress belongs to the worker pane. Peers receive only the final
|
|
539
|
+
// answer, including an explicitly empty ack-only result.
|
|
489
540
|
if (reply) busSender.enqueue(publisher, reply);
|
|
490
541
|
}
|
|
491
542
|
await busSender.flush();
|
|
@@ -501,9 +552,11 @@ async function handleThreadedEvent({
|
|
|
501
552
|
tracker.markIdle();
|
|
502
553
|
}
|
|
503
554
|
const errorText = `[internal:${agentType}] error: ${err && err.message ? err.message : "unknown error"}`;
|
|
504
|
-
|
|
555
|
+
const cancelled = signal?.aborted || err?.code === "cancelled" || err?.name === "AbortError";
|
|
556
|
+
emitSurface(cancelled
|
|
505
557
|
? { type: "task_cancelled" } : { type: "task_failed", error: errorText });
|
|
506
|
-
|
|
558
|
+
await reportLifecycle("error", errorText, { cancelled });
|
|
559
|
+
if (!cancelled && threadRuntime && typeof threadRuntime.rebuildThread === "function") {
|
|
507
560
|
try { await threadRuntime.rebuildThread(); }
|
|
508
561
|
catch (recoveryError) { console.error(`[internal:${agentType}] recovery failed: ${recoveryError?.message || "unknown error"}`); }
|
|
509
562
|
}
|
|
@@ -526,14 +579,6 @@ async function handleThreadedEvent({
|
|
|
526
579
|
}
|
|
527
580
|
}
|
|
528
581
|
|
|
529
|
-
function getCodexThreadMode(projectRoot) {
|
|
530
|
-
const envValue = process.env.UFOO_CODEX_INTERNAL_THREAD_MODE;
|
|
531
|
-
if (typeof envValue === "string" && envValue.trim()) {
|
|
532
|
-
return normalizeCodexInternalThreadMode(envValue);
|
|
533
|
-
}
|
|
534
|
-
return loadConfig(projectRoot).codexInternalThreadMode;
|
|
535
|
-
}
|
|
536
|
-
|
|
537
582
|
function getWorkerThreadToolMode() {
|
|
538
583
|
return normalizeWorkerThreadToolMode(process.env.UFOO_CODEX_INTERNAL_THREAD_TOOLS);
|
|
539
584
|
}
|
|
@@ -622,14 +667,6 @@ function buildWorkerThreadToolRuntime({ projectRoot, subscriber, observer }) {
|
|
|
622
667
|
};
|
|
623
668
|
}
|
|
624
669
|
|
|
625
|
-
function getClaudeThreadMode() {
|
|
626
|
-
const envValue = process.env.UFOO_CLAUDE_INTERNAL_THREAD_MODE;
|
|
627
|
-
const raw = String(envValue || "").trim().toLowerCase();
|
|
628
|
-
if (raw === "legacy" || raw === "off" || raw === "disabled" || raw === "0") return "legacy";
|
|
629
|
-
if (raw === "api") return "api";
|
|
630
|
-
return "api";
|
|
631
|
-
}
|
|
632
|
-
|
|
633
670
|
function buildClaudeAuthProvider(projectRoot) {
|
|
634
671
|
const config = loadConfig(projectRoot);
|
|
635
672
|
return async () => {
|
|
@@ -723,10 +760,6 @@ function createThreadRuntime({ projectRoot, provider, model, extraArgs = [], sub
|
|
|
723
760
|
}
|
|
724
761
|
|
|
725
762
|
if (provider === "codex-cli") {
|
|
726
|
-
if (getCodexThreadMode(projectRoot) !== "api") {
|
|
727
|
-
return disabledRuntime;
|
|
728
|
-
}
|
|
729
|
-
|
|
730
763
|
try {
|
|
731
764
|
const toolRuntime = buildWorkerThreadToolRuntime({
|
|
732
765
|
projectRoot,
|
|
@@ -773,15 +806,12 @@ function createThreadRuntime({ projectRoot, provider, model, extraArgs = [], sub
|
|
|
773
806
|
}
|
|
774
807
|
},
|
|
775
808
|
};
|
|
776
|
-
} catch {
|
|
777
|
-
return disabledRuntime;
|
|
809
|
+
} catch (error) {
|
|
810
|
+
return { ...disabledRuntime, error };
|
|
778
811
|
}
|
|
779
812
|
}
|
|
780
813
|
|
|
781
814
|
if (provider === "claude-cli") {
|
|
782
|
-
if (getClaudeThreadMode() !== "api") {
|
|
783
|
-
return disabledRuntime;
|
|
784
|
-
}
|
|
785
815
|
if (typeof createClaudeThreadProvider !== "function") {
|
|
786
816
|
return disabledRuntime;
|
|
787
817
|
}
|
|
@@ -823,8 +853,8 @@ function createThreadRuntime({ projectRoot, provider, model, extraArgs = [], sub
|
|
|
823
853
|
}
|
|
824
854
|
},
|
|
825
855
|
};
|
|
826
|
-
} catch {
|
|
827
|
-
return disabledRuntime;
|
|
856
|
+
} catch (error) {
|
|
857
|
+
return { ...disabledRuntime, error };
|
|
828
858
|
}
|
|
829
859
|
}
|
|
830
860
|
|
|
@@ -832,15 +862,15 @@ function createThreadRuntime({ projectRoot, provider, model, extraArgs = [], sub
|
|
|
832
862
|
}
|
|
833
863
|
|
|
834
864
|
async function runInternalRunner({ projectRoot, agentType = "codex", extraArgs = [] }) {
|
|
865
|
+
const normalizedAgentType = normalizeInternalAgentType(agentType);
|
|
866
|
+
if (!normalizedAgentType) throw new Error(`unsupported internal agent type: ${agentType}; use codex, claude or ucode`);
|
|
835
867
|
// Internal runner 必须由 daemon 启动,UFOO_SUBSCRIBER_ID 应该已经设置
|
|
836
868
|
const { subscriber, agentType: parsedAgentType, sessionId } = parseSubscriberId();
|
|
837
869
|
const nickname = process.env.UFOO_NICKNAME || "";
|
|
838
870
|
|
|
839
871
|
const queueDir = path.join(getUfooPaths(projectRoot).busQueuesDir, safeSubscriber(subscriber));
|
|
840
872
|
const queueFile = path.join(queueDir, "pending.jsonl");
|
|
841
|
-
const
|
|
842
|
-
const provider = ["ufoo", "ucode", "ufoo-code"].includes(normalizedAgentType)
|
|
843
|
-
? "ucode" : normalizedAgentType === "codex" ? "codex-cli" : "claude-cli";
|
|
873
|
+
const provider = { ucode: "ucode", codex: "codex-cli", claude: "claude-cli" }[normalizedAgentType];
|
|
844
874
|
const model = resolveInternalModel({ projectRoot, provider, extraArgs });
|
|
845
875
|
const bootstrap = resolveInternalBootstrap({
|
|
846
876
|
projectRoot,
|
|
@@ -863,9 +893,14 @@ async function runInternalRunner({ projectRoot, agentType = "codex", extraArgs =
|
|
|
863
893
|
let processing = false;
|
|
864
894
|
let lastHeartbeat = 0;
|
|
865
895
|
const HEARTBEAT_INTERVAL = 30000; // 30秒心跳间隔
|
|
896
|
+
const runnerAbort = new AbortController();
|
|
866
897
|
|
|
867
898
|
const stop = () => {
|
|
868
899
|
running = false;
|
|
900
|
+
runnerAbort.abort("runner_stopped");
|
|
901
|
+
// Closing the provider aborts an in-flight turn, which records cancellation
|
|
902
|
+
// and queues a terminal report before the runner drains and exits.
|
|
903
|
+
threadRuntime.close().catch(error => console.error(`[internal] stop failed: ${error.message}`));
|
|
869
904
|
};
|
|
870
905
|
|
|
871
906
|
process.on("SIGTERM", stop);
|
|
@@ -928,7 +963,7 @@ async function runInternalRunner({ projectRoot, agentType = "codex", extraArgs =
|
|
|
928
963
|
for (const claim of claims) {
|
|
929
964
|
const evt = claim.event;
|
|
930
965
|
const runnableEvents = [];
|
|
931
|
-
const rawInput =
|
|
966
|
+
const rawInput = parseInternalRawInput(evt && evt.data ? evt.data.message : "");
|
|
932
967
|
if (rawInput === null) {
|
|
933
968
|
runnableEvents.push(evt);
|
|
934
969
|
} else {
|
|
@@ -937,7 +972,7 @@ async function runInternalRunner({ projectRoot, agentType = "codex", extraArgs =
|
|
|
937
972
|
for (const message of submissions) {
|
|
938
973
|
runnableEvents.push({
|
|
939
974
|
...evt,
|
|
940
|
-
|
|
975
|
+
__internalRawInput: true,
|
|
941
976
|
data: {
|
|
942
977
|
...(evt.data || {}),
|
|
943
978
|
message,
|
|
@@ -965,9 +1000,10 @@ async function runInternalRunner({ projectRoot, agentType = "codex", extraArgs =
|
|
|
965
1000
|
bootstrap.extraArgs,
|
|
966
1001
|
threadRuntime,
|
|
967
1002
|
bootstrap.promptText,
|
|
968
|
-
activityTracker
|
|
1003
|
+
activityTracker,
|
|
1004
|
+
runnerAbort.signal
|
|
969
1005
|
);
|
|
970
|
-
if (runnableEvent.
|
|
1006
|
+
if (runnableEvent.__internalRawInput) {
|
|
971
1007
|
getInteractiveSession(runnableEvent.publisher || "unknown").writeResponsePrompt();
|
|
972
1008
|
}
|
|
973
1009
|
}
|
|
@@ -1005,13 +1041,11 @@ module.exports = {
|
|
|
1005
1041
|
createThreadRuntime,
|
|
1006
1042
|
resolveInternalModel,
|
|
1007
1043
|
resolveInternalCodexEffort,
|
|
1008
|
-
getCodexThreadMode,
|
|
1009
1044
|
getWorkerThreadToolMode,
|
|
1010
1045
|
buildWorkerThreadToolRuntime,
|
|
1011
1046
|
normalizeWorkerThreadToolMode,
|
|
1012
|
-
getClaudeThreadMode,
|
|
1013
1047
|
buildClaudeAuthProvider,
|
|
1014
|
-
|
|
1048
|
+
parseInternalRawInput,
|
|
1015
1049
|
createInteractiveInputSession,
|
|
1016
1050
|
resolveInternalBootstrap,
|
|
1017
1051
|
persistProviderSessionId,
|