u-foo 4.0.2 → 4.0.5
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/README.md +22 -4
- package/README.zh-CN.md +5 -4
- package/dist/tui/darwin-arm64/ufoo-tui +0 -0
- package/dist/tui/darwin-x64/ufoo-tui +0 -0
- package/dist/tui/linux-arm64/ufoo-tui +0 -0
- package/dist/tui/linux-x64/ufoo-tui +0 -0
- package/package.json +3 -3
- package/src/agents/providers/nativeTransport.js +109 -53
- package/src/agents/providers/runtimeConfig.js +41 -1
- package/src/agents/runtime/context/checkpointStore.js +15 -1
- package/src/agents/runtime/context/compaction.js +27 -7
- package/src/agents/runtime/context/runtimeStore.js +1 -0
- package/src/agents/runtime/core/agentLoop.js +48 -6
- package/src/app/cli/busCoreCommands.js +63 -3
- package/src/app/cli/run.js +1 -0
- package/src/code/agent.js +36 -19
- package/src/code/context/planGraphService.js +41 -0
- package/src/code/modelCommand.js +6 -5
- package/src/code/nativeRunner.js +15 -56
- package/src/code/taskDecomposer.js +3 -0
- package/src/code/tools/executor.js +1 -0
- package/src/code/tools/planGraph.js +1 -0
- package/src/code/tools/specs.js +2 -1
- package/src/coordination/bus/index.js +2 -2
- package/src/coordination/bus/message.js +10 -1
- package/src/coordination/bus/nickname.js +3 -1
- package/src/coordination/bus/subscriber.js +25 -10
- package/src/coordination/bus/utils.js +4 -0
- package/src/coordination/bus/wakeEndpoint.js +198 -0
- package/src/coordination/state/paths.js +4 -0
- package/src/runtime/daemon/agentHost.js +2 -0
- package/src/runtime/daemon/deliveryScheduler.js +70 -2
- package/src/runtime/daemon/index.js +1 -0
- package/src/runtime/daemon/mcpStdioProxy.js +130 -10
- package/src/ui/agentSurface.js +34 -3
- package/src/ui/format/markdownRenderer.js +4 -2
- package/src/ui/rustUcodeHost.js +3 -3
|
@@ -318,6 +318,10 @@ function isMetaActive(meta) {
|
|
|
318
318
|
// 1. 显式标记为 inactive
|
|
319
319
|
if (meta.status === "inactive") return false;
|
|
320
320
|
|
|
321
|
+
// A wake registration has no local process. Liveness is the saved adapter,
|
|
322
|
+
// not a pid or a 30s heartbeat.
|
|
323
|
+
if (meta.launch_mode === "wake" && meta.wake_adapter) return true;
|
|
324
|
+
|
|
321
325
|
// 2. PID 存活(最可靠)
|
|
322
326
|
if (meta.pid && isAgentPidAlive(meta.pid)) return true;
|
|
323
327
|
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const fs = require("fs");
|
|
4
|
+
const path = require("path");
|
|
5
|
+
const { getUfooPaths } = require("../state/paths");
|
|
6
|
+
const { withFileLock } = require("../state/fileLock");
|
|
7
|
+
|
|
8
|
+
const WAKE_ADAPTERS = Object.freeze({
|
|
9
|
+
"bearer-json": Object.freeze({
|
|
10
|
+
acceptedStatuses: Object.freeze([200]),
|
|
11
|
+
}),
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
function isWakeMeta(meta) {
|
|
15
|
+
return Boolean(
|
|
16
|
+
meta
|
|
17
|
+
&& meta.status !== "inactive"
|
|
18
|
+
&& meta.launch_mode === "wake"
|
|
19
|
+
&& typeof meta.wake_adapter === "string"
|
|
20
|
+
&& WAKE_ADAPTERS[meta.wake_adapter]
|
|
21
|
+
);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function assertHttpsWakeUrl(rawUrl) {
|
|
25
|
+
let parsed;
|
|
26
|
+
try {
|
|
27
|
+
parsed = new URL(String(rawUrl || "").trim());
|
|
28
|
+
} catch {
|
|
29
|
+
throw new Error("wake URL must be an http(s) URL");
|
|
30
|
+
}
|
|
31
|
+
if (parsed.username || parsed.password) {
|
|
32
|
+
throw new Error("wake URL must not include credentials");
|
|
33
|
+
}
|
|
34
|
+
const loopback = ["localhost", "127.0.0.1", "::1", "[::1]"].includes(parsed.hostname);
|
|
35
|
+
if (parsed.protocol === "https:") return parsed.toString();
|
|
36
|
+
if (parsed.protocol === "http:" && loopback) return parsed.toString();
|
|
37
|
+
throw new Error("wake URL must use https");
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function normalizeAdapter(adapter) {
|
|
41
|
+
const name = String(adapter || "bearer-json").trim();
|
|
42
|
+
if (!WAKE_ADAPTERS[name]) {
|
|
43
|
+
throw new Error(`Unknown wake adapter "${name}"`);
|
|
44
|
+
}
|
|
45
|
+
return name;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function readJsonFile(filePath) {
|
|
49
|
+
try {
|
|
50
|
+
if (!filePath || !fs.existsSync(filePath)) return null;
|
|
51
|
+
const parsed = JSON.parse(fs.readFileSync(filePath, "utf8"));
|
|
52
|
+
return parsed && typeof parsed === "object" ? parsed : null;
|
|
53
|
+
} catch {
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function writeJsonFile(filePath, data, mode) {
|
|
59
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true, mode: 0o700 });
|
|
60
|
+
const tmp = `${filePath}.${process.pid}.tmp`;
|
|
61
|
+
fs.writeFileSync(tmp, `${JSON.stringify(data, null, 2)}\n`, { mode });
|
|
62
|
+
fs.renameSync(tmp, filePath);
|
|
63
|
+
fs.chmodSync(filePath, mode);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function endpointStore(projectRoot) {
|
|
67
|
+
const filePath = getUfooPaths(projectRoot).wakeEndpointsFile;
|
|
68
|
+
const parsed = readJsonFile(filePath) || { version: 1, endpoints: {} };
|
|
69
|
+
if (!parsed.endpoints || typeof parsed.endpoints !== "object") parsed.endpoints = {};
|
|
70
|
+
parsed.version = 1;
|
|
71
|
+
return { filePath, data: parsed };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function receiptStore(projectRoot) {
|
|
75
|
+
const filePath = getUfooPaths(projectRoot).wakeReceiptsFile;
|
|
76
|
+
const parsed = readJsonFile(filePath) || { version: 1, accepted: {} };
|
|
77
|
+
if (!parsed.accepted || typeof parsed.accepted !== "object") parsed.accepted = {};
|
|
78
|
+
parsed.version = 1;
|
|
79
|
+
return { filePath, data: parsed };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function writeWakeEndpoint(projectRoot, subscriber, endpoint = {}) {
|
|
83
|
+
const adapter = normalizeAdapter(endpoint.adapter);
|
|
84
|
+
const url = assertHttpsWakeUrl(endpoint.url);
|
|
85
|
+
const key = String(endpoint.key || "");
|
|
86
|
+
if (!key.trim()) throw new Error("wake key is empty");
|
|
87
|
+
if (key.length > 4096) throw new Error("wake key is too long");
|
|
88
|
+
if (/[\r\n]/.test(key)) throw new Error("wake key must be a single line");
|
|
89
|
+
return withFileLock(getUfooPaths(projectRoot).wakeEndpointsFile, () => {
|
|
90
|
+
const store = endpointStore(projectRoot);
|
|
91
|
+
store.data.endpoints[subscriber] = { adapter, url, key };
|
|
92
|
+
writeJsonFile(store.filePath, store.data, 0o600);
|
|
93
|
+
return { adapter, url };
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function readWakeEndpoint(projectRoot, subscriber) {
|
|
98
|
+
const record = endpointStore(projectRoot).data.endpoints[subscriber];
|
|
99
|
+
if (!record || typeof record !== "object") return null;
|
|
100
|
+
if (!WAKE_ADAPTERS[record.adapter] || typeof record.url !== "string" || typeof record.key !== "string") {
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
return { adapter: record.adapter, url: record.url, key: record.key };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function removeWakeEndpoint(projectRoot, subscriber) {
|
|
107
|
+
return withFileLock(getUfooPaths(projectRoot).wakeEndpointsFile, () => {
|
|
108
|
+
const store = endpointStore(projectRoot);
|
|
109
|
+
if (!store.data.endpoints[subscriber]) return false;
|
|
110
|
+
delete store.data.endpoints[subscriber];
|
|
111
|
+
writeJsonFile(store.filePath, store.data, 0o600);
|
|
112
|
+
withFileLock(getUfooPaths(projectRoot).wakeReceiptsFile, () => {
|
|
113
|
+
const receipts = receiptStore(projectRoot);
|
|
114
|
+
if (receipts.data.accepted[subscriber]) {
|
|
115
|
+
delete receipts.data.accepted[subscriber];
|
|
116
|
+
writeJsonFile(receipts.filePath, receipts.data, 0o600);
|
|
117
|
+
}
|
|
118
|
+
});
|
|
119
|
+
return true;
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function hasWakeAccepted(projectRoot, subscriber, seq) {
|
|
124
|
+
const accepted = receiptStore(projectRoot).data.accepted[subscriber] || {};
|
|
125
|
+
return Boolean(accepted[String(seq)]);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function markWakeAccepted(projectRoot, subscriber, seq) {
|
|
129
|
+
return withFileLock(getUfooPaths(projectRoot).wakeReceiptsFile, () => {
|
|
130
|
+
const store = receiptStore(projectRoot);
|
|
131
|
+
if (!store.data.accepted[subscriber]) store.data.accepted[subscriber] = {};
|
|
132
|
+
store.data.accepted[subscriber][String(seq)] = new Date().toISOString();
|
|
133
|
+
writeJsonFile(store.filePath, store.data, 0o600);
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function readWakeKeyFile(filePath) {
|
|
138
|
+
const resolved = String(filePath || "").trim();
|
|
139
|
+
if (!resolved) throw new Error("wake key file is required");
|
|
140
|
+
let key = "";
|
|
141
|
+
try {
|
|
142
|
+
key = fs.readFileSync(resolved, "utf8");
|
|
143
|
+
} catch (error) {
|
|
144
|
+
throw new Error(`cannot read wake key file: ${error.message}`);
|
|
145
|
+
}
|
|
146
|
+
key = key.replace(/\r?\n$/, "");
|
|
147
|
+
if (!key.trim()) throw new Error("wake key file is empty");
|
|
148
|
+
return key;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async function wakeBearerJson({ url, key, payload, fetchImpl, signal }) {
|
|
152
|
+
const response = await fetchImpl(url, {
|
|
153
|
+
method: "POST",
|
|
154
|
+
headers: {
|
|
155
|
+
"content-type": "application/json",
|
|
156
|
+
authorization: `Bearer ${key}`,
|
|
157
|
+
},
|
|
158
|
+
body: JSON.stringify(payload),
|
|
159
|
+
signal,
|
|
160
|
+
redirect: "error",
|
|
161
|
+
});
|
|
162
|
+
try { Promise.resolve(response.body?.cancel()).catch(() => {}); } catch { /* response body is optional */ }
|
|
163
|
+
return {
|
|
164
|
+
accepted: response.status === 200,
|
|
165
|
+
status: response.status,
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
async function wakeSubscriber(endpoint, payload, fetchImpl = global.fetch, { timeoutMs = 10000 } = {}) {
|
|
170
|
+
if (!endpoint) throw new Error("wake endpoint is missing");
|
|
171
|
+
if (typeof fetchImpl !== "function") throw new Error("wake fetch is unavailable");
|
|
172
|
+
if (endpoint.adapter === "bearer-json") {
|
|
173
|
+
const controller = new AbortController();
|
|
174
|
+
let timer;
|
|
175
|
+
const timeout = new Promise((_, reject) => {
|
|
176
|
+
timer = setTimeout(() => {
|
|
177
|
+
controller.abort();
|
|
178
|
+
reject(Object.assign(new Error("wake request timed out"), { code: "WAKE_TIMEOUT" }));
|
|
179
|
+
}, timeoutMs);
|
|
180
|
+
});
|
|
181
|
+
try { return await Promise.race([wakeBearerJson({ ...endpoint, payload, fetchImpl, signal: controller.signal }), timeout]); }
|
|
182
|
+
finally { clearTimeout(timer); }
|
|
183
|
+
}
|
|
184
|
+
throw new Error(`Unknown wake adapter "${endpoint.adapter}"`);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
module.exports = {
|
|
188
|
+
WAKE_ADAPTERS,
|
|
189
|
+
isWakeMeta,
|
|
190
|
+
assertHttpsWakeUrl,
|
|
191
|
+
writeWakeEndpoint,
|
|
192
|
+
readWakeEndpoint,
|
|
193
|
+
removeWakeEndpoint,
|
|
194
|
+
hasWakeAccepted,
|
|
195
|
+
markWakeAccepted,
|
|
196
|
+
readWakeKeyFile,
|
|
197
|
+
wakeSubscriber,
|
|
198
|
+
};
|
|
@@ -6,6 +6,8 @@ function getUfooPaths(projectRoot) {
|
|
|
6
6
|
const agentDir = path.join(ufooDir, "agent");
|
|
7
7
|
const memoryDir = path.join(ufooDir, "memory");
|
|
8
8
|
const agentsFile = path.join(agentDir, "all-agents.json");
|
|
9
|
+
const wakeEndpointsFile = path.join(agentDir, "wake-endpoints.json");
|
|
10
|
+
const wakeReceiptsFile = path.join(busDir, "wake-receipts.json");
|
|
9
11
|
const memoryFile = path.join(memoryDir, "memory.jsonl");
|
|
10
12
|
|
|
11
13
|
const busQueuesDir = path.join(busDir, "queues");
|
|
@@ -33,6 +35,8 @@ function getUfooPaths(projectRoot) {
|
|
|
33
35
|
agentDir,
|
|
34
36
|
memoryDir,
|
|
35
37
|
agentsFile,
|
|
38
|
+
wakeEndpointsFile,
|
|
39
|
+
wakeReceiptsFile,
|
|
36
40
|
memoryFile,
|
|
37
41
|
busQueuesDir,
|
|
38
42
|
busEventsDir,
|
|
@@ -192,6 +192,8 @@ function createAgentHost({ projectRoot, provider, model, ports = {}, onEvent = (
|
|
|
192
192
|
const contextManager = createContextManager({ policy: contextPolicy, store: {
|
|
193
193
|
sourceRef: store.journal,
|
|
194
194
|
load: () => store.read().contextCheckpoint || null,
|
|
195
|
+
loadRetryState: () => store.read().contextCompactionRetry || null,
|
|
196
|
+
saveRetryState: retryState => store.append({ type: "context.compaction.retry_state", retryState }),
|
|
195
197
|
commit(checkpoint, sourceBatch, expectedVersion) {
|
|
196
198
|
let committed = false;
|
|
197
199
|
store.transaction(state => {
|
|
@@ -6,6 +6,13 @@ const { buildPromptInjectionText } = require("../../coordination/bus/promptEnvel
|
|
|
6
6
|
const { createTerminalAdapterRouter } = require("../terminal/adapterRouter");
|
|
7
7
|
const { normalizeQueueEnvelope } = require("../../coordination/bus/deliveryQueue");
|
|
8
8
|
const { writeActivityState } = require("../../agents/activity/activityStateWriter");
|
|
9
|
+
const {
|
|
10
|
+
hasWakeAccepted,
|
|
11
|
+
isWakeMeta,
|
|
12
|
+
markWakeAccepted,
|
|
13
|
+
readWakeEndpoint,
|
|
14
|
+
wakeSubscriber,
|
|
15
|
+
} = require("../../coordination/bus/wakeEndpoint");
|
|
9
16
|
|
|
10
17
|
function asState(value = "") {
|
|
11
18
|
return String(value || "").trim().toLowerCase();
|
|
@@ -74,6 +81,8 @@ class DeliveryScheduler {
|
|
|
74
81
|
});
|
|
75
82
|
};
|
|
76
83
|
this.log = typeof options.log === "function" ? options.log : () => {};
|
|
84
|
+
this.wakeFetch = typeof options.wakeFetch === "function" ? options.wakeFetch : global.fetch;
|
|
85
|
+
this.wakeTimeoutMs = positiveMs(options.wakeTimeoutMs, 10000);
|
|
77
86
|
this.now = typeof options.now === "function" ? options.now : () => Date.now();
|
|
78
87
|
this.deferWarnAfterMs = positiveMs(options.deferWarnAfterMs, DEFAULT_DEFER_WARN_AFTER_MS);
|
|
79
88
|
this.warnIntervalMs = positiveMs(options.warnIntervalMs, DEFAULT_WARN_INTERVAL_MS);
|
|
@@ -188,6 +197,9 @@ class DeliveryScheduler {
|
|
|
188
197
|
if (!meta || meta.status === "inactive") {
|
|
189
198
|
return { ok: false, reason: "missing_or_inactive" };
|
|
190
199
|
}
|
|
200
|
+
if (isWakeMeta(meta)) {
|
|
201
|
+
return { ok: true, reason: "wake" };
|
|
202
|
+
}
|
|
191
203
|
if (meta.mcp_bridge === true) {
|
|
192
204
|
return { ok: false, reason: "external_receive" };
|
|
193
205
|
}
|
|
@@ -350,6 +362,49 @@ class DeliveryScheduler {
|
|
|
350
362
|
};
|
|
351
363
|
}
|
|
352
364
|
|
|
365
|
+
async deliverWake(subscriber) {
|
|
366
|
+
const queue = this.queueFactory(subscriber);
|
|
367
|
+
const pending = this.readPendingEvents(queue).filter((event) => (
|
|
368
|
+
event
|
|
369
|
+
&& event.event === "message"
|
|
370
|
+
&& event.data
|
|
371
|
+
&& typeof event.data.message === "string"
|
|
372
|
+
));
|
|
373
|
+
const next = pending[0];
|
|
374
|
+
if (!next || hasWakeAccepted(this.projectRoot, subscriber, next.seq)) {
|
|
375
|
+
return { ok: true, delivered: 0, reason: "wake_waiting_ack" };
|
|
376
|
+
}
|
|
377
|
+
const endpoint = readWakeEndpoint(this.projectRoot, subscriber);
|
|
378
|
+
if (!endpoint) {
|
|
379
|
+
return { ok: false, delivered: 0, reason: "wake_endpoint_missing" };
|
|
380
|
+
}
|
|
381
|
+
const claim = queue.claimNext((event) => Number(event && event.seq) === Number(next.seq));
|
|
382
|
+
if (!claim) return { ok: true, delivered: 0, reason: "empty" };
|
|
383
|
+
try {
|
|
384
|
+
const result = await wakeSubscriber(endpoint, {
|
|
385
|
+
source: "ufoo",
|
|
386
|
+
project_root: this.projectRoot,
|
|
387
|
+
subscriber,
|
|
388
|
+
seq: Number(next.seq) || 0,
|
|
389
|
+
publisher: next.publisher || "",
|
|
390
|
+
message: next.data.message,
|
|
391
|
+
}, this.wakeFetch, { timeoutMs: this.wakeTimeoutMs });
|
|
392
|
+
if (!result.accepted) {
|
|
393
|
+
queue.restoreClaim(claim);
|
|
394
|
+
this.log(`wake not accepted subscriber=${subscriber} seq=${next.seq} status=${result.status}`);
|
|
395
|
+
return { ok: false, delivered: 0, reason: "wake_not_accepted", status: result.status };
|
|
396
|
+
}
|
|
397
|
+
markWakeAccepted(this.projectRoot, subscriber, next.seq);
|
|
398
|
+
queue.restoreClaim(claim);
|
|
399
|
+
return { ok: true, delivered: 0, woken: true, seq: Number(next.seq) || 0 };
|
|
400
|
+
} catch (err) {
|
|
401
|
+
queue.restoreClaim(claim);
|
|
402
|
+
const message = err && err.message ? err.message : String(err || "wake failed");
|
|
403
|
+
this.log(`wake failed subscriber=${subscriber} seq=${next.seq}`);
|
|
404
|
+
return { ok: false, delivered: 0, reason: "wake_failed", error: message };
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
|
|
353
408
|
async deliverSubscriber(subscriber) {
|
|
354
409
|
if (!subscriber) return { ok: false, delivered: 0, reason: "missing_subscriber" };
|
|
355
410
|
if (this.locks.has(subscriber)) {
|
|
@@ -361,6 +416,9 @@ class DeliveryScheduler {
|
|
|
361
416
|
try {
|
|
362
417
|
const queue = this.queueFactory(subscriber);
|
|
363
418
|
const transportGate = this.shouldDeliver(subscriber, { requireIdle: false });
|
|
419
|
+
if (transportGate.reason === "wake") {
|
|
420
|
+
return await this.deliverWake(subscriber);
|
|
421
|
+
}
|
|
364
422
|
if (!transportGate.ok) {
|
|
365
423
|
this.noteDeferral(subscriber, transportGate.reason);
|
|
366
424
|
return { ok: true, delivered: 0, deferred: true, reason: transportGate.reason };
|
|
@@ -510,7 +568,13 @@ class DeliveryScheduler {
|
|
|
510
568
|
continue;
|
|
511
569
|
}
|
|
512
570
|
const queue = this.queueFactory(subscriber);
|
|
513
|
-
|
|
571
|
+
let pending = [];
|
|
572
|
+
try {
|
|
573
|
+
pending = queue.readPending();
|
|
574
|
+
} catch {
|
|
575
|
+
continue;
|
|
576
|
+
}
|
|
577
|
+
if (pending.length > 0) {
|
|
514
578
|
subscribers.push(subscriber);
|
|
515
579
|
pendingSubscribers.add(subscriber);
|
|
516
580
|
} else {
|
|
@@ -533,7 +597,11 @@ class DeliveryScheduler {
|
|
|
533
597
|
this.running = true;
|
|
534
598
|
const run = () => {
|
|
535
599
|
this.tick().catch((err) => {
|
|
536
|
-
|
|
600
|
+
try {
|
|
601
|
+
this.log(`delivery scheduler tick failed: ${err && err.message ? err.message : String(err)}`);
|
|
602
|
+
} catch {
|
|
603
|
+
// A full project volume must not take down the controller.
|
|
604
|
+
}
|
|
537
605
|
});
|
|
538
606
|
};
|
|
539
607
|
run();
|
|
@@ -950,6 +950,7 @@ function startDaemon({
|
|
|
950
950
|
if (manageProcessState) writePid(projectRoot);
|
|
951
951
|
|
|
952
952
|
const logFile = fs.createWriteStream(logPath(projectRoot), { flags: "a" });
|
|
953
|
+
logFile.on("error", () => {});
|
|
953
954
|
const formatLogLine = (msg) => `[daemon] ${new Date().toISOString()} ${msg}\n`;
|
|
954
955
|
const log = (msg) => {
|
|
955
956
|
logFile.write(formatLogLine(msg));
|
|
@@ -22,11 +22,81 @@ const REPLAYABLE_TOOLS = new Set([
|
|
|
22
22
|
"list_agents", "ufoo_mcp_status", "poll_inbox", "wait_for_message",
|
|
23
23
|
]);
|
|
24
24
|
const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "::1", "[::1]"]);
|
|
25
|
+
const CONTENT_LENGTH_HEADER = "content-length:";
|
|
26
|
+
const MAX_STDIO_HEADER_BYTES = 64 * 1024;
|
|
27
|
+
const MAX_STDIO_BODY_BYTES = 2 * 1024 * 1024;
|
|
25
28
|
|
|
26
29
|
function sleep(ms) {
|
|
27
30
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
28
31
|
}
|
|
29
32
|
|
|
33
|
+
function skipAsciiSpace(buffer) {
|
|
34
|
+
let index = 0;
|
|
35
|
+
while (index < buffer.length && (buffer[index] === 0x20 || buffer[index] === 0x09)) index += 1;
|
|
36
|
+
return index;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function classifyStdioChunk(buffer) {
|
|
40
|
+
const offset = skipAsciiSpace(buffer);
|
|
41
|
+
const sample = buffer.slice(offset, offset + CONTENT_LENGTH_HEADER.length).toString("latin1").toLowerCase();
|
|
42
|
+
if (!sample) return "empty";
|
|
43
|
+
if (sample.startsWith("{")) return "json";
|
|
44
|
+
if (sample.startsWith(CONTENT_LENGTH_HEADER)) return "header";
|
|
45
|
+
if (CONTENT_LENGTH_HEADER.startsWith(sample) && !sample.includes("\n")) return "prefix";
|
|
46
|
+
return "line";
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function takeContentLengthFrame(buffer) {
|
|
50
|
+
let index = 0;
|
|
51
|
+
while (
|
|
52
|
+
index < buffer.length
|
|
53
|
+
&& (buffer[index] === 0x20 || buffer[index] === 0x09 || buffer[index] === 0x0d || buffer[index] === 0x0a)
|
|
54
|
+
) index += 1;
|
|
55
|
+
if (index === buffer.length) return { status: "empty" };
|
|
56
|
+
const slice = buffer.slice(index);
|
|
57
|
+
const crlf = slice.indexOf("\r\n\r\n");
|
|
58
|
+
const lf = slice.indexOf("\n\n");
|
|
59
|
+
let headerEnd = -1;
|
|
60
|
+
let separatorLength = 0;
|
|
61
|
+
if (crlf >= 0 && (lf < 0 || crlf <= lf)) {
|
|
62
|
+
headerEnd = crlf;
|
|
63
|
+
separatorLength = 4;
|
|
64
|
+
} else if (lf >= 0) {
|
|
65
|
+
headerEnd = lf;
|
|
66
|
+
separatorLength = 2;
|
|
67
|
+
}
|
|
68
|
+
if (headerEnd < 0) {
|
|
69
|
+
if (slice.length > MAX_STDIO_HEADER_BYTES) {
|
|
70
|
+
return { status: "invalid", rest: Buffer.alloc(0), message: "MCP header is too large" };
|
|
71
|
+
}
|
|
72
|
+
return { status: "need-more" };
|
|
73
|
+
}
|
|
74
|
+
const header = slice.slice(0, headerEnd).toString("utf8");
|
|
75
|
+
const match = header.match(/content-length:\s*(\d+)/i);
|
|
76
|
+
if (!match) {
|
|
77
|
+
return {
|
|
78
|
+
status: "invalid",
|
|
79
|
+
rest: slice.slice(headerEnd + separatorLength),
|
|
80
|
+
message: "MCP frame is missing Content-Length",
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
const length = Number(match[1]);
|
|
84
|
+
if (!Number.isSafeInteger(length) || length < 0 || length > MAX_STDIO_BODY_BYTES) {
|
|
85
|
+
return {
|
|
86
|
+
status: "invalid",
|
|
87
|
+
rest: slice.slice(headerEnd + separatorLength),
|
|
88
|
+
message: "MCP Content-Length is invalid",
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
const bodyStart = headerEnd + separatorLength;
|
|
92
|
+
if (slice.length < bodyStart + length) return { status: "need-more" };
|
|
93
|
+
return {
|
|
94
|
+
status: "ok",
|
|
95
|
+
body: slice.slice(bodyStart, bodyStart + length).toString("utf8"),
|
|
96
|
+
rest: slice.slice(bodyStart + length),
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
30
100
|
function validateEndpoint(raw = "") {
|
|
31
101
|
let parsed;
|
|
32
102
|
try {
|
|
@@ -85,12 +155,21 @@ class McpStdioProxy {
|
|
|
85
155
|
this.initializing = null;
|
|
86
156
|
this.activeRequests = new Map();
|
|
87
157
|
this.closed = false;
|
|
88
|
-
this.buffer =
|
|
158
|
+
this.buffer = Buffer.alloc(0);
|
|
159
|
+
this.inputFraming = "";
|
|
160
|
+
this.outputFraming = "ndjson";
|
|
89
161
|
}
|
|
90
162
|
|
|
91
163
|
writeMessage(message) {
|
|
92
164
|
if (!message || this.closed) return;
|
|
93
|
-
|
|
165
|
+
const json = JSON.stringify(message);
|
|
166
|
+
if (this.outputFraming === "content-length") {
|
|
167
|
+
const body = Buffer.from(json, "utf8");
|
|
168
|
+
this.output.write(`Content-Length: ${body.length}\r\n\r\n`);
|
|
169
|
+
this.output.write(body);
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
this.output.write(`${json}\n`);
|
|
94
173
|
}
|
|
95
174
|
|
|
96
175
|
writeError(message) {
|
|
@@ -288,11 +367,10 @@ class McpStdioProxy {
|
|
|
288
367
|
}
|
|
289
368
|
}
|
|
290
369
|
|
|
291
|
-
|
|
292
|
-
if (!line.trim()) return;
|
|
370
|
+
handleJsonText(text) {
|
|
293
371
|
let request;
|
|
294
372
|
try {
|
|
295
|
-
request = JSON.parse(
|
|
373
|
+
request = JSON.parse(text);
|
|
296
374
|
} catch (err) {
|
|
297
375
|
this.writeMessage(createJsonRpcError(
|
|
298
376
|
null,
|
|
@@ -304,13 +382,55 @@ class McpStdioProxy {
|
|
|
304
382
|
void this.forward(request);
|
|
305
383
|
}
|
|
306
384
|
|
|
385
|
+
handleLine(line) {
|
|
386
|
+
if (!line.trim()) return;
|
|
387
|
+
this.handleJsonText(line);
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
drainInput() {
|
|
391
|
+
while (this.buffer.length > 0) {
|
|
392
|
+
if (this.inputFraming === "content-length") {
|
|
393
|
+
const frame = takeContentLengthFrame(this.buffer);
|
|
394
|
+
if (frame.status === "need-more") return;
|
|
395
|
+
if (frame.status === "empty") {
|
|
396
|
+
this.buffer = Buffer.alloc(0);
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
399
|
+
this.buffer = frame.rest;
|
|
400
|
+
this.outputFraming = "content-length";
|
|
401
|
+
if (frame.status === "invalid") {
|
|
402
|
+
this.writeMessage(createJsonRpcError(
|
|
403
|
+
null,
|
|
404
|
+
MCP_ERROR_CODES.PARSE_ERROR,
|
|
405
|
+
frame.message || "Parse error"
|
|
406
|
+
));
|
|
407
|
+
continue;
|
|
408
|
+
}
|
|
409
|
+
this.handleJsonText(frame.body);
|
|
410
|
+
continue;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
const kind = classifyStdioChunk(this.buffer);
|
|
414
|
+
if (kind === "empty" || kind === "prefix") return;
|
|
415
|
+
if (kind === "header") {
|
|
416
|
+
this.inputFraming = "content-length";
|
|
417
|
+
this.outputFraming = "content-length";
|
|
418
|
+
continue;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
const newline = this.buffer.indexOf(0x0a);
|
|
422
|
+
if (newline < 0) return;
|
|
423
|
+
const line = this.buffer.slice(0, newline).toString("utf8").replace(/\r$/, "");
|
|
424
|
+
this.buffer = this.buffer.slice(newline + 1);
|
|
425
|
+
this.handleLine(line);
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
307
429
|
start() {
|
|
308
|
-
this.input.setEncoding("utf8");
|
|
309
430
|
this.input.on("data", (chunk) => {
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
this.
|
|
313
|
-
for (const line of lines) this.handleLine(line);
|
|
431
|
+
const next = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));
|
|
432
|
+
this.buffer = this.buffer.length ? Buffer.concat([this.buffer, next]) : next;
|
|
433
|
+
this.drainInput();
|
|
314
434
|
});
|
|
315
435
|
this.input.on("end", () => {
|
|
316
436
|
void this.close();
|
package/src/ui/agentSurface.js
CHANGED
|
@@ -26,6 +26,22 @@ function createAgentSurface(options = {}) {
|
|
|
26
26
|
const background = new Map();
|
|
27
27
|
let contextUsage = "";
|
|
28
28
|
const tools = new Map();
|
|
29
|
+
const renderedEntries = new WeakMap();
|
|
30
|
+
|
|
31
|
+
function presentEntry(row) {
|
|
32
|
+
if (!["assistant", "thinking"].includes(row.kind) || /\x1b\[/.test(row.text)) return { ...row };
|
|
33
|
+
let cached = renderedEntries.get(row);
|
|
34
|
+
if (!cached || cached.source !== row.text) {
|
|
35
|
+
cached = { source: row.text, text: fmt.renderLogLinesWithMarkdownAnsi(row.text, { inCodeBlock: false }).join("\n") };
|
|
36
|
+
renderedEntries.set(row, cached);
|
|
37
|
+
}
|
|
38
|
+
return { ...row, text: cached.text };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function getEntry(id) {
|
|
42
|
+
const row = entries.find((row) => row.id === id);
|
|
43
|
+
return row ? presentEntry(row) : null;
|
|
44
|
+
}
|
|
29
45
|
|
|
30
46
|
function bound() {
|
|
31
47
|
for (const entry of entries) {
|
|
@@ -261,10 +277,25 @@ function createAgentSurface(options = {}) {
|
|
|
261
277
|
const failed = bg.filter((task) => ["failed", "stopped", "killed"].includes(task.status)).length;
|
|
262
278
|
const suffix = [running && `${running} running`, done && `${done} done`, failed && `${failed} failed`].filter(Boolean).join("/");
|
|
263
279
|
const label = `${status}${!busy && status === "ready" && idlePlanHint ? ` · ${idlePlanHint}` : ""}${submitted.length > 1 || (submitted.length && runningTask) ? ` · queued ${submitted.length}` : ""}${suffix ? ` · BG ${suffix}` : ""}`;
|
|
264
|
-
return { entries: entries.map(
|
|
280
|
+
return { entries: entries.map(presentEntry), status: label, busy, usage, plan: plan.slice(), revision, started_at: startedAt };
|
|
265
281
|
}
|
|
266
282
|
|
|
267
|
-
return { apply, accept, snapshot, toggleExpanded };
|
|
283
|
+
return { apply, accept, snapshot, getEntry, toggleExpanded };
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// Keep source deltas in the surface; send the rendered entry as a replacement
|
|
287
|
+
// so delimiters split across chunks and multi-line tables can be re-evaluated.
|
|
288
|
+
function projectSurfaceEvent(surface, name, payload = {}) {
|
|
289
|
+
const delta = name === "stream.delta" || name === "thinking.delta";
|
|
290
|
+
const id = payload.id || (name === "thinking.delta" ? "thinking" : "stream");
|
|
291
|
+
const exists = delta && Boolean(surface.getEntry(id));
|
|
292
|
+
surface.apply(name, payload);
|
|
293
|
+
if (delta) {
|
|
294
|
+
const row = surface.getEntry(id);
|
|
295
|
+
return { name: exists ? "transcript.patch" : "transcript.append", payload: row };
|
|
296
|
+
}
|
|
297
|
+
if (name === "transcript.reset") return { name, payload: { ...payload, entries: surface.snapshot().entries } };
|
|
298
|
+
return { name, payload };
|
|
268
299
|
}
|
|
269
300
|
|
|
270
|
-
module.exports = { createAgentSurface };
|
|
301
|
+
module.exports = { createAgentSurface, projectSurfaceEvent };
|
|
@@ -222,8 +222,10 @@ function renderInlineMarkdown(input = "", adapters = createBlessedAdapters()) {
|
|
|
222
222
|
let out = "";
|
|
223
223
|
let i = 0;
|
|
224
224
|
while (i < source.length) {
|
|
225
|
+
// Underscores inside identifiers/filenames are literal, as in GFM.
|
|
226
|
+
const canOpenUnderscore = i === 0 || !/[\p{L}\p{N}_]/u.test(source[i - 1]);
|
|
225
227
|
// **bold** / __bold__
|
|
226
|
-
if (source.startsWith("**", i) || source.startsWith("__", i)) {
|
|
228
|
+
if (source.startsWith("**", i) || source.startsWith("__", i) && canOpenUnderscore) {
|
|
227
229
|
const mark = source.slice(i, i + 2);
|
|
228
230
|
const close = source.indexOf(mark, i + 2);
|
|
229
231
|
if (close !== -1) {
|
|
@@ -253,7 +255,7 @@ function renderInlineMarkdown(input = "", adapters = createBlessedAdapters()) {
|
|
|
253
255
|
// *italic* / _italic_ (single delimiter; avoid ** / __)
|
|
254
256
|
if (
|
|
255
257
|
(source[i] === "*" && source[i + 1] !== "*")
|
|
256
|
-
|| (source[i] === "_" && source[i + 1] !== "_")
|
|
258
|
+
|| (source[i] === "_" && source[i + 1] !== "_" && canOpenUnderscore)
|
|
257
259
|
) {
|
|
258
260
|
const mark = source[i];
|
|
259
261
|
const close = source.indexOf(mark, i + 1);
|
package/src/ui/rustUcodeHost.js
CHANGED
|
@@ -17,7 +17,7 @@ const {
|
|
|
17
17
|
} = require("../code/UcodeController");
|
|
18
18
|
const { createEnvelope, encodeMessage } = require("../runtime/contracts/uiProtocol");
|
|
19
19
|
const fmt = require("./format");
|
|
20
|
-
const { createAgentSurface } = require("./agentSurface");
|
|
20
|
+
const { createAgentSurface, projectSurfaceEvent } = require("./agentSurface");
|
|
21
21
|
const { buildPlanSetPayload, statusForAgentPhase } = require("./agentPresentation");
|
|
22
22
|
const PACKAGE_VERSION = require("../../package.json").version;
|
|
23
23
|
|
|
@@ -219,9 +219,9 @@ async function runUcodeRust(props = {}) {
|
|
|
219
219
|
});
|
|
220
220
|
|
|
221
221
|
function publish(name, payload) {
|
|
222
|
-
surface
|
|
222
|
+
const projected = projectSurfaceEvent(surface, name, payload);
|
|
223
223
|
if (!hostRef) return;
|
|
224
|
-
hostRef.broadcast(hostRef.createEvent(name, payload, {
|
|
224
|
+
hostRef.broadcast(hostRef.createEvent(projected.name, projected.payload, {
|
|
225
225
|
surface: "ucode",
|
|
226
226
|
project_id: workspaceRoot,
|
|
227
227
|
}));
|