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
package/README.md
CHANGED
|
@@ -132,16 +132,19 @@ loopback endpoint. Existing ufoo authentication fields and headers are retained.
|
|
|
132
132
|
Use `ufoo mcp configure codex --dry-run` to preview the change with credentials
|
|
133
133
|
redacted. Restart the Codex surface after configuring it.
|
|
134
134
|
|
|
135
|
-
For
|
|
136
|
-
stdio configuration:
|
|
135
|
+
For Cursor and any other host that has not been verified with direct HTTP,
|
|
136
|
+
keep the compatible stdio configuration:
|
|
137
137
|
|
|
138
138
|
```bash
|
|
139
139
|
ufoo mcp
|
|
140
140
|
```
|
|
141
141
|
|
|
142
142
|
This command is a stateless transport proxy into the same global server. It
|
|
143
|
-
|
|
144
|
-
|
|
143
|
+
accepts both newline-delimited JSON and standard `Content-Length` frames, and
|
|
144
|
+
answers in the framing that client used. Cursor can keep `command: ufoo` and
|
|
145
|
+
`args: ["mcp"]`. The proxy does not own Agent registrations or project state.
|
|
146
|
+
Inspect or restart the singleton listener with `ufoo mcp status` and
|
|
147
|
+
`ufoo mcp restart`.
|
|
145
148
|
|
|
146
149
|
## Runtime Model
|
|
147
150
|
|
|
@@ -403,6 +406,21 @@ second command catalog. Initialization and unified status are handled by
|
|
|
403
406
|
|
|
404
407
|
### Event Bus
|
|
405
408
|
|
|
409
|
+
External HTTP agents can register a wake endpoint, including `grok-bot`:
|
|
410
|
+
|
|
411
|
+
```bash
|
|
412
|
+
ufoo bus join my-session grok-bot --wake-url https://agent.example/wake --wake-key-file /path/to/wake-key
|
|
413
|
+
```
|
|
414
|
+
|
|
415
|
+
The `bearer-json` adapter sends a bearer-authenticated JSON request containing
|
|
416
|
+
`project_root`, `subscriber`, `seq`, `publisher`, and `message`. The endpoint
|
|
417
|
+
must return HTTP 200 after accepting the work. The receiver acknowledges its
|
|
418
|
+
queue with `ufoo bus ack <subscriber> --through <seq>` after handling it; later
|
|
419
|
+
messages wait for that acknowledgement. Failed requests remain queued for retry.
|
|
420
|
+
Requests have a ten-second deadline and do not follow redirects. HTTPS is
|
|
421
|
+
required except for loopback HTTP. Endpoint keys stay in a mode-600 local file.
|
|
422
|
+
Wake registrations have no local PID or terminal ownership.
|
|
423
|
+
|
|
406
424
|
```text
|
|
407
425
|
/bus list
|
|
408
426
|
/bus status
|
package/README.zh-CN.md
CHANGED
|
@@ -138,10 +138,11 @@ ufoo -g
|
|
|
138
138
|
ufoo mcp configure codex
|
|
139
139
|
```
|
|
140
140
|
|
|
141
|
-
重启 Codex surface
|
|
142
|
-
`ufoo mcp
|
|
143
|
-
|
|
144
|
-
`ufoo mcp
|
|
141
|
+
重启 Codex surface 后即可使用。Cursor 以及其他尚未验证直接 HTTP 的 host
|
|
142
|
+
继续配置 `ufoo mcp`。这个无状态 stdio 代理连接同一个 global server,同时接受
|
|
143
|
+
换行 JSON 和标准 `Content-Length` 帧,并按客户端使用的帧格式回写。Cursor 保持
|
|
144
|
+
`command: ufoo`、`args: ["mcp"]` 即可。它不拥有 Agent 注册或项目状态。用
|
|
145
|
+
`ufoo mcp status` 检查唯一 listener,用 `ufoo mcp restart` 只重启 listener。
|
|
145
146
|
|
|
146
147
|
## 运行模型
|
|
147
148
|
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "u-foo",
|
|
3
|
-
"version": "4.0.
|
|
3
|
+
"version": "4.0.5",
|
|
4
4
|
"description": "Multi-Agent Workspace Protocol. Just add u. claude → uclaude, codex → ucodex.",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE",
|
|
6
6
|
"homepage": "https://ufoo.dev",
|
|
@@ -59,14 +59,14 @@
|
|
|
59
59
|
"dependencies": {
|
|
60
60
|
"@anthropic-ai/claude-agent-sdk": "^0.3.295",
|
|
61
61
|
"@anthropic-ai/sdk": "^0.132.1",
|
|
62
|
-
"@modelcontextprotocol/sdk": "^1.32.
|
|
62
|
+
"@modelcontextprotocol/sdk": "^1.32.2",
|
|
63
63
|
"@openai/codex-sdk": "^0.162.0",
|
|
64
64
|
"chalk": "^4.1.2",
|
|
65
65
|
"commander": "^13.1.0",
|
|
66
66
|
"gray-matter": "^4.0.3",
|
|
67
67
|
"node-pty": "^1.1.0",
|
|
68
68
|
"proper-lockfile": "^4.1.2",
|
|
69
|
-
"undici": "^6.
|
|
69
|
+
"undici": "^6.29.1",
|
|
70
70
|
"ws": "^8.19.0"
|
|
71
71
|
},
|
|
72
72
|
"devDependencies": {
|
|
@@ -11,6 +11,12 @@ const { buildResponsesPayload, isResponsesKeepalive, responseEventDelta, parseRe
|
|
|
11
11
|
|
|
12
12
|
const DEFAULT_NATIVE_TIMEOUT_MS = 43200000;
|
|
13
13
|
const DEFAULT_NATIVE_CONNECT_TIMEOUT_MS = 10 * 60 * 1000;
|
|
14
|
+
const NATIVE_MAX_RETRIES = 3;
|
|
15
|
+
const RETRYABLE_STATUS = new Set([408, 429, 500, 502, 503, 504, 529]);
|
|
16
|
+
const RETRYABLE_CODES = new Set([
|
|
17
|
+
"ECONNRESET", "ECONNREFUSED", "EPIPE", "ETIMEDOUT", "EAI_AGAIN", "ENETUNREACH", "EHOSTUNREACH",
|
|
18
|
+
"UND_ERR_CONNECT_TIMEOUT", "UND_ERR_SOCKET", "UND_ERR_HEADERS_TIMEOUT", "UND_ERR_BODY_TIMEOUT",
|
|
19
|
+
]);
|
|
14
20
|
const DEFAULT_OPENAI_MAX_TOKENS = 32768;
|
|
15
21
|
const DEFAULT_ANTHROPIC_MAX_TOKENS = 32768;
|
|
16
22
|
// Undici otherwise imposes its own 10-second connection deadline, regardless
|
|
@@ -275,6 +281,33 @@ function emitPhase(callback, event = {}) {
|
|
|
275
281
|
}
|
|
276
282
|
}
|
|
277
283
|
|
|
284
|
+
function isRetryableRequestError(error) {
|
|
285
|
+
if (RETRYABLE_STATUS.has(error?.status)) return true;
|
|
286
|
+
for (let current = error, depth = 0; current && depth < 5; current = current.cause, depth += 1) {
|
|
287
|
+
if (RETRYABLE_CODES.has(current.code)) return true;
|
|
288
|
+
}
|
|
289
|
+
return error instanceof TypeError && error.message === "fetch failed" && !error.cause?.code;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function retryDelayMs(response, attempt) {
|
|
293
|
+
const value = response?.headers?.get?.("retry-after");
|
|
294
|
+
let requested = Number.NaN;
|
|
295
|
+
if (value != null && String(value).trim()) {
|
|
296
|
+
requested = /^\d+(?:\.\d+)?$/.test(value) ? Number(value) * 1000 : Date.parse(value) - Date.now();
|
|
297
|
+
}
|
|
298
|
+
return Math.min(30000, Math.max(1000 * 2 ** (attempt - 1), Number.isFinite(requested) ? requested : 0));
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
function waitForRetry(delayMs, signal) {
|
|
302
|
+
return new Promise((resolve, reject) => {
|
|
303
|
+
const cleanup = () => signal.removeEventListener("abort", abort);
|
|
304
|
+
const abort = () => { clearTimeout(timer); cleanup(); reject(new Error("provider retry cancelled")); };
|
|
305
|
+
const timer = setTimeout(() => { cleanup(); resolve(); }, delayMs);
|
|
306
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
307
|
+
if (signal.aborted) abort();
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
|
|
278
311
|
// Shared SSE transport skeleton: POST the payload, then read the stream as
|
|
279
312
|
// SSE blocks, dispatch each non-[DONE] block to onEvent, and stop after the
|
|
280
313
|
// batch that carried [DONE]. Timeout/cancel translation and request cleanup
|
|
@@ -292,67 +325,90 @@ async function runSseRequest({
|
|
|
292
325
|
buildResult,
|
|
293
326
|
} = {}) {
|
|
294
327
|
const request = createRequestController({ signal, timeoutMs });
|
|
295
|
-
|
|
296
|
-
emitPhase(onPhase, { type: "request_start" });
|
|
297
|
-
|
|
298
328
|
try {
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
329
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
330
|
+
let response;
|
|
331
|
+
let reader;
|
|
332
|
+
// Protocol handlers retain their own accumulators. Once any event has
|
|
333
|
+
// reached one, replay would duplicate text/tool arguments; stop retrying.
|
|
334
|
+
let consumed = false;
|
|
335
|
+
emitPhase(onPhase, { type: "request_start" });
|
|
336
|
+
try {
|
|
337
|
+
response = await fetch(url, {
|
|
338
|
+
method: "POST",
|
|
339
|
+
headers,
|
|
340
|
+
body: JSON.stringify(payload),
|
|
341
|
+
signal: request.signal,
|
|
342
|
+
dispatcher: getNativeSseDispatcher(),
|
|
343
|
+
});
|
|
311
344
|
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
const data = await response.json();
|
|
317
|
-
return onNonStream(data);
|
|
318
|
-
}
|
|
345
|
+
if (!response.ok) {
|
|
346
|
+
const body = await response.text().catch(() => "");
|
|
347
|
+
throw Object.assign(new Error(`provider request failed (${response.status}): ${clipText(body, 500)}`), { status: response.status });
|
|
348
|
+
}
|
|
319
349
|
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
if (done) break;
|
|
328
|
-
|
|
329
|
-
rawBuffer += decoder.decode(value, { stream: true });
|
|
330
|
-
const parsed = parseSseBlocks(rawBuffer);
|
|
331
|
-
rawBuffer = parsed.rest;
|
|
332
|
-
|
|
333
|
-
for (const block of parsed.blocks) {
|
|
334
|
-
const { event, data } = parseSseEventBlock(block);
|
|
335
|
-
if (!data) continue;
|
|
336
|
-
if (data === "[DONE]") {
|
|
337
|
-
// Stop reading after this batch instead of waiting for the server
|
|
338
|
-
// to close the connection, but keep the buffered tail and finish
|
|
339
|
-
// the blocks already parsed alongside [DONE] instead of silently
|
|
340
|
-
// dropping them.
|
|
341
|
-
sawDone = true;
|
|
342
|
-
continue;
|
|
350
|
+
const contentType = String(response.headers && typeof response.headers.get === "function"
|
|
351
|
+
? response.headers.get("content-type") || "" : "");
|
|
352
|
+
if (/application\/(?:[a-z0-9.+-]*\+)?json\b/i.test(contentType)
|
|
353
|
+
|| !response.body || typeof response.body.getReader !== "function") {
|
|
354
|
+
const data = await response.json();
|
|
355
|
+
consumed = true;
|
|
356
|
+
return onNonStream(data);
|
|
343
357
|
}
|
|
344
358
|
|
|
345
|
-
|
|
346
|
-
|
|
359
|
+
reader = response.body.getReader();
|
|
360
|
+
const decoder = new TextDecoder();
|
|
361
|
+
let rawBuffer = "";
|
|
362
|
+
let sawDone = false;
|
|
363
|
+
|
|
364
|
+
while (true) {
|
|
365
|
+
const { done, value } = await reader.read();
|
|
366
|
+
if (done) break;
|
|
367
|
+
|
|
368
|
+
rawBuffer += decoder.decode(value, { stream: true });
|
|
369
|
+
const parsed = parseSseBlocks(rawBuffer);
|
|
370
|
+
rawBuffer = parsed.rest;
|
|
371
|
+
|
|
372
|
+
for (const block of parsed.blocks) {
|
|
373
|
+
const { event, data } = parseSseEventBlock(block);
|
|
374
|
+
if (!data) continue;
|
|
375
|
+
if (data === "[DONE]") {
|
|
376
|
+
// Stop reading after this batch instead of waiting for the server
|
|
377
|
+
// to close the connection, but keep the buffered tail and finish
|
|
378
|
+
// the blocks already parsed alongside [DONE] instead of silently
|
|
379
|
+
// dropping them.
|
|
380
|
+
sawDone = true;
|
|
381
|
+
continue;
|
|
382
|
+
}
|
|
347
383
|
|
|
348
|
-
|
|
349
|
-
|
|
384
|
+
consumed = true;
|
|
385
|
+
onEvent({ event, data });
|
|
386
|
+
}
|
|
350
387
|
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
388
|
+
if (sawDone) break;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
if (typeof onTail === "function") {
|
|
392
|
+
consumed = consumed || Boolean(rawBuffer.trim());
|
|
393
|
+
onTail(rawBuffer);
|
|
394
|
+
}
|
|
354
395
|
|
|
355
|
-
|
|
396
|
+
return buildResult();
|
|
397
|
+
} catch (error) {
|
|
398
|
+
if (request.signal.aborted || consumed || attempt >= NATIVE_MAX_RETRIES || !isRetryableRequestError(error)) throw error;
|
|
399
|
+
const delayMs = retryDelayMs(response, attempt + 1);
|
|
400
|
+
emitPhase(onPhase, { type: "retry", attempt: attempt + 1, max_retries: NATIVE_MAX_RETRIES,
|
|
401
|
+
retry_delay_ms: delayMs, code: error.cause?.code || error.code || "", status: error.status || null });
|
|
402
|
+
await waitForRetry(delayMs, request.signal);
|
|
403
|
+
} finally {
|
|
404
|
+
if (reader) {
|
|
405
|
+
// A stream source may never settle cancellation. Cleanup must not
|
|
406
|
+
// hold a completed result or hide the original request failure.
|
|
407
|
+
try { Promise.resolve(reader.cancel?.()).catch(() => {}); } catch { /* preserve the request result */ }
|
|
408
|
+
try { reader.releaseLock?.(); } catch { /* preserve the request result */ }
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
}
|
|
356
412
|
} catch (err) {
|
|
357
413
|
if (request.timedOut()) {
|
|
358
414
|
const timeoutError = new Error(`CLI timeout (${normalizeTimeoutMs(timeoutMs)}ms)`);
|
|
@@ -156,6 +156,46 @@ function resolveRuntimeConfig({ workspaceRoot = process.cwd(), provider = "", mo
|
|
|
156
156
|
};
|
|
157
157
|
}
|
|
158
158
|
|
|
159
|
+
// Model discovery and inference must resolve the same credentials and URL.
|
|
160
|
+
// The synchronous resolver alone cannot refresh subscription credentials.
|
|
161
|
+
async function resolveAuthenticatedRuntime(options = {}) {
|
|
162
|
+
const runtime = resolveRuntimeConfig(options);
|
|
163
|
+
const workspaceRoot = options.workspaceRoot || process.cwd();
|
|
164
|
+
let accountId = "";
|
|
165
|
+
if (runtime.provider === "codex" && !runtime.apiKey) {
|
|
166
|
+
try {
|
|
167
|
+
const config = loadConfig(workspaceRoot) || {};
|
|
168
|
+
const { resolveCodexUpstreamCredentials } = require("./credentials/codex");
|
|
169
|
+
const credential = await resolveCodexUpstreamCredentials({
|
|
170
|
+
authPath: config.codexAuthPath,
|
|
171
|
+
refreshWindowMs: Number(config.codexOauthRefreshWindowSec || 300) * 1000,
|
|
172
|
+
env: process.env,
|
|
173
|
+
...(options.fetchImpl ? { fetchImpl: options.fetchImpl } : {}),
|
|
174
|
+
});
|
|
175
|
+
const token = String(credential && (credential.accessToken || credential.apiKey) || "").trim();
|
|
176
|
+
if (token) {
|
|
177
|
+
runtime.apiKey = token;
|
|
178
|
+
runtime.apiKeySource = String(credential.source || "codex-credential");
|
|
179
|
+
}
|
|
180
|
+
if (credential?.credentialKind === "api-key"
|
|
181
|
+
&& !String(process.env.UFOO_UCODE_BASE_URL || "").trim()
|
|
182
|
+
&& !String(config.ucodeBaseUrl || "").trim()) {
|
|
183
|
+
runtime.baseUrl = String(process.env.OPENAI_BASE_URL || DEFAULT_OPENAI_BASE_URL).trim();
|
|
184
|
+
}
|
|
185
|
+
if (credential?.credentialKind === "oauth") accountId = String(credential.accountId || "").trim();
|
|
186
|
+
} catch { /* Requests surface missing/invalid credentials. */ }
|
|
187
|
+
}
|
|
188
|
+
if (runtime.provider === "kimi" && runtime.apiKeySource === "kimi-credential" && runtime.kimiCredentialState !== "fresh") {
|
|
189
|
+
try {
|
|
190
|
+
const { resolveKimiUpstreamCredentials } = require("./credentials/kimi");
|
|
191
|
+
const credential = await resolveKimiUpstreamCredentials({ env: process.env,
|
|
192
|
+
...(options.fetchImpl ? { fetchImpl: options.fetchImpl } : {}) });
|
|
193
|
+
if (credential?.accessToken) runtime.apiKey = String(credential.accessToken).trim();
|
|
194
|
+
} catch { /* Retain the file token; requests surface auth failures. */ }
|
|
195
|
+
}
|
|
196
|
+
return { ...runtime, accountId, requestHeaders: accountId ? { "chatgpt-account-id": accountId } : {} };
|
|
197
|
+
}
|
|
198
|
+
|
|
159
199
|
function resolveCompletionUrl(baseUrl = "") {
|
|
160
200
|
const raw = String(baseUrl || "").trim();
|
|
161
201
|
if (!raw) return "";
|
|
@@ -185,4 +225,4 @@ function resolveAnthropicMessagesUrl(baseUrl = "") {
|
|
|
185
225
|
return `${normalized}/messages`;
|
|
186
226
|
}
|
|
187
227
|
|
|
188
|
-
module.exports = { normalizeProvider, normalizeKimiModel, resolveTransport, resolveRuntimeConfig, resolveCompletionUrl, resolveResponsesUrl, resolveAnthropicMessagesUrl, DEFAULT_OPENAI_BASE_URL };
|
|
228
|
+
module.exports = { normalizeProvider, normalizeKimiModel, resolveTransport, resolveRuntimeConfig, resolveAuthenticatedRuntime, resolveCompletionUrl, resolveResponsesUrl, resolveAnthropicMessagesUrl, DEFAULT_OPENAI_BASE_URL };
|
|
@@ -3,11 +3,13 @@
|
|
|
3
3
|
const fs = require("fs");
|
|
4
4
|
const path = require("path");
|
|
5
5
|
const { withFileLock } = require("./fileLock");
|
|
6
|
+
const { randomUUID } = require("crypto");
|
|
6
7
|
|
|
7
8
|
/** Append-only checkpoints also preserve source batches from in-flight turns. */
|
|
8
9
|
function createCheckpointStore({ workspaceRoot, namespace = "ucode", sessionId, redact = value => value } = {}) {
|
|
9
10
|
if (![namespace, sessionId].every(value => /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/.test(value || ""))) throw new Error("invalid checkpoint identity");
|
|
10
11
|
const file = path.join(path.resolve(workspaceRoot), ".ufoo", "agent", namespace, "context", `${sessionId}.jsonl`);
|
|
12
|
+
const retryFile = file.replace(/\.jsonl$/, ".retry.json");
|
|
11
13
|
const records = () => {
|
|
12
14
|
if (!fs.existsSync(file)) return [];
|
|
13
15
|
const lines = fs.readFileSync(file, "utf8").split("\n");
|
|
@@ -17,6 +19,18 @@ function createCheckpointStore({ workspaceRoot, namespace = "ucode", sessionId,
|
|
|
17
19
|
return {
|
|
18
20
|
file,
|
|
19
21
|
load: () => records().at(-1)?.checkpoint || null,
|
|
22
|
+
loadRetryState: () => fs.existsSync(retryFile) ? JSON.parse(fs.readFileSync(retryFile, "utf8")) : null,
|
|
23
|
+
saveRetryState(state) {
|
|
24
|
+
return withFileLock(file, () => {
|
|
25
|
+
const temporary = `${retryFile}.${randomUUID()}.tmp`;
|
|
26
|
+
try {
|
|
27
|
+
const fd = fs.openSync(temporary, "wx", 0o600);
|
|
28
|
+
try { fs.writeSync(fd, JSON.stringify(state)); fs.fsyncSync(fd); }
|
|
29
|
+
finally { fs.closeSync(fd); }
|
|
30
|
+
fs.renameSync(temporary, retryFile);
|
|
31
|
+
} finally { if (fs.existsSync(temporary)) fs.unlinkSync(temporary); }
|
|
32
|
+
});
|
|
33
|
+
},
|
|
20
34
|
archive: () => records().flatMap(record => record.sourceBatch || []),
|
|
21
35
|
commit(checkpoint, sourceBatch, expectedVersion) {
|
|
22
36
|
return withFileLock(file, () => {
|
|
@@ -31,7 +45,7 @@ function createCheckpointStore({ workspaceRoot, namespace = "ucode", sessionId,
|
|
|
31
45
|
return true;
|
|
32
46
|
});
|
|
33
47
|
},
|
|
34
|
-
remove() { if (fs.existsSync(
|
|
48
|
+
remove() { for (const entry of [file, retryFile]) if (fs.existsSync(entry)) fs.unlinkSync(entry); },
|
|
35
49
|
};
|
|
36
50
|
}
|
|
37
51
|
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
const { estimateTextTokens, estimateMessagesTokens, summaryMessage, historyDigest, historyUnits, userInstruction } = require("./contextBudget");
|
|
4
4
|
const { resolveModelContextLimit } = require("./contextWindow");
|
|
5
|
+
const { createHash } = require("crypto");
|
|
5
6
|
|
|
6
7
|
const DEFAULT_CONTEXT_POLICY = Object.freeze({ maxMessages: 50, keepRecentUnits: 6 });
|
|
7
8
|
|
|
@@ -36,13 +37,15 @@ function boundedRequest(work, signal, timeoutMs) {
|
|
|
36
37
|
function createContextManager({ store = null, policy = {}, now = Date.now } = {}) {
|
|
37
38
|
let checkpoint = null;
|
|
38
39
|
let loaded = false;
|
|
39
|
-
let
|
|
40
|
+
let retryState = null;
|
|
41
|
+
const retryBaseMs = Math.max(1, policy.retryDelayMs || 30000);
|
|
42
|
+
const retryMaxMs = Math.max(retryBaseMs, policy.maxRetryDelayMs || 300000);
|
|
40
43
|
let queue = Promise.resolve();
|
|
41
44
|
const limitOption = policy.limitTokens || Number(process.env.UFOO_CONTEXT_LIMIT_TOKENS) || 0;
|
|
42
45
|
|
|
43
46
|
async function prepare(input) {
|
|
44
47
|
if (input.signal?.aborted) throw Object.assign(new Error("context compression cancelled"), { code: "cancelled" });
|
|
45
|
-
if (!loaded) { checkpoint = store?.load() || null; loaded = true; }
|
|
48
|
+
if (!loaded) { checkpoint = store?.load() || null; retryState = store?.loadRetryState?.() || null; loaded = true; }
|
|
46
49
|
const { messages, model, systemPrompt = "", systemBlocks, tools = [], transport, signal, onPhase, onEvent, request = {} } = input;
|
|
47
50
|
const system = messages.filter(message => message.role === "system");
|
|
48
51
|
const source = messages.filter(message => message.role !== "system");
|
|
@@ -56,6 +59,14 @@ function createContextManager({ store = null, policy = {}, now = Date.now } = {}
|
|
|
56
59
|
const maxItems = policy.maxMessages || DEFAULT_CONTEXT_POLICY.maxMessages;
|
|
57
60
|
const keepUnits = policy.keepRecentUnits || DEFAULT_CONTEXT_POLICY.keepRecentUnits;
|
|
58
61
|
const batchBudget = policy.batchTokens || Math.min(16000, Math.floor(hard / 2));
|
|
62
|
+
const retryKey = createHash("sha256").update(JSON.stringify([model, request.provider, request.url,
|
|
63
|
+
transport.name || transport.id, limit, batchBudget, policy.timeoutMs || 30000, retryBaseMs, retryMaxMs])).digest("hex");
|
|
64
|
+
if (retryState?.key !== retryKey) retryState = null;
|
|
65
|
+
const saveRetryState = async value => {
|
|
66
|
+
retryState = value;
|
|
67
|
+
try { await store?.saveRetryState?.(value); }
|
|
68
|
+
catch (error) { await onEvent?.("context.compaction.retry_state_failed", { error: error.message }); }
|
|
69
|
+
};
|
|
59
70
|
const previousVersion = checkpoint?.version || 0;
|
|
60
71
|
let covered = checkpoint?.coveredCount || 0;
|
|
61
72
|
if (covered > source.length || checkpoint && historyDigest(source.slice(0, covered)) !== checkpoint.coveredDigest) {
|
|
@@ -94,7 +105,12 @@ function createContextManager({ store = null, policy = {}, now = Date.now } = {}
|
|
|
94
105
|
if (!unit.complete || cost > batchBudget) break;
|
|
95
106
|
batch = candidate;
|
|
96
107
|
}
|
|
97
|
-
if (!batch.length
|
|
108
|
+
if (!batch.length) break;
|
|
109
|
+
if (now() < (retryState?.retryAt || 0)) {
|
|
110
|
+
await onEvent?.("context.compaction.deferred", { retryAt: retryState.retryAt,
|
|
111
|
+
retryAfterMs: retryState.retryAt - now(), failures: retryState.failures, coveredCount: covered });
|
|
112
|
+
break;
|
|
113
|
+
}
|
|
98
114
|
attempted = true;
|
|
99
115
|
const version = checkpoint?.version || 0;
|
|
100
116
|
const summaryPrompt = JSON.stringify({ previousSummary, sourceStart: covered + 1,
|
|
@@ -124,20 +140,24 @@ function createContextManager({ store = null, policy = {}, now = Date.now } = {}
|
|
|
124
140
|
covered = nextCovered;
|
|
125
141
|
forced = false;
|
|
126
142
|
projected = project();
|
|
127
|
-
|
|
143
|
+
await saveRetryState(null);
|
|
128
144
|
await onEvent?.("context.compaction.completed", { version: next.version, coveredCount: covered, batchCount: batch.length,
|
|
129
145
|
durationMs: now() - started, usage: result.usage || {}, sourceArchive: store?.sourceRef || store?.file || "" });
|
|
130
146
|
} catch (error) {
|
|
131
147
|
if (error.code === "stale_checkpoint") loaded = false;
|
|
132
|
-
|
|
148
|
+
const cancelled = error.code === "cancelled" || signal?.aborted === true;
|
|
149
|
+
const failures = Math.min(16, (retryState?.failures || 0) + 1);
|
|
150
|
+
const retryDelayMs = Math.min(retryMaxMs, retryBaseMs * 2 ** (failures - 1));
|
|
151
|
+
if (!cancelled) await saveRetryState({ key: retryKey, failures, retryAt: now() + retryDelayMs });
|
|
133
152
|
await onEvent?.("context.compaction.failed", { error: error.message, code: error.code || "compaction_failed",
|
|
134
|
-
cancelled:
|
|
153
|
+
cancelled, durationMs: now() - started, ...(cancelled ? {} : { retryDelayMs, retryAt: retryState.retryAt, failures }),
|
|
135
154
|
coveredCount: covered, batchCount: batch.length });
|
|
136
155
|
if (error.code === "cancelled" || signal?.aborted) throw error;
|
|
137
156
|
break;
|
|
138
157
|
} finally { onPhase?.({ type: "request_start" }); }
|
|
139
158
|
}
|
|
140
|
-
if (forced || occupancy(projected) >= hard) throw Object.assign(new Error(attempted ? "context compression failed to create enough space; original history retained" : "context exceeds the configured input budget; original history retained"),
|
|
159
|
+
if (forced || occupancy(projected) >= hard) throw Object.assign(new Error(attempted ? "context compression failed to create enough space; original history retained" : "context exceeds the configured input budget; original history retained"),
|
|
160
|
+
{ code: "context_budget_exceeded", retryAfterMs: Math.max(0, (retryState?.retryAt || 0) - now()) });
|
|
141
161
|
return { messages: projected, coveredCount: covered, estimatedTokens: overhead + estimateMessagesTokens(projected), maxOutputTokens: reserve, checkpoint };
|
|
142
162
|
}
|
|
143
163
|
|
|
@@ -33,6 +33,7 @@ function projectEvent(state, event) {
|
|
|
33
33
|
if (event.type === "runtime.closed") state.owner = null;
|
|
34
34
|
if (event.type === "runtime.binding") state.binding = event.binding;
|
|
35
35
|
if (event.type === "context.checkpoint") state.contextCheckpoint = event.checkpoint;
|
|
36
|
+
if (event.type === "context.compaction.retry_state") state.contextCompactionRetry = event.retryState;
|
|
36
37
|
if (event.type === "capability.state_committed") state.capabilityState[event.capabilityId] = { version: event.version, value: event.value };
|
|
37
38
|
if (event.type === "command.started") state.commands[event.commandId] = { ...event, status: "uncertain" };
|
|
38
39
|
if (event.type === "command.resolved") Object.assign(state.commands[event.commandId], { status: "resolved", result: event.result });
|
|
@@ -36,6 +36,7 @@ async function runAgentLoop({
|
|
|
36
36
|
traceId = "", parentTaskRunId = "", parentSessionId = "",
|
|
37
37
|
artifactNamespace = "ucode",
|
|
38
38
|
contextManager = null, historyOffset: restoredHistoryOffset = null,
|
|
39
|
+
onConversationUpdate = null,
|
|
39
40
|
} = {}) {
|
|
40
41
|
const requestModel = String(model || "").trim();
|
|
41
42
|
if (!requestModel) throw new Error("agent model is not configured");
|
|
@@ -48,10 +49,15 @@ async function runAgentLoop({
|
|
|
48
49
|
const historyOffset = restoredHistoryOffset ?? (resume ? 0 : messages.filter(message => message.role !== "system").length);
|
|
49
50
|
if (!resume) transport.prepareMessages({ messages, systemPrompt, prompt });
|
|
50
51
|
const outputStart = messages.length;
|
|
51
|
-
const
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
52
|
+
const companionItems = new Set();
|
|
53
|
+
const currentTurnItems = () => clone(messages.slice(outputStart).filter((message, index) => {
|
|
54
|
+
if (String(message.role || "").toLowerCase() !== "user" || companionItems.has(index)) return true;
|
|
55
|
+
const companion = Array.isArray(message.content)
|
|
56
|
+
&& message.content.some(block => ["tool_result", "image", "image_url"].includes(block.type));
|
|
57
|
+
// Keep indices stable after one-shot image bytes retire to text markers.
|
|
58
|
+
if (companion) companionItems.add(index);
|
|
59
|
+
return companion;
|
|
60
|
+
}));
|
|
55
61
|
let executionState = initialState;
|
|
56
62
|
for (const policy of policies) if (policy.initializeState) executionState = policy.initializeState(executionState);
|
|
57
63
|
if (!executionState || typeof executionState !== "object") executionState = {};
|
|
@@ -64,6 +70,9 @@ async function runAgentLoop({
|
|
|
64
70
|
let emptyRetries = 0;
|
|
65
71
|
let activeLedger = null;
|
|
66
72
|
let lastLedger = null;
|
|
73
|
+
let activePending = [];
|
|
74
|
+
let flushedLedgerId = "";
|
|
75
|
+
let flushAttemptedLedgerId = "";
|
|
67
76
|
let autoContinues = 0;
|
|
68
77
|
let lastContinueKey = "";
|
|
69
78
|
let emptyContinues = 0;
|
|
@@ -98,11 +107,21 @@ async function runAgentLoop({
|
|
|
98
107
|
turnItems: currentTurnItems(), usage, executionState,
|
|
99
108
|
protocolLedger: lastLedger || ledgerApi.snapshotLedger(activeLedger), historyOffset, ...extra,
|
|
100
109
|
});
|
|
110
|
+
let committedMessages = messages.length;
|
|
111
|
+
let committedItems = [];
|
|
112
|
+
const commitConversation = async () => {
|
|
113
|
+
// A persistence port is awaited, unlike display/telemetry observers.
|
|
114
|
+
committedMessages = messages.length;
|
|
115
|
+
committedItems = currentTurnItems();
|
|
116
|
+
if (onConversationUpdate) await onConversationUpdate(finish({ turnItems: committedItems }));
|
|
117
|
+
};
|
|
101
118
|
const flush = (calls) => {
|
|
119
|
+
flushAttemptedLedgerId = activeLedger.turnId;
|
|
102
120
|
const pendingById = Object.fromEntries(calls.map((call) => [callId(call), call]));
|
|
103
121
|
materializeResolvedToolResults(activeLedger, { transport, messages: providerMessages, pendingById });
|
|
104
122
|
mirror();
|
|
105
123
|
lastLedger = ledgerApi.snapshotLedger(activeLedger);
|
|
124
|
+
flushedLedgerId = activeLedger.turnId;
|
|
106
125
|
};
|
|
107
126
|
const pendingInteraction = () => {
|
|
108
127
|
for (const policy of policies) {
|
|
@@ -119,7 +138,7 @@ async function runAgentLoop({
|
|
|
119
138
|
tools: tools.toOpenAiTools(), resume, requestKind, engineFingerprint: LOOP_IMPLEMENTATION_FINGERPRINT }) });
|
|
120
139
|
if (resume) await withFaultPoint("before_provider_resume", () => {});
|
|
121
140
|
|
|
122
|
-
while (true) {
|
|
141
|
+
try { while (true) {
|
|
123
142
|
activeGuards.ensureActive();
|
|
124
143
|
const turnStop = await policyStop("beforeTurn");
|
|
125
144
|
if (turnStop) return finish(turnStop);
|
|
@@ -229,6 +248,7 @@ async function runAgentLoop({
|
|
|
229
248
|
await event("model.retry", { code: "empty_response", retry: emptyRetries });
|
|
230
249
|
providerMessages.push({ role: "user", content: "Continue the current task after the tool results. Call any remaining tools, or provide a concrete final answer to the user. Do not end the turn with an empty response." });
|
|
231
250
|
mirror();
|
|
251
|
+
await commitConversation();
|
|
232
252
|
continue;
|
|
233
253
|
}
|
|
234
254
|
emptyRetries = 0;
|
|
@@ -242,9 +262,11 @@ async function runAgentLoop({
|
|
|
242
262
|
if (result && result.executionState) executionState = result.executionState;
|
|
243
263
|
providerMessages.push({ role: "user", content: JSON.stringify({ type: legacy.resultType, ...sanitizeResult(result && result.status ? result : { status: "rejected", ok: false, error: `${legacy.tool} failed` }) }) });
|
|
244
264
|
mirror();
|
|
265
|
+
await commitConversation();
|
|
245
266
|
continue;
|
|
246
267
|
}
|
|
247
268
|
mirror();
|
|
269
|
+
await commitConversation();
|
|
248
270
|
if (!aggregated.trim() && text) aggregated = text;
|
|
249
271
|
let continuation = false;
|
|
250
272
|
if (autoContinues < maxAutoContinues) {
|
|
@@ -266,6 +288,7 @@ async function runAgentLoop({
|
|
|
266
288
|
emptyRetries = 0;
|
|
267
289
|
const pending = transport.prepareToolCalls({ messages: providerMessages, turnResult, toolCalls: calls });
|
|
268
290
|
if (!pending) { mirror(); return finish(); }
|
|
291
|
+
activePending = pending;
|
|
269
292
|
loopGuard.observe(pending);
|
|
270
293
|
activeLedger = ledgerApi.createToolCallLedger({ provider, sessionId, deferableTools: tools.deferableTools() });
|
|
271
294
|
for (const call of pending) {
|
|
@@ -287,6 +310,7 @@ async function runAgentLoop({
|
|
|
287
310
|
resolve(call, batchError); toolCallsExecuted += 1; toolErrors += 1;
|
|
288
311
|
}
|
|
289
312
|
flush(pending);
|
|
313
|
+
await commitConversation();
|
|
290
314
|
continue;
|
|
291
315
|
}
|
|
292
316
|
let deferred = null;
|
|
@@ -318,7 +342,6 @@ async function runAgentLoop({
|
|
|
318
342
|
outcome: "unknown", durationMs: Date.now() - toolStarted });
|
|
319
343
|
throw error;
|
|
320
344
|
}
|
|
321
|
-
activeGuards.ensureActive();
|
|
322
345
|
if (result && result.executionState) executionState = result.executionState;
|
|
323
346
|
toolCallsExecuted += 1;
|
|
324
347
|
if (!result || result.ok === false) toolErrors += 1;
|
|
@@ -331,6 +354,7 @@ async function runAgentLoop({
|
|
|
331
354
|
}
|
|
332
355
|
resolve(call, result);
|
|
333
356
|
await event("tool.completed", { toolCallId: callId(call), toolName: name, result: sanitizeResult(result), durationMs: Date.now() - toolStarted });
|
|
357
|
+
activeGuards.ensureActive();
|
|
334
358
|
toolStop = await policyStop("afterTool", { call, result });
|
|
335
359
|
if (toolStop) continue;
|
|
336
360
|
if (toolBudget.maxToolCalls != null && toolCallsExecuted >= toolBudget.maxToolCalls) throw new Error(`tool call budget exceeded (${toolBudget.maxToolCalls})`);
|
|
@@ -340,9 +364,27 @@ async function runAgentLoop({
|
|
|
340
364
|
}
|
|
341
365
|
}
|
|
342
366
|
flush(pending);
|
|
367
|
+
if (!ledgerApi.listUnresolved(activeLedger).length && !ledgerApi.listDeferred(activeLedger).length) await commitConversation();
|
|
343
368
|
if (toolStop) return finish(toolStop);
|
|
344
369
|
const interaction = pendingInteraction();
|
|
345
370
|
if (deferred || interaction) return finish({ waitingUserInteraction: true, interactionId: deferred && deferred.interactionId || interaction && interaction.id || "" });
|
|
371
|
+
} } catch (error) {
|
|
372
|
+
if (!error || typeof error !== "object") error = new Error(String(error));
|
|
373
|
+
if (activeLedger && activeLedger.turnId !== flushedLedgerId && activeLedger.turnId !== flushAttemptedLedgerId
|
|
374
|
+
&& !ledgerApi.listUnresolved(activeLedger).length && !ledgerApi.listDeferred(activeLedger).length) {
|
|
375
|
+
// Cancellation/budget checks can fail immediately after the last tool
|
|
376
|
+
// returned a known result. That completed batch still belongs in history.
|
|
377
|
+
flush(activePending);
|
|
378
|
+
try { await commitConversation(); }
|
|
379
|
+
catch (persistenceError) { error = persistenceError; }
|
|
380
|
+
}
|
|
381
|
+
// Preserve completed units without exposing a newly declared, interrupted
|
|
382
|
+
// tool batch as a valid continuation transcript. The ledger retains its
|
|
383
|
+
// unresolved/unknown effects for recovery inspection.
|
|
384
|
+
error.result = finish({ error: error.message, stopReason: error.code || "runtime_error",
|
|
385
|
+
messages: clone(messages.slice(0, committedMessages)), turnItems: clone(committedItems),
|
|
386
|
+
protocolLedger: ledgerApi.snapshotLedger(activeLedger) || lastLedger });
|
|
387
|
+
throw error;
|
|
346
388
|
}
|
|
347
389
|
}
|
|
348
390
|
|