u-foo 4.0.0 → 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 +88 -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/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 +8 -8
- package/src/agents/launch/notifier.js +2 -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 +50 -39
- 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 +2 -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/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 +1 -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
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const fs = require("fs");
|
|
4
|
+
const path = require("path");
|
|
5
|
+
const { getUfooPaths } = require("../state/paths");
|
|
6
|
+
const { redactSecrets } = require("../../runtime/privacy/redactor");
|
|
7
|
+
const { normalizeTraceContext } = require("../../agents/runtime/protocol/traceContext");
|
|
8
|
+
const { observationFingerprint } = require("../../agents/runtime/protocol/runObservation");
|
|
9
|
+
const { summarizeAgentPerformance } = require("./agentPerformance");
|
|
10
|
+
|
|
11
|
+
const TYPES = { run_config: "run.config", task_started: "task.started", task_completed: "task.completed", task_failed: "task.failed", task_cancelled: "task.cancelled", task_paused: "task.paused",
|
|
12
|
+
turn_started: "model.started", turn_completed: "model.completed", turn_failed: "model.failed", tool_call: "tool.started", text_delta: "message.delta", thinking_delta: "thinking.delta", context_usage: "context.usage" };
|
|
13
|
+
const clip = value => String(value || "").replace(/\s+/g, " ").slice(0, 240);
|
|
14
|
+
|
|
15
|
+
/** Read-only view over canonical journals, reports, display events and queues. */
|
|
16
|
+
function readAgentTrace(projectRoot, options = {}) {
|
|
17
|
+
const root = path.resolve(projectRoot);
|
|
18
|
+
const paths = getUfooPaths(root);
|
|
19
|
+
const warnings = [];
|
|
20
|
+
const entries = dir => {
|
|
21
|
+
try { return fs.readdirSync(dir, { withFileTypes: true }); }
|
|
22
|
+
catch (error) { if (error.code !== "ENOENT") warnings.push({ source: path.relative(root, dir), code: error.code || "source_unavailable" }); return []; }
|
|
23
|
+
};
|
|
24
|
+
let remaining = Math.max(1, Math.floor(Number(options.maxReadBytes) || 32 * 1024 * 1024));
|
|
25
|
+
const read = file => {
|
|
26
|
+
let fd;
|
|
27
|
+
try {
|
|
28
|
+
const stat = fs.lstatSync(file);
|
|
29
|
+
if (stat.isSymbolicLink()) return [];
|
|
30
|
+
if (!stat.isFile()) { warnings.push({ source: path.relative(root, file), code: "invalid_source_type" }); return []; }
|
|
31
|
+
fd = fs.openSync(file, "r");
|
|
32
|
+
const size = fs.fstatSync(fd).size;
|
|
33
|
+
const count = Math.min(size, 2 * 1024 * 1024, remaining);
|
|
34
|
+
if (count < size) warnings.push({ source: path.relative(root, file), code: "source_tail_truncated", totalBytes: size, readBytes: count });
|
|
35
|
+
if (!count) return [];
|
|
36
|
+
remaining -= count;
|
|
37
|
+
const buffer = Buffer.alloc(count);
|
|
38
|
+
fs.readSync(fd, buffer, 0, count, size - count);
|
|
39
|
+
const text = buffer.toString("utf8");
|
|
40
|
+
let lines = text.split("\n");
|
|
41
|
+
if (lines.at(-1)?.trim()) { warnings.push({ source: path.relative(root, file), code: "incomplete_record" }); lines.pop(); }
|
|
42
|
+
if (count < size) lines.shift();
|
|
43
|
+
return lines.flatMap((line, index) => {
|
|
44
|
+
if (!line.trim()) return [];
|
|
45
|
+
try {
|
|
46
|
+
const value = JSON.parse(line);
|
|
47
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("invalid record");
|
|
48
|
+
return [{ value, line: index, source: path.relative(root, file) }];
|
|
49
|
+
}
|
|
50
|
+
catch { warnings.push({ source: path.relative(root, file), code: "incomplete_or_invalid_record" }); return []; }
|
|
51
|
+
});
|
|
52
|
+
} catch (error) {
|
|
53
|
+
if (error.code !== "ENOENT") warnings.push({ source: path.relative(root, file), code: error.code || "source_unavailable" });
|
|
54
|
+
return [];
|
|
55
|
+
} finally { if (fd !== undefined) fs.closeSync(fd); }
|
|
56
|
+
};
|
|
57
|
+
const runtimes = [];
|
|
58
|
+
for (const namespace of entries(paths.agentDir).filter(e => e.isDirectory())) {
|
|
59
|
+
const dir = path.join(paths.agentDir, namespace.name, "runtimes");
|
|
60
|
+
for (const session of entries(dir).filter(e => e.isDirectory())) runtimes.push(path.join(dir, session.name, "events.jsonl"));
|
|
61
|
+
}
|
|
62
|
+
if (runtimes.length > 200) warnings.push({ code: "runtime_file_limit", total: runtimes.length, read: 200 });
|
|
63
|
+
const modified = file => { try { return fs.statSync(file).mtimeMs; } catch { return 0; } };
|
|
64
|
+
const records = runtimes.sort((a, b) => modified(b) - modified(a)).slice(0, 200).flatMap(read);
|
|
65
|
+
const tasks = new Map();
|
|
66
|
+
const events = [];
|
|
67
|
+
function add(event, record, index = "") {
|
|
68
|
+
const value = { id: `${record.source}:${record.value.eventId || record.value.seq || record.value.sequence || record.value.entry_id || record.value.timestamp || record.line}${index}`,
|
|
69
|
+
source: record.source, ...event, time: String(event.time || event.timestamp || event.ts || "") };
|
|
70
|
+
if (event.type === "observation.warning") warnings.push({ source: record.source, code: event.warning?.code || "observation_unavailable" });
|
|
71
|
+
delete value.eventId;
|
|
72
|
+
if (!options.details) { delete value.args; delete value.result; delete value.text; delete value.phase; delete value.message; delete value.error; }
|
|
73
|
+
events.push(value);
|
|
74
|
+
}
|
|
75
|
+
function normalize(event) {
|
|
76
|
+
const result = event.result || {};
|
|
77
|
+
return { type: event.type, time: event.time || event.timestamp || "", sequence: event.sequence,
|
|
78
|
+
sessionId: event.sessionId, agentId: event.agentId || (event.sessionId === "control" ? "ufoo-agent" : ""),
|
|
79
|
+
traceId: event.traceId, taskId: event.taskId || event.request?.taskId, taskRunId: event.taskRunId, parentTaskRunId: event.parentTaskRunId || event.request?.parentTaskRunId,
|
|
80
|
+
parentSessionId: event.parentSessionId, requestId: event.requestId || event.request?.requestId, turnId: event.turnId, toolCallId: event.toolCallId, toolName: event.toolName,
|
|
81
|
+
attemptId: event.attemptId, argumentFingerprint: event.argumentFingerprint || (event.args ? observationFingerprint(event.args) : undefined),
|
|
82
|
+
durationMs: event.durationMs, usage: event.usage || result.usage, status: event.status,
|
|
83
|
+
...(event.configuration ? { configuration: event.configuration } : {}),
|
|
84
|
+
...(event.repeatedSteps !== undefined ? { repeatedSteps: event.repeatedSteps } : {}),
|
|
85
|
+
...(typeof event.text === "string" ? { textCharacters: [...event.text].length } : {}),
|
|
86
|
+
...(typeof result.text === "string" ? { finalTextCharacters: [...result.text].length } : {}),
|
|
87
|
+
...(event.finalTextCharacters != null ? { finalTextCharacters: event.finalTextCharacters } : {}),
|
|
88
|
+
...(result.code ? { resultCode: result.code } : {}),
|
|
89
|
+
provider: event.provider, model: event.model, transport: event.transport, estimatedInputTokens: event.estimatedInputTokens,
|
|
90
|
+
...(["model.started", "model.completed", "model.failed"].includes(event.type) ? { modelScope: event.modelScope || "api-call" } : {}),
|
|
91
|
+
summary: clip(event.error?.message || event.error || result.error?.message || result.error || event.text || result.text || event.phase?.type || event.type),
|
|
92
|
+
...(event.args ? { args: event.args } : {}), ...(event.result ? { result: event.result, ok: result.ok } : {}),
|
|
93
|
+
...(event.text ? { text: event.text } : {}), ...(event.phase ? { phase: event.phase } : {}),
|
|
94
|
+
...(event.binding ? { binding: event.binding } : {}), ...(event.code ? { code: event.code } : {}), ...(event.outcome ? { outcome: event.outcome } : {}),
|
|
95
|
+
...(event.warning ? { warning: event.warning } : {}),
|
|
96
|
+
...(event.error ? { error: event.error } : {}),
|
|
97
|
+
...(String(event.type || "").startsWith("context.compaction") ? { coveredCount: event.coveredCount, batchCount: event.batchCount, checkpointVersion: event.version, sourceArchive: event.sourceArchive } : {}) };
|
|
98
|
+
}
|
|
99
|
+
for (const record of records) {
|
|
100
|
+
const e = record.value;
|
|
101
|
+
if (e.type === "capability.state_committed") {
|
|
102
|
+
const assignments = e.capabilityId === "agent-management" ? e.value?.tasks : e.capabilityId === "task-execution" ? e.value?.jobs : null;
|
|
103
|
+
for (const task of Object.values(assignments || {})) {
|
|
104
|
+
const id = task.taskId || task.taskRunId || task.id;
|
|
105
|
+
const previous = tasks.get(id);
|
|
106
|
+
if (previous?.status !== task.status || previous?.report?.entry_id !== task.report?.entry_id) add({ type: "delegation.state", time: e.time,
|
|
107
|
+
taskId: id, taskRunId: task.taskRunId, traceId: task.traceId, parentTaskRunId: task.parentTaskRunId, parentSessionId: task.parentSessionId,
|
|
108
|
+
agentId: task.workerId || task.id, status: task.status, summary: `${task.status}${task.report?.phase ? ` (${task.report.phase})` : ""}` }, record, `:${id}`);
|
|
109
|
+
tasks.set(id, task);
|
|
110
|
+
}
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
if (e.type && typeof e.type !== "string") { warnings.push({ source: record.source, code: "invalid_event_type" }); continue; }
|
|
114
|
+
if (!e.type || ["command.started", "command.resolved"].includes(e.type)) {
|
|
115
|
+
if (e.type) {
|
|
116
|
+
const task = [...tasks.values()].find(task => task.commandIds?.includes(e.commandId));
|
|
117
|
+
add({ ...normalize(e), taskId: task?.taskId, parentTaskRunId: task?.parentTaskRunId, traceId: task?.traceId,
|
|
118
|
+
agentId: task?.workerId || "ufoo-agent", commandId: e.commandId, commandKind: e.kind,
|
|
119
|
+
summary: `${e.type} ${e.kind || e.commandId || ""}` }, record);
|
|
120
|
+
}
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
add(normalize(e), record);
|
|
124
|
+
}
|
|
125
|
+
const busFiles = entries(paths.busEventsDir).filter(e => e.isFile() && e.name.endsWith(".jsonl")).map(e => path.join(paths.busEventsDir, e.name)).sort().reverse();
|
|
126
|
+
if (busFiles.length > 14) warnings.push({ code: "bus_day_limit", total: busFiles.length, read: 14 });
|
|
127
|
+
const bus = busFiles.slice(0, 14).flatMap(read);
|
|
128
|
+
const nativeRuns = new Set(records.filter(r => r.source.includes("/ucode/runtimes/"))
|
|
129
|
+
.flatMap(r => [r.value.taskRunId, r.value.parentTaskRunId]).filter(Boolean));
|
|
130
|
+
const committedEvents = new Set(records.map(r => r.value.eventId).filter(Boolean));
|
|
131
|
+
for (const record of bus) {
|
|
132
|
+
const e = record.value;
|
|
133
|
+
if (e.event === "agent_surface") {
|
|
134
|
+
const surface = e.data?.surface || {};
|
|
135
|
+
// Native core events have their own canonical journal. Avoid displaying
|
|
136
|
+
// the same tool/text lifecycle again through its presentation adapter.
|
|
137
|
+
if (surface.type === "runtime_event") {
|
|
138
|
+
if (surface.event && !committedEvents.has(surface.event.eventId)) add({ ...normalize(surface.event),
|
|
139
|
+
agentId: e.publisher, taskId: surface.task_id || surface.taskId, time: surface.event.time || e.timestamp }, record);
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
if (nativeRuns.has(surface.taskRunId) && ["tool_call", "tool_result", "text_delta", "thinking_delta", "turn_started", "turn_completed"].includes(surface.type)) continue;
|
|
143
|
+
const type = surface.type === "tool_result" ? surface.status === "in_progress" ? "tool.progress" : "tool.completed" : TYPES[surface.type] || surface.type;
|
|
144
|
+
add({ ...normalize({ ...surface, type, modelScope: "sdk-turn", toolName: surface.name, text: surface.delta, result: surface.type === "tool_result" ? { output: surface.output,
|
|
145
|
+
ok: surface.is_error !== true && surface.status !== "failed" && (!Number.isFinite(surface.exitCode) || surface.exitCode === 0), exitCode: surface.exitCode } : undefined }),
|
|
146
|
+
time: e.timestamp, agentId: e.publisher, taskId: surface.task_id || surface.taskId, busSequence: e.seq, queueSequence: surface.queueSequence, model: surface.model, provider: surface.provider,
|
|
147
|
+
summary: clip(surface.error || surface.delta || surface.name || surface.phase?.type || type) }, record);
|
|
148
|
+
} else if (e.event === "message" && e.data?.runtime_context) {
|
|
149
|
+
add({ ...normalizeTraceContext(e.data.runtime_context), type: "queue.enqueued", time: e.timestamp, agentId: e.target, publisher: e.publisher,
|
|
150
|
+
busSequence: e.seq, taskId: e.data.task_id, summary: clip(e.data.message), ...(options.details ? { message: e.data.message } : {}) }, record);
|
|
151
|
+
} else if (e.event === "activity_state_changed") {
|
|
152
|
+
add({ type: "agent.activity", time: e.timestamp, agentId: e.publisher, status: e.data?.state, summary: [e.data?.state, e.data?.detail].filter(Boolean).join(" ") }, record);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
for (const record of read(path.join(paths.agentDir, "reports.jsonl"))) {
|
|
156
|
+
const e = record.value;
|
|
157
|
+
add({ ...normalizeTraceContext(e.meta), type: `report.${e.phase}`, time: e.ts, agentId: e.agent_id, taskId: e.task_id, reportSource: e.source,
|
|
158
|
+
reportCharacters: [...String(e.summary || e.message || e.error || "")].length,
|
|
159
|
+
...(e.meta?.cancelled ? { cancelled: true } : {}),
|
|
160
|
+
reportId: e.entry_id, scope: e.scope, controllerId: e.controller_id, summary: clip(e.error || e.summary || e.message || e.phase) }, record);
|
|
161
|
+
}
|
|
162
|
+
const queues = [];
|
|
163
|
+
for (const dir of entries(paths.busQueuesDir).filter(e => e.isDirectory())) {
|
|
164
|
+
const base = path.join(paths.busQueuesDir, dir.name);
|
|
165
|
+
for (const file of entries(base).filter(e => e.isFile() && (e.name === "pending.jsonl" || e.name.includes("processing")))) {
|
|
166
|
+
for (const record of read(path.join(base, file.name))) {
|
|
167
|
+
const e = record.value;
|
|
168
|
+
queues.push({ agentId: e.target, publisher: e.publisher, taskId: e.data?.task_id || e.data?.runtime_context?.taskId,
|
|
169
|
+
sequence: e.seq, enqueuedAt: e.timestamp, state: file.name === "pending.jsonl" ? "pending" : "claimed", source: record.source });
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
const reportQueue = path.join(paths.busDir, "control", "report");
|
|
174
|
+
for (const file of entries(reportQueue).filter(e => e.isFile() && (e.name === "pending.jsonl" || e.name.includes("processing")))) {
|
|
175
|
+
for (const record of read(path.join(reportQueue, file.name))) {
|
|
176
|
+
const report = record.value.data?.report;
|
|
177
|
+
if (report) queues.push({ kind: "report", agentId: report.agent_id, taskId: report.task_id, phase: report.phase,
|
|
178
|
+
state: file.name === "pending.jsonl" ? "pending" : "claimed", source: record.source });
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
let agents = {};
|
|
182
|
+
try { agents = JSON.parse(fs.readFileSync(paths.agentsFile, "utf8")).agents || {}; } catch { /* optional registration */ }
|
|
183
|
+
const requestedAgent = options.agent_id || "";
|
|
184
|
+
const agentId = Object.keys(agents).find(id => id === requestedAgent || agents[id].nickname === requestedAgent) || requestedAgent;
|
|
185
|
+
const selected = String(options.task_id || "");
|
|
186
|
+
const related = new Set(selected ? [selected] : []);
|
|
187
|
+
if (selected) {
|
|
188
|
+
// Expand only descendants; include parent lifecycle as evidence without
|
|
189
|
+
// pulling in unrelated sibling jobs that happen to share that parent.
|
|
190
|
+
let changed = true;
|
|
191
|
+
while (changed) {
|
|
192
|
+
changed = false;
|
|
193
|
+
for (const task of tasks.values()) if (related.has(task.taskId || task.taskRunId || task.id) || related.has(task.parentTaskRunId)) {
|
|
194
|
+
for (const id of [task.taskId, task.taskRunId, task.id].filter(Boolean)) if (!related.has(id)) { related.add(id); changed = true; }
|
|
195
|
+
}
|
|
196
|
+
for (const e of events) if (related.has(e.taskId) && e.taskRunId && !related.has(e.taskRunId)) { related.add(e.taskRunId); changed = true; }
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
const selectedTasks = [...tasks.values()].filter(t => (!selected || related.has(t.taskId || t.taskRunId || t.id)) && (!agentId || t.workerId === agentId || t.id === agentId));
|
|
200
|
+
const parents = new Set(selectedTasks.map(t => t.parentTaskRunId).filter(Boolean));
|
|
201
|
+
const since = options.since ? Date.parse(options.since) : null;
|
|
202
|
+
if (since !== null && !Number.isFinite(since)) throw new Error("since must be an ISO timestamp");
|
|
203
|
+
const scoped = events.filter(e => (!selected || related.has(e.taskId) || related.has(e.taskRunId) || parents.has(e.taskRunId))
|
|
204
|
+
&& (!agentId || e.agentId === agentId)
|
|
205
|
+
&& (!options.session_id || e.sessionId === options.session_id)).sort((a, b) => a.time.localeCompare(b.time)
|
|
206
|
+
|| (a.source === b.source ? (a.sequence || a.busSequence || 0) - (b.sequence || b.busSequence || 0) : 0) || a.id.localeCompare(b.id));
|
|
207
|
+
const matched = scoped.filter(e => since === null || Date.parse(e.time) >= since);
|
|
208
|
+
const selectedQueues = queues.filter(q => (!selected || related.has(q.taskId)) && (!agentId || q.agentId === agentId));
|
|
209
|
+
const limit = Math.max(1, Math.min(2000, Number(options.limit) || 200));
|
|
210
|
+
const offset = options.offset === undefined ? Math.max(0, matched.length - limit) : Math.max(0, Math.floor(Number(options.offset) || 0));
|
|
211
|
+
const last = offset + limit;
|
|
212
|
+
const toolCalls = new Map();
|
|
213
|
+
for (const e of matched.filter(e => ["tool.started", "tool.completed", "tool.failed"].includes(e.type))) {
|
|
214
|
+
if (!e.toolCallId) warnings.push({ source: e.source, code: "missing_tool_call_id" });
|
|
215
|
+
const key = `${e.taskRunId || e.taskId || e.agentId}:${e.toolCallId || e.id}`;
|
|
216
|
+
if (!toolCalls.has(key)) toolCalls.set(key, { toolCallId: e.toolCallId, toolName: e.toolName, agentId: e.agentId, taskRunId: e.taskRunId, started: false, ended: false });
|
|
217
|
+
const call = toolCalls.get(key);
|
|
218
|
+
if (e.type === "tool.started") { call.started = true; call.startedAt ||= e.time; }
|
|
219
|
+
else { call.ended = true; call.endedAt = e.time; call.outcome = e.type === "tool.failed" ? "unknown" : e.ok === false ? "error" : "ok";
|
|
220
|
+
call.durationMs = e.durationMs ?? (call.startedAt ? Math.max(0, Date.parse(e.time) - Date.parse(call.startedAt)) : undefined); }
|
|
221
|
+
}
|
|
222
|
+
const taskView = task => options.details ? task : { taskId: task.taskId || task.id, taskRunId: task.taskRunId,
|
|
223
|
+
traceId: task.traceId, workerId: task.workerId, parentTaskRunId: task.parentTaskRunId, parentSessionId: task.parentSessionId,
|
|
224
|
+
status: task.status, reportPhase: task.report?.phase, summary: clip(task.report?.error || task.report?.summary || task.report?.message), acceptance: task.acceptance };
|
|
225
|
+
const performance = summarizeAgentPerformance(scoped.filter(e => !selected || related.has(e.taskId) || related.has(e.taskRunId)), selectedTasks, selectedQueues,
|
|
226
|
+
{ ...(options.performanceQuery || { since: options.since, includeRuns: false }), warnings });
|
|
227
|
+
return redactSecrets({ version: 1, projectRoot: root, taskId: selected || null, total: matched.length, offset,
|
|
228
|
+
next_offset: last < matched.length ? last : null, has_more_before: offset > 0,
|
|
229
|
+
events: matched.slice(offset, last), tasks: selectedTasks.slice(-100).map(taskView),
|
|
230
|
+
counts: { modelCalls: matched.filter(e => e.type === "model.started" && e.modelScope === "api-call").length,
|
|
231
|
+
sdkTurns: matched.filter(e => e.type === "model.started" && e.modelScope === "sdk-turn").length,
|
|
232
|
+
modelFailures: matched.filter(e => e.type === "model.failed").length, toolCalls: toolCalls.size,
|
|
233
|
+
toolErrors: [...toolCalls.values()].filter(t => t.outcome === "error").length,
|
|
234
|
+
unresolvedTools: [...toolCalls.values()].filter(t => !t.ended || t.outcome === "unknown").length,
|
|
235
|
+
compactions: matched.filter(e => e.type === "context.compaction.completed").length,
|
|
236
|
+
compactionFailures: matched.filter(e => e.type === "context.compaction.failed").length },
|
|
237
|
+
tools: [...toolCalls.values()],
|
|
238
|
+
performance,
|
|
239
|
+
queues: selectedQueues.slice(-100),
|
|
240
|
+
incomplete: warnings.length > 0, warnings });
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function readAgentPerformance(projectRoot, options = {}) {
|
|
244
|
+
const trace = readAgentTrace(projectRoot, { task_id: options.task_id, agent_id: options.agent_id, session_id: options.session_id,
|
|
245
|
+
maxReadBytes: options.maxReadBytes, limit: 1, performanceQuery: options });
|
|
246
|
+
return { projectRoot: trace.projectRoot, taskId: trace.taskId, ...trace.performance };
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
module.exports = { readAgentTrace, readAgentPerformance };
|
|
@@ -23,7 +23,7 @@ function createWorkspaceAccess({ projectRoot, externalWriters = () => [] } = {})
|
|
|
23
23
|
if (!["write", "edit", "bash"].includes(context.tool)) return operation();
|
|
24
24
|
const workspace = key(context.workspaceRoot);
|
|
25
25
|
const writers = workspace === root ? externalWriters(context) : [];
|
|
26
|
-
if (writers.length) return { ok: false, code: "workspace_busy", error: "
|
|
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
27
|
return leases.run({ key: workspace, ownerId: context.taskRunId || context.sessionId || `process-${process.pid}`, signal: context.signal }, operation);
|
|
28
28
|
},
|
|
29
29
|
async runTask(context, operation) {
|
|
@@ -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";
|
|
@@ -1,7 +1,16 @@
|
|
|
1
1
|
"use strict";
|
|
2
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
|
+
|
|
3
11
|
function isInternalAgentMeta(meta = {}) {
|
|
4
|
-
|
|
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]));
|
|
5
14
|
}
|
|
6
15
|
|
|
7
16
|
function isInternalDashboardEvent(data = {}, getMeta = () => null) {
|
|
@@ -14,4 +23,4 @@ function isInternalDashboardEvent(data = {}, getMeta = () => null) {
|
|
|
14
23
|
return isInternalAgentMeta(getMeta(agentId));
|
|
15
24
|
}
|
|
16
25
|
|
|
17
|
-
module.exports = { isInternalAgentMeta, isInternalDashboardEvent };
|
|
26
|
+
module.exports = { INTERNAL_AGENT_TYPES, normalizeInternalAgentType, isInternalAgentMeta, isInternalDashboardEvent };
|
|
@@ -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,12 +47,11 @@ 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
|
-
"
|
|
48
|
-
"
|
|
49
|
-
"multi.toggle",
|
|
53
|
+
"window.set",
|
|
54
|
+
"window.cycle",
|
|
50
55
|
"multi.focus",
|
|
51
56
|
"multi.viewport",
|
|
52
57
|
"multi.raw",
|
|
@@ -79,18 +84,14 @@ const EVENT_NAMES = Object.freeze([
|
|
|
79
84
|
"tool.group",
|
|
80
85
|
"settings.snapshot",
|
|
81
86
|
"prompt.apply_paste",
|
|
87
|
+
"prompt.set_text",
|
|
88
|
+
"prompt.restore",
|
|
82
89
|
"prompt.set_prefix",
|
|
83
90
|
"attachments.set",
|
|
84
91
|
"usage.set",
|
|
85
|
-
"agent.view.open",
|
|
86
|
-
"agent.view.append",
|
|
87
|
-
"agent.view.status",
|
|
88
|
-
"agent.view.close",
|
|
89
|
-
"ui.suspend.prepare",
|
|
90
|
-
"ui.resume",
|
|
91
92
|
"connection.set",
|
|
92
93
|
"error",
|
|
93
|
-
"
|
|
94
|
+
"window.set",
|
|
94
95
|
"multi.pane.frame",
|
|
95
96
|
]);
|
|
96
97
|
|
|
@@ -135,9 +136,6 @@ function validateEnvelope(raw) {
|
|
|
135
136
|
if (!KINDS.includes(String(raw.kind || ""))) {
|
|
136
137
|
errors.push(`invalid kind "${raw.kind}"`);
|
|
137
138
|
}
|
|
138
|
-
if (raw.kind === "command" && raw.name && !COMMAND_NAMES.includes(String(raw.name))) {
|
|
139
|
-
// Additive: unknown commands are soft-fail for forward compat.
|
|
140
|
-
}
|
|
141
139
|
if (raw.payload != null && typeof raw.payload !== "object") {
|
|
142
140
|
errors.push("payload must be an object");
|
|
143
141
|
}
|
|
@@ -185,6 +183,7 @@ function createSeqCounter(start = 0) {
|
|
|
185
183
|
module.exports = {
|
|
186
184
|
PROTOCOL,
|
|
187
185
|
MULTI_FRAMES_CAPABILITY,
|
|
186
|
+
WINDOW_MODES_CAPABILITY,
|
|
188
187
|
KINDS,
|
|
189
188
|
COMMAND_NAMES,
|
|
190
189
|
EVENT_NAMES,
|
|
@@ -4,6 +4,7 @@ const fs = require("fs");
|
|
|
4
4
|
const path = require("path");
|
|
5
5
|
const { createHash, randomUUID } = require("crypto");
|
|
6
6
|
const { stableStringify } = require("../../agents/runtime/core/stableJson");
|
|
7
|
+
const { resolveToolBudget, resolveTaskTimeoutMs } = require("../../agents/runtime/core/executionBudget");
|
|
7
8
|
const { spawnSync } = require("child_process");
|
|
8
9
|
const { createAgentRuntime, createRuntimeStore, createTaskScheduler } = require("../../agents/runtime");
|
|
9
10
|
const { createMainCapabilities, createGlobalCapabilities } = require("../../agents/capabilities");
|
|
@@ -15,8 +16,8 @@ const { executeControllerTool } = require("../../agents/controller/controllerToo
|
|
|
15
16
|
const { TOOL_PERMISSIONS } = require("../../agents/capabilities/coordination");
|
|
16
17
|
const { getNativeTransport } = require("../../agents/providers/nativeTransport");
|
|
17
18
|
const { resolveRuntimeConfig } = require("../../agents/providers/runtimeConfig");
|
|
18
|
-
const { resolveUpstreamRuntime, normalizeProvider } = require("../../agents/providers/
|
|
19
|
-
const { loadConfig, defaultAgentModelForProvider } = require("../../config");
|
|
19
|
+
const { resolveUpstreamRuntime, normalizeProvider } = require("../../agents/providers/upstreamRuntime");
|
|
20
|
+
const { loadConfig, defaultAgentModelForProvider, sameModelProvider } = require("../../config");
|
|
20
21
|
const mainProfile = require("../../agents/profiles/main");
|
|
21
22
|
const globalProfile = require("../../agents/profiles/globalRouter");
|
|
22
23
|
const { buildMainAgentPrompt, buildCodingTaskPrompt } = require("../../agents/prompts/mainAgent");
|
|
@@ -33,8 +34,9 @@ const { listProjectRuntimes, isGlobalControllerProjectRoot } = require("../proje
|
|
|
33
34
|
const { canonicalProjectRoot, buildProjectId } = require("../projects/projectId");
|
|
34
35
|
const { resolveWorkspacePath } = require("../../code/tools/common");
|
|
35
36
|
const { listControllerInboxEntries } = require("../../coordination/report/store");
|
|
36
|
-
const { readControllerSummary } = require("../../coordination/history/controllerSummary");
|
|
37
37
|
const { redactSecrets } = require("../privacy/redactor");
|
|
38
|
+
const { createContextManager } = require("../../agents/runtime/context/compaction");
|
|
39
|
+
const { replayHistory } = require("../../agents/runtime/context/replayHistory");
|
|
38
40
|
|
|
39
41
|
const hash = (value) => createHash("sha256").update(value).digest("hex").slice(0, 32);
|
|
40
42
|
const safeId = (value) => /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,100}$/.test(value || "");
|
|
@@ -53,7 +55,7 @@ function resolveTaskWorkspace(projectRoot, requested = "") {
|
|
|
53
55
|
|
|
54
56
|
/** Project-owned runtime instances. A client disconnect never owns their cancellation. */
|
|
55
57
|
function createAgentHost({ projectRoot, provider, model, ports = {}, onEvent = () => {}, log = () => {},
|
|
56
|
-
resolveProvider = resolveUpstreamRuntime, transportFactory = getNativeTransport, maxConcurrent = 2 } = {}) {
|
|
58
|
+
resolveProvider = resolveUpstreamRuntime, transportFactory = getNativeTransport, maxConcurrent = 2, contextPolicy = {} } = {}) {
|
|
57
59
|
const root = canonicalProjectRoot(projectRoot);
|
|
58
60
|
const projectId = buildProjectId(root);
|
|
59
61
|
const global = isGlobalControllerProjectRoot(root);
|
|
@@ -61,7 +63,6 @@ function createAgentHost({ projectRoot, provider, model, ports = {}, onEvent = (
|
|
|
61
63
|
const children = new Map();
|
|
62
64
|
const stores = new Map();
|
|
63
65
|
const scheduler = createTaskScheduler({ maxConcurrent });
|
|
64
|
-
const compatibilityScheduler = createTaskScheduler({ maxConcurrent: 1 });
|
|
65
66
|
const conversationScheduler = createTaskScheduler({ maxConcurrent: 2, maxQueued: 128 });
|
|
66
67
|
const control = createRuntimeStore({ workspaceRoot: root, namespace: "main-control", sessionId: "control", redact: redactSecrets });
|
|
67
68
|
let closed = false;
|
|
@@ -108,12 +109,22 @@ function createAgentHost({ projectRoot, provider, model, ports = {}, onEvent = (
|
|
|
108
109
|
const rows = await coordinatedOps(root, [{ action: "launch", ...args }], ports.processManager);
|
|
109
110
|
return { ok: Array.isArray(rows) && rows.some((row) => row.action === "launch" && row.ok !== false), ops_results: rows };
|
|
110
111
|
},
|
|
111
|
-
dispatch: async ({ target, message }) => {
|
|
112
|
-
const receipts = await ports.dispatchMessages(root, [{ target, message, source: "ufoo-agent", injection_mode: "immediate" }]);
|
|
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 });
|
|
113
114
|
if (ports.markPending) ports.markPending(target);
|
|
114
|
-
return { ok:
|
|
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") });
|
|
115
127
|
},
|
|
116
|
-
wake: (request) => getSession(Object.values(management.snapshot().tasks).find((task) => task.taskId === request.taskId)?.parentSessionId || "main-default").submit(request),
|
|
117
128
|
emit: (event) => { const state = control.append(event); publish({ ...event, sessionId: "control", sequence: state.sequence }); },
|
|
118
129
|
validateEvidence(evidence, task, context) {
|
|
119
130
|
return validateEvidence(evidence, context, task.report.ts);
|
|
@@ -178,21 +189,45 @@ function createAgentHost({ projectRoot, provider, model, ports = {}, onEvent = (
|
|
|
178
189
|
function makeRuntime({ sessionId, namespace, profile, capabilities, host, workspaceRoot = root, child = null }) {
|
|
179
190
|
const productConfig = loadConfig(root);
|
|
180
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
|
+
} });
|
|
181
205
|
const previousBinding = store.read().binding;
|
|
182
206
|
const configuredProvider = normalizeProvider(provider || productConfig.agentProvider || "ucode");
|
|
183
207
|
const useCodingConfig = previousBinding?.codingConfig ?? configuredProvider === "ucode";
|
|
184
208
|
const selectedProvider = useCodingConfig ? "" : previousBinding?.provider || configuredProvider;
|
|
185
|
-
const
|
|
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));
|
|
186
213
|
const config = resolveRuntimeConfig({ workspaceRoot: root, provider: selectedProvider, model: selectedModel, useCodingConfig });
|
|
187
214
|
const transport = transportFactory(config.transport);
|
|
188
|
-
const binding = { provider: selectedProvider || config.provider, model: config.model, transport: config.transport, codingConfig: useCodingConfig
|
|
215
|
+
const binding = { provider: selectedProvider || config.provider, model: config.model, transport: config.transport, codingConfig: useCodingConfig,
|
|
216
|
+
modelRevision: changedModel || !previousBinding ? modelRevision : previousBinding.modelRevision || 0 };
|
|
189
217
|
store.transaction((state) => {
|
|
190
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" });
|
|
191
|
-
return state.binding
|
|
219
|
+
return !state.binding || changedModel ? [{ type: "runtime.binding", binding }] : [];
|
|
192
220
|
});
|
|
193
221
|
stores.set(sessionId, store);
|
|
194
222
|
let runtime;
|
|
195
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
|
+
}
|
|
196
231
|
const resolved = useCodingConfig && config.apiKey && config.apiKeySource !== "kimi-credential"
|
|
197
232
|
? { ...config, auth: { apiKey: config.apiKey } }
|
|
198
233
|
: await resolveProvider({ projectRoot: root, provider: selectedProvider || config.provider, model: config.model });
|
|
@@ -206,7 +241,6 @@ function createAgentHost({ projectRoot, provider, model, ports = {}, onEvent = (
|
|
|
206
241
|
context.push({ requestMeta: request.requestMeta || {}, reports: listControllerInboxEntries(root, "ufoo-agent", { num: 30 })
|
|
207
242
|
.filter((report) => isInternalAgentMeta(registered[report.agent_id])) });
|
|
208
243
|
}
|
|
209
|
-
if (!child) context.push(readControllerSummary(root));
|
|
210
244
|
const sources = await runtime.buildContext({ workspaceRoot, prompt: request.text, promptText: request.text });
|
|
211
245
|
const skillSource = sources.find((source) => source.capabilityId === "skills")?.value;
|
|
212
246
|
const skillBlocks = (skillSource?.blocks || []).join("\n\n").slice(0, 65536);
|
|
@@ -214,16 +248,18 @@ function createAgentHost({ projectRoot, provider, model, ports = {}, onEvent = (
|
|
|
214
248
|
if (skillSource) context.push({ skills: { active: skillSource.activeSkills, warnings: skillSource.warnings } });
|
|
215
249
|
const instructionFile = path.join(workspaceRoot, "AGENTS.md");
|
|
216
250
|
const instructions = fs.existsSync(instructionFile) ? fs.readFileSync(instructionFile, "utf8").slice(0, 16000) : "";
|
|
217
|
-
const history = child ? [] :
|
|
218
|
-
.flatMap((item) => [{ role: "user", content: item.request.text.slice(0, 4000) }, { role: "assistant", content: String(item.result?.text || "").slice(-6000) }]);
|
|
251
|
+
const history = child ? [] : replayHistory(store.events(), task.taskRunId);
|
|
219
252
|
const attachments = (request.attachments || []).map((attachment) => resolveWorkspacePath(workspaceRoot, typeof attachment === "string" ? attachment : attachment.path).resolved);
|
|
220
253
|
return { workspaceRoot, sessionId, projectId, agentId: child ? child.id : "ufoo-agent", artifactNamespace: namespace,
|
|
221
254
|
model: resolved.model, provider: resolved.provider === "claude" ? "anthropic" : resolved.provider,
|
|
222
255
|
baseUrl: resolved.baseUrl, apiKey: resolved.auth?.apiKey || "", requestHeaders: resolved.auth?.headers || {},
|
|
223
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",
|
|
224
259
|
prompt: resumed ? "" : request.text + (attachments.length ? `\n\nWorkspace attachments (read with read/read_image): ${JSON.stringify(attachments)}` : ""), historyMessages: history,
|
|
225
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 }),
|
|
226
|
-
|
|
261
|
+
timeoutMs: resolveTaskTimeoutMs(), toolBudget: resolveToolBudget(),
|
|
262
|
+
contextManager,
|
|
227
263
|
};
|
|
228
264
|
};
|
|
229
265
|
runtime = createAgentRuntime({ profile, capabilities, transport,
|
|
@@ -238,7 +274,8 @@ function createAgentHost({ projectRoot, provider, model, ports = {}, onEvent = (
|
|
|
238
274
|
if (!resolved.ok) throw new Error(resolved.error);
|
|
239
275
|
const paired = materializeAnswerToolResult(previous.messages, resolved.resume, resolved.answer);
|
|
240
276
|
if (!paired.ok) throw new Error(paired.error);
|
|
241
|
-
return { ...await prepare(task.request, task, true), historyMessages: previous.messages,
|
|
277
|
+
return { ...await prepare(task.request, task, true), historyMessages: previous.messages, historyOffset: previous.historyOffset,
|
|
278
|
+
executionState: previous.executionState, resume: true };
|
|
242
279
|
},
|
|
243
280
|
eventSink(event) {
|
|
244
281
|
publish({ ...event, sessionId });
|
|
@@ -307,11 +344,6 @@ function createAgentHost({ projectRoot, provider, model, ports = {}, onEvent = (
|
|
|
307
344
|
}
|
|
308
345
|
return Object.freeze({
|
|
309
346
|
getSession, resolveRuntime, taskPort, management, publicEvent, workspaceAccess, projectRoot: root,
|
|
310
|
-
runCompatibility({ originalPrompt, requestId }, invoke) {
|
|
311
|
-
const commandId = `compat-${hash(requestId)}`;
|
|
312
|
-
return management.commands.execute({ commandId, kind: "controller-compatibility", args: { prompt: originalPrompt } },
|
|
313
|
-
() => compatibilityScheduler.schedule({ id: commandId }, invoke));
|
|
314
|
-
},
|
|
315
347
|
findRuntime({ taskRunId, interactionId, sessionId } = {}) {
|
|
316
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;
|
|
317
349
|
return resolveRuntime(sessionId);
|
|
@@ -322,7 +354,7 @@ function createAgentHost({ projectRoot, provider, model, ports = {}, onEvent = (
|
|
|
322
354
|
const accepted = runtime.submit({ requestId, text: prompt, requestMeta });
|
|
323
355
|
const task = await runtime.wait(accepted.taskRunId);
|
|
324
356
|
if (["failed", "cancelled", "interrupted"].includes(task.status)) return { ok: false, error: task.error, taskRunId: task.taskRunId };
|
|
325
|
-
let payload = { reply: task.result?.text || "", dispatch: [], ops: [] };
|
|
357
|
+
let payload = { reply: typeof task.result?.finalText === "string" ? task.result.finalText : task.result?.text || "", dispatch: [], ops: [] };
|
|
326
358
|
if (global) {
|
|
327
359
|
try { payload = JSON.parse(payload.reply); } catch { return { ok: false, error: "global router returned invalid JSON" }; }
|
|
328
360
|
if (!payload || typeof payload !== "object" || Array.isArray(payload) || typeof payload.reply !== "string") return { ok: false, error: "global router returned an invalid payload" };
|
|
@@ -341,7 +373,7 @@ function createAgentHost({ projectRoot, provider, model, ports = {}, onEvent = (
|
|
|
341
373
|
},
|
|
342
374
|
snapshot: () => ({ sessions: [...sessions].map(([sessionId, runtime]) => ({ sessionId, sequence: runtime.snapshot().sequence,
|
|
343
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 })) })),
|
|
344
|
-
children: Object.values(jobs()).map(publicChild), delegated: Object.values(management.snapshot().tasks), scheduler: scheduler.snapshot(), conversations: conversationScheduler.snapshot(),
|
|
376
|
+
children: Object.values(jobs()).map(publicChild), delegated: Object.values(management.snapshot().tasks), scheduler: scheduler.snapshot(), conversations: conversationScheduler.snapshot(),
|
|
345
377
|
uncertainReceipts: Object.values(control.read().commands).filter((command) => command.status === "uncertain").map(({ commandId, kind, time }) => ({ commandId, kind, time })) }),
|
|
346
378
|
async recover() {
|
|
347
379
|
const directory = path.join(root, ".ufoo", "agent", global ? "global-router" : "main", "runtimes");
|
|
@@ -368,7 +400,7 @@ function createAgentHost({ projectRoot, provider, model, ports = {}, onEvent = (
|
|
|
368
400
|
for (const report of listControllerInboxEntries(root, "ufoo-agent", { num: 1000 })) await management.report(report);
|
|
369
401
|
await management.flushWakes(); flushChildWakes();
|
|
370
402
|
},
|
|
371
|
-
async close() { closed = true; await Promise.allSettled([...sessions.values(), ...children.values()].map((runtime) => runtime.close())); await scheduler.close(); await conversationScheduler.close();
|
|
403
|
+
async close() { closed = true; await Promise.allSettled([...sessions.values(), ...children.values()].map((runtime) => runtime.close())); await scheduler.close(); await conversationScheduler.close(); },
|
|
372
404
|
});
|
|
373
405
|
}
|
|
374
406
|
|