u-foo 3.1.6 → 4.0.0
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 +172 -13
- package/README.zh-CN.md +108 -13
- package/SKILLS/ufoo/SKILL.md +15 -3
- package/SKILLS/ufoo-bus/SKILL.md +21 -1
- package/bin/uclaude.js +4 -0
- package/bin/ucodex.js +4 -0
- package/bin/ufoo.js +3 -1
- 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 +10 -3
- package/scripts/postinstall-skills.js +53 -0
- package/scripts/postinstall.js +11 -16
- package/scripts/smoke-native-messages.js +214 -0
- package/src/agents/activity/activityStateWriter.js +37 -38
- package/src/agents/capabilities/agentManagement/index.js +4 -0
- package/src/agents/capabilities/agentManagement/service.js +113 -0
- package/src/agents/capabilities/agentRouting/index.js +4 -0
- package/src/agents/capabilities/coding/index.js +32 -0
- package/src/agents/capabilities/coordination/index.js +37 -0
- package/src/agents/capabilities/globalRouting/index.js +5 -0
- package/src/agents/capabilities/groups/index.js +3 -0
- package/src/agents/capabilities/index.js +25 -0
- package/src/agents/capabilities/planning/index.js +123 -0
- package/src/agents/capabilities/planning/main.js +28 -0
- package/src/agents/capabilities/projectDiscovery/index.js +3 -0
- package/src/agents/capabilities/scheduling/index.js +3 -0
- package/src/agents/capabilities/sharedMemory/index.js +4 -0
- package/src/agents/capabilities/skills/index.js +12 -0
- package/src/agents/capabilities/taskExecution/index.js +3 -0
- package/src/agents/capabilities/taskReports/index.js +6 -0
- package/src/agents/controller/controllerToolExecutor.js +6 -4
- package/src/agents/controller/loopRuntime.js +85 -221
- package/src/agents/controller/ufooAgent.js +1 -0
- package/src/agents/internal/internalRunner.js +103 -32
- package/src/agents/launch/launcher.js +88 -6
- package/src/agents/launch/nativeCapabilities.js +40 -0
- package/src/agents/launch/nativeMessages.js +362 -0
- package/src/agents/launch/notifier.js +13 -18
- package/src/agents/launch/readyDetector.js +26 -12
- package/src/agents/profiles/coding.js +6 -0
- package/src/agents/profiles/globalRouter.js +2 -0
- package/src/agents/profiles/main.js +5 -0
- package/src/agents/prompts/groupBootstrap.js +10 -0
- package/src/agents/prompts/mainAgent.js +39 -0
- package/src/agents/prompts/native/tasks.js +2 -2
- package/src/agents/prompts/native/ufoo.js +3 -0
- package/src/agents/providers/claudeEventTranslator.js +6 -1
- package/src/agents/providers/claudeThreadProvider.js +44 -2
- package/src/agents/providers/codexEventTranslator.js +47 -7
- package/src/agents/providers/codexThreadProvider.js +3 -2
- package/src/agents/providers/controllerJsonTransport.js +28 -0
- package/src/agents/providers/credentials/claude.js +10 -3
- package/src/agents/providers/nativeTransport.js +1135 -0
- package/src/agents/providers/runtimeConfig.js +186 -0
- package/src/agents/providers/thinkingLevels.js +132 -0
- package/src/agents/providers/transports/anthropicMessagesTransport.js +121 -0
- package/src/agents/providers/transports/index.js +10 -0
- package/src/agents/providers/transports/openaiChatTransport.js +117 -0
- package/src/agents/providers/transports/openaiResponsesTransport.js +120 -0
- package/src/agents/providers/transports/responsesProtocol.js +499 -0
- package/src/agents/providers/transports/systemBlocks.js +16 -0
- package/src/agents/providers/transports/transportContract.js +50 -0
- package/src/agents/providers/transports/visionBlocks.js +151 -0
- package/src/agents/providers/upstreamTransport.js +13 -4
- package/src/agents/runtime/composeCapabilities.js +89 -0
- package/src/agents/runtime/context/commandStore.js +43 -0
- package/src/agents/runtime/context/contextWindow.js +119 -0
- package/src/agents/runtime/context/fileLock.js +36 -0
- package/src/agents/runtime/context/runtimeStore.js +126 -0
- package/src/agents/runtime/context/sessionJournal.js +360 -0
- package/src/agents/runtime/context/sessionStore.js +57 -0
- package/src/agents/runtime/core/agentLoop.js +270 -0
- package/src/agents/runtime/core/stableJson.js +29 -0
- package/src/agents/runtime/core/toolLoopGuard.js +55 -0
- package/src/agents/runtime/createAgentRuntime.js +247 -0
- package/src/agents/runtime/index.js +14 -0
- package/src/agents/runtime/protocol/faultHarness.js +90 -0
- package/src/agents/runtime/protocol/materialize.js +107 -0
- package/src/agents/runtime/protocol/toolCallLedger.js +221 -0
- package/src/agents/runtime/tasks/resourceLease.js +66 -0
- package/src/agents/runtime/tasks/scheduler.js +73 -0
- package/src/agents/runtime/tools/registry.js +57 -0
- package/src/app/chat/ChatController.js +14 -3
- package/src/app/chat/agentDirectory.js +8 -2
- package/src/app/chat/commandExecutor.js +36 -46
- package/src/app/chat/commands.js +14 -7
- package/src/app/chat/daemonConnection.js +58 -5
- package/src/app/chat/daemonMessageRouter.js +61 -3
- package/src/app/chat/inputSubmitHandler.js +14 -2
- package/src/app/chat/launchRequestContext.js +42 -0
- package/src/app/chat/multiWindow/paneManager.js +85 -165
- package/src/app/chat/streamState.js +3 -3
- package/src/app/chat/transport.js +1 -1
- package/src/app/cli/busCoreCommands.js +9 -0
- package/src/app/cli/features/doctor.js +33 -0
- package/src/app/cli/features/skills.js +16 -4
- package/src/app/cli/reportCoreCommands.js +37 -0
- package/src/app/cli/run.js +40 -39
- package/src/code/agent.js +16 -4
- package/src/code/context/artifacts.js +12 -11
- package/src/code/context/assembler.js +2 -1
- package/src/code/context/promptLayers.js +1 -13
- package/src/code/context/stableJson.js +2 -27
- package/src/code/contextWindow.js +2 -117
- package/src/code/conversation/sessionJournal.js +3 -349
- package/src/code/internalThread.js +100 -0
- package/src/code/nativeRunner.js +36 -2668
- package/src/code/protocol/faultHarness.js +2 -88
- package/src/code/protocol/materialize.js +2 -105
- package/src/code/protocol/toolCallLedger.js +5 -215
- package/src/code/providers/anthropicMessagesTransport.js +2 -118
- package/src/code/providers/openaiChatTransport.js +2 -114
- package/src/code/providers/openaiResponsesTransport.js +2 -117
- package/src/code/providers/responsesProtocol.js +2 -497
- package/src/code/providers/transportContract.js +2 -48
- package/src/code/providers/visionBlocks.js +2 -149
- package/src/code/sessionStore.js +24 -96
- package/src/code/thinkingLevels.js +1 -130
- package/src/code/toolLoopGuard.js +3 -49
- package/src/code/tools/artifactRead.js +1 -1
- package/src/code/tools/executor.js +373 -0
- package/src/code/tools/specs.js +312 -0
- package/src/config.js +81 -67
- package/src/coordination/bus/deliveryQueue.js +16 -2
- package/src/coordination/bus/index.js +2 -6
- package/src/coordination/bus/inject.js +13 -5
- package/src/coordination/bus/nativeReceipts.js +100 -0
- package/src/coordination/bus/queue.js +1 -3
- package/src/coordination/bus/utils.js +7 -3
- package/src/coordination/history/agentSurface.js +142 -0
- package/src/coordination/history/controllerSummary.js +23 -0
- package/src/coordination/memory/index.js +5 -21
- package/src/coordination/report/store.js +103 -83
- package/src/coordination/state/agentsStore.js +57 -3
- package/src/coordination/state/fileLock.js +2 -0
- package/src/coordination/state/workspaceAccess.js +36 -0
- package/src/runtime/contracts/agentMode.js +17 -0
- package/src/runtime/contracts/eventContract.js +3 -0
- package/src/runtime/contracts/uiProtocol.js +4 -0
- package/src/runtime/daemon/agentHost.js +375 -0
- package/src/runtime/daemon/busBridge.js +396 -0
- package/src/runtime/daemon/claudeChannel.js +159 -0
- package/src/runtime/daemon/controlPlaneService.js +27 -17
- package/src/runtime/daemon/cronOps.js +25 -17
- package/src/runtime/daemon/deliveryScheduler.js +32 -5
- package/src/runtime/daemon/executionPaths.js +30 -0
- package/src/runtime/daemon/globalDaemon.js +28 -1
- package/src/runtime/daemon/groupOrchestrator.js +1 -0
- package/src/runtime/daemon/index.js +114 -344
- package/src/runtime/daemon/ipcServer.js +32 -10
- package/src/runtime/daemon/mcpConfigure.js +113 -20
- package/src/runtime/daemon/mcpHttpServer.js +27 -5
- package/src/runtime/daemon/mcpServer.js +7 -4
- package/src/runtime/daemon/mcpStdioProxy.js +127 -10
- package/src/runtime/daemon/ops.js +22 -17
- package/src/runtime/daemon/promptRequest.js +23 -4
- package/src/runtime/daemon/providerSessions.js +67 -33
- package/src/runtime/daemon/reportControlBus.js +59 -25
- package/src/runtime/daemon/status.js +4 -0
- package/src/runtime/privacy/redactor.js +2 -2
- package/src/runtime/projects/identity.js +2 -1
- package/src/runtime/projects/registry.js +98 -38
- package/src/tools/controllerSchemas.js +24 -0
- package/src/tools/handlers/dispatchMessage.js +5 -2
- package/src/tools/handlers/listAgents.js +3 -1
- package/src/tools/handlers/readBusSummary.js +3 -1
- package/src/tools/handlers/readProjectRegistry.js +29 -2
- package/src/tools/handlers/routeAgent.js +35 -0
- package/src/tools/index.js +1 -0
- package/src/tools/registry.js +2 -0
- package/src/tools/schemaFixtures.js +16 -3
- package/src/tools/tier1/routeAgent.js +2 -2
- package/src/tools/tier2/runtimeCoordination.js +38 -0
- package/src/tools/types.js +2 -0
- package/src/ui/agentPresentation.js +109 -0
- package/src/ui/agentSurface.js +270 -0
- package/src/ui/format/banner.js +8 -11
- package/src/ui/format/startupBanner.js +50 -0
- package/src/ui/multiPaneBusMirror.js +29 -3
- package/src/ui/rustChatHost.js +170 -438
- package/src/ui/rustMultiSession.js +225 -51
- package/src/ui/rustUcodeHost.js +20 -87
- package/src/ui/settingsBridge.js +7 -4
- package/src/app/chat/agentEnter.js +0 -70
- package/src/app/chat/multiWindow/index.js +0 -310
- package/src/app/chat/multiWindow/paneLayout.js +0 -84
- package/src/app/chat/multiWindow/renderer.js +0 -420
- package/src/app/chat/multiWindow/virtualTerminal.js +0 -327
- package/src/app/chat/multiWindow/vtFrame.js +0 -93
- package/src/ui/multiWindowHandoff.js +0 -232
- package/src/ui/ptyHandoff.js +0 -23
package/src/config.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
const fs = require("fs");
|
|
2
2
|
const os = require("os");
|
|
3
3
|
const path = require("path");
|
|
4
|
+
const { withFileLock } = require("./coordination/state/fileLock");
|
|
5
|
+
const { writeFileAtomic } = require("./coordination/bus/utils");
|
|
4
6
|
|
|
5
7
|
const UCODE_FIELDS = [
|
|
6
8
|
"ucodeProvider",
|
|
@@ -187,6 +189,17 @@ function loadJsonSafe(filePath) {
|
|
|
187
189
|
}
|
|
188
190
|
}
|
|
189
191
|
|
|
192
|
+
function loadJsonForUpdate(filePath) {
|
|
193
|
+
try {
|
|
194
|
+
const value = JSON.parse(fs.readFileSync(filePath, "utf8"));
|
|
195
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Expected a JSON object");
|
|
196
|
+
return value;
|
|
197
|
+
} catch (error) {
|
|
198
|
+
if (error.code === "ENOENT") return {};
|
|
199
|
+
throw new Error(`Refusing to overwrite unreadable configuration: ${filePath}`, { cause: error });
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
190
203
|
function loadConfig(projectRoot) {
|
|
191
204
|
try {
|
|
192
205
|
const raw = loadJsonSafe(configPath(projectRoot));
|
|
@@ -221,7 +234,7 @@ function loadConfig(projectRoot) {
|
|
|
221
234
|
claudeOauthProfile: normalizeClaudeOauthProfile(raw.claudeOauthProfile),
|
|
222
235
|
claudeOauthTokenPath: normalizeClaudeOauthTokenPath(raw.claudeOauthTokenPath),
|
|
223
236
|
claudeOauthRefreshWindowSec: normalizeClaudeOauthRefreshWindowSec(raw.claudeOauthRefreshWindowSec),
|
|
224
|
-
autoResume: raw.autoResume
|
|
237
|
+
autoResume: typeof raw.autoResume === "boolean" ? raw.autoResume : DEFAULT_CONFIG.autoResume,
|
|
225
238
|
// Merge ucode fields from global config so callers still see them
|
|
226
239
|
...loadGlobalUcodeConfig(),
|
|
227
240
|
};
|
|
@@ -240,56 +253,53 @@ function loadConfig(projectRoot) {
|
|
|
240
253
|
|
|
241
254
|
function saveConfig(projectRoot, config) {
|
|
242
255
|
const target = configPath(projectRoot);
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
for (const [k, v] of Object.entries(config)) {
|
|
253
|
-
if (!UCODE_FIELDS.includes(k)) {
|
|
254
|
-
projectUpdates[k] = v;
|
|
256
|
+
return withFileLock(target, () => {
|
|
257
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
258
|
+
const existing = loadJsonForUpdate(target);
|
|
259
|
+
// Strip ucode fields — they belong in global config only
|
|
260
|
+
const projectUpdates = {};
|
|
261
|
+
for (const [k, v] of Object.entries(config)) {
|
|
262
|
+
if (!UCODE_FIELDS.includes(k)) {
|
|
263
|
+
projectUpdates[k] = v;
|
|
264
|
+
}
|
|
255
265
|
}
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
266
|
+
const merged = {
|
|
267
|
+
...DEFAULT_CONFIG,
|
|
268
|
+
...existing,
|
|
269
|
+
...projectUpdates,
|
|
270
|
+
};
|
|
271
|
+
const hasProjectDaemonTopology =
|
|
272
|
+
Object.prototype.hasOwnProperty.call(existing, "daemonTopology")
|
|
273
|
+
|| Object.prototype.hasOwnProperty.call(projectUpdates, "daemonTopology");
|
|
274
|
+
// Remove any stale ucode fields from project config
|
|
275
|
+
for (const f of UCODE_FIELDS) {
|
|
276
|
+
delete merged[f];
|
|
277
|
+
}
|
|
278
|
+
merged.launchMode = normalizeLaunchMode(merged.launchMode);
|
|
279
|
+
if (hasProjectDaemonTopology) {
|
|
280
|
+
merged.daemonTopology = normalizeDaemonTopology(merged.daemonTopology);
|
|
281
|
+
} else {
|
|
282
|
+
// Topology is a machine-wide rollout setting unless a project explicitly
|
|
283
|
+
// opts into an override. Do not persist the default and accidentally pin
|
|
284
|
+
// this project to project-daemon mode forever.
|
|
285
|
+
delete merged.daemonTopology;
|
|
286
|
+
}
|
|
287
|
+
merged.agentProvider = normalizeAgentProvider(merged.agentProvider);
|
|
288
|
+
merged.agentModel = typeof merged.agentModel === "string" ? merged.agentModel.trim() : "";
|
|
289
|
+
merged.routerProvider = typeof merged.routerProvider === "string" ? merged.routerProvider.trim() : "";
|
|
290
|
+
merged.routerModel = typeof merged.routerModel === "string" ? merged.routerModel.trim() : "";
|
|
291
|
+
merged.controllerMode = normalizeControllerMode(merged.controllerMode);
|
|
292
|
+
merged.mcpPort = normalizeMcpPort(merged.mcpPort);
|
|
293
|
+
merged.codexInternalThreadMode = normalizeCodexInternalThreadMode(merged.codexInternalThreadMode);
|
|
294
|
+
merged.codexAuthPath = normalizeCodexAuthPath(merged.codexAuthPath);
|
|
295
|
+
merged.codexOauthRefreshWindowSec = normalizeCodexOauthRefreshWindowSec(merged.codexOauthRefreshWindowSec);
|
|
296
|
+
merged.claudeOauthProfile = normalizeClaudeOauthProfile(merged.claudeOauthProfile);
|
|
297
|
+
merged.claudeOauthTokenPath = normalizeClaudeOauthTokenPath(merged.claudeOauthTokenPath);
|
|
298
|
+
merged.claudeOauthRefreshWindowSec = normalizeClaudeOauthRefreshWindowSec(merged.claudeOauthRefreshWindowSec);
|
|
299
|
+
merged.autoResume = typeof merged.autoResume === "boolean" ? merged.autoResume : DEFAULT_CONFIG.autoResume;
|
|
300
|
+
writeFileAtomic(target, JSON.stringify(merged, null, 2), { mode: 0o600 });
|
|
301
|
+
return merged;
|
|
302
|
+
});
|
|
293
303
|
}
|
|
294
304
|
|
|
295
305
|
function loadGlobalUcodeConfig() {
|
|
@@ -306,16 +316,18 @@ function loadGlobalUcodeConfig() {
|
|
|
306
316
|
|
|
307
317
|
function saveGlobalUcodeConfig(updates = {}) {
|
|
308
318
|
const target = globalConfigPath();
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
319
|
+
return withFileLock(target, () => {
|
|
320
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
321
|
+
const existing = loadJsonForUpdate(target);
|
|
322
|
+
const merged = { ...existing };
|
|
323
|
+
for (const [k, v] of Object.entries(updates)) {
|
|
324
|
+
if (UCODE_FIELDS.includes(k)) {
|
|
325
|
+
merged[k] = typeof v === "string" ? v : "";
|
|
326
|
+
}
|
|
315
327
|
}
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
328
|
+
writeFileAtomic(target, JSON.stringify(merged, null, 2), { mode: 0o600 });
|
|
329
|
+
return merged;
|
|
330
|
+
});
|
|
319
331
|
}
|
|
320
332
|
|
|
321
333
|
function loadGlobalDaemonConfig() {
|
|
@@ -327,14 +339,16 @@ function loadGlobalDaemonConfig() {
|
|
|
327
339
|
|
|
328
340
|
function saveGlobalDaemonConfig(updates = {}) {
|
|
329
341
|
const target = globalConfigPath();
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
342
|
+
return withFileLock(target, () => {
|
|
343
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
344
|
+
const existing = loadJsonForUpdate(target);
|
|
345
|
+
const merged = { ...existing };
|
|
346
|
+
if (Object.prototype.hasOwnProperty.call(updates, "daemonTopology")) {
|
|
347
|
+
merged.daemonTopology = normalizeDaemonTopology(updates.daemonTopology);
|
|
348
|
+
}
|
|
349
|
+
writeFileAtomic(target, JSON.stringify(merged, null, 2), { mode: 0o600 });
|
|
350
|
+
return loadGlobalDaemonConfig();
|
|
351
|
+
});
|
|
338
352
|
}
|
|
339
353
|
|
|
340
354
|
module.exports = {
|
|
@@ -15,6 +15,7 @@ const {
|
|
|
15
15
|
} = require("./utils");
|
|
16
16
|
|
|
17
17
|
const PROCESSING_STALE_MS = 30000;
|
|
18
|
+
const { withFileLock } = require("../state/fileLock");
|
|
18
19
|
|
|
19
20
|
function positiveSeq(event) {
|
|
20
21
|
const seq = Number(event && event.seq);
|
|
@@ -241,12 +242,15 @@ class DeliveryQueue {
|
|
|
241
242
|
.filter((file) => this.isRecoverableProcessingFile(file, options));
|
|
242
243
|
if (files.length === 0) return { recovered: 0, files: [] };
|
|
243
244
|
|
|
244
|
-
const all = [
|
|
245
|
+
const all = [];
|
|
245
246
|
for (const file of files) {
|
|
246
247
|
all.push(...readJsonlLoose(file));
|
|
247
248
|
}
|
|
249
|
+
const pending = this.readPendingRaw();
|
|
250
|
+
all.push(...pending);
|
|
248
251
|
|
|
249
|
-
const
|
|
252
|
+
const latestPending = new Map(pending.filter((event) => positiveSeq(event)).map((event) => [positiveSeq(event), event]));
|
|
253
|
+
const merged = this.mergeAndSort(all).map((event) => latestPending.get(positiveSeq(event)) || event);
|
|
250
254
|
this.writePending(merged);
|
|
251
255
|
|
|
252
256
|
for (const file of files) {
|
|
@@ -319,6 +323,16 @@ class DeliveryQueue {
|
|
|
319
323
|
}
|
|
320
324
|
}
|
|
321
325
|
|
|
326
|
+
// All queue mutations share the same cross-process transaction, including
|
|
327
|
+
// nested recovery and pending rewrites. Atomic rename alone cannot protect an
|
|
328
|
+
// append from a concurrent read-modify-write consumer.
|
|
329
|
+
for (const method of ["append", "writePending", "recover", "claimNext", "completeClaim", "restoreClaim", "readPending"]) {
|
|
330
|
+
const implementation = DeliveryQueue.prototype[method];
|
|
331
|
+
DeliveryQueue.prototype[method] = function (...args) {
|
|
332
|
+
return withFileLock(this.pendingFile, () => implementation.apply(this, args));
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
|
|
322
336
|
module.exports = {
|
|
323
337
|
DeliveryQueue,
|
|
324
338
|
QUEUE_TYPES,
|
|
@@ -11,7 +11,6 @@ const {
|
|
|
11
11
|
generateInstanceId,
|
|
12
12
|
subscriberToSafeName,
|
|
13
13
|
isPidAlive,
|
|
14
|
-
truncateFile,
|
|
15
14
|
getCurrentTty,
|
|
16
15
|
sleep,
|
|
17
16
|
} = require("./utils");
|
|
@@ -891,13 +890,10 @@ class EventBus {
|
|
|
891
890
|
|
|
892
891
|
const queuePath = this.queueManager.getPendingPath(target);
|
|
893
892
|
this.queueManager.ensureQueueDir(target);
|
|
894
|
-
if (!fs.existsSync(queuePath)) {
|
|
895
|
-
fs.writeFileSync(queuePath, "", "utf8");
|
|
896
|
-
}
|
|
897
893
|
|
|
898
894
|
if (options.reset) {
|
|
899
895
|
console.log("[listen] Resetting queue...");
|
|
900
|
-
|
|
896
|
+
await this.queueManager.clearPending(target);
|
|
901
897
|
}
|
|
902
898
|
|
|
903
899
|
const readLines = () => {
|
|
@@ -958,7 +954,7 @@ class EventBus {
|
|
|
958
954
|
async inject(subscriber, commandOverride) {
|
|
959
955
|
this.ensureBus();
|
|
960
956
|
const injector = new Injector(this.busDir, this.agentsFile);
|
|
961
|
-
await injector.inject(subscriber, commandOverride);
|
|
957
|
+
await injector.inject(subscriber, commandOverride, { deliveryId: `manual:${require("crypto").randomUUID()}` });
|
|
962
958
|
}
|
|
963
959
|
}
|
|
964
960
|
|
|
@@ -387,16 +387,17 @@ class Injector {
|
|
|
387
387
|
/**
|
|
388
388
|
* 使用指定路径的 PTY socket 注入命令
|
|
389
389
|
*/
|
|
390
|
-
async injectPtyAtPath(sockPath, command) {
|
|
390
|
+
async injectPtyAtPath(sockPath, command, options = {}) {
|
|
391
391
|
return new Promise((resolve, reject) => {
|
|
392
392
|
const client = net.createConnection(sockPath, () => {
|
|
393
|
-
client.write(JSON.stringify({ type: "inject", command }) + "\n");
|
|
393
|
+
client.write(JSON.stringify({ type: "inject", command, ...options }) + "\n");
|
|
394
394
|
});
|
|
395
395
|
|
|
396
396
|
let buffer = "";
|
|
397
|
+
let received = false;
|
|
397
398
|
const timeout = setTimeout(() => {
|
|
398
399
|
client.destroy();
|
|
399
|
-
reject(new Error("
|
|
400
|
+
reject(Object.assign(new Error("Inject response timed out"), options.deliveryId ? { code: "native_outcome_unknown" } : {}));
|
|
400
401
|
}, 5000);
|
|
401
402
|
|
|
402
403
|
client.on("data", (data) => {
|
|
@@ -406,6 +407,7 @@ class Injector {
|
|
|
406
407
|
|
|
407
408
|
for (const line of lines) {
|
|
408
409
|
if (!line.trim()) continue;
|
|
410
|
+
received = true;
|
|
409
411
|
clearTimeout(timeout);
|
|
410
412
|
try {
|
|
411
413
|
const res = JSON.parse(line);
|
|
@@ -413,7 +415,7 @@ class Injector {
|
|
|
413
415
|
if (res.ok) {
|
|
414
416
|
resolve();
|
|
415
417
|
} else {
|
|
416
|
-
reject(new Error(res.error || "PTY inject failed"));
|
|
418
|
+
reject(Object.assign(new Error(res.error || "PTY inject failed"), { code: res.code }));
|
|
417
419
|
}
|
|
418
420
|
} catch (err) {
|
|
419
421
|
client.end();
|
|
@@ -430,6 +432,7 @@ class Injector {
|
|
|
430
432
|
|
|
431
433
|
client.on("close", () => {
|
|
432
434
|
clearTimeout(timeout);
|
|
435
|
+
if (!received) reject(Object.assign(new Error("Inject socket closed without a receipt"), options.deliveryId ? { code: "native_outcome_unknown" } : {}));
|
|
433
436
|
});
|
|
434
437
|
});
|
|
435
438
|
}
|
|
@@ -455,7 +458,7 @@ class Injector {
|
|
|
455
458
|
* 2. tmux send-keys(无需权限)
|
|
456
459
|
* 3. Terminal.app/iTerm2 tty lookup(terminal mode fallback)
|
|
457
460
|
*/
|
|
458
|
-
async inject(subscriber, commandOverride) {
|
|
461
|
+
async inject(subscriber, commandOverride, delivery = {}) {
|
|
459
462
|
if (String(subscriber || "").startsWith("ufoo-code:")) {
|
|
460
463
|
throw new Error(`Inject disabled for ${subscriber}. ufoo-code consumes bus internally.`);
|
|
461
464
|
}
|
|
@@ -471,6 +474,11 @@ class Injector {
|
|
|
471
474
|
}
|
|
472
475
|
|
|
473
476
|
const meta = this.getAgentMeta(subscriber) || {};
|
|
477
|
+
if (meta.native_delivery) {
|
|
478
|
+
// A native write may already be accepted. Never fall back to keystrokes
|
|
479
|
+
// after a native failure; the scheduler retains the queued work.
|
|
480
|
+
return this.injectPtyAtPath(this.getInjectSockPath(subscriber), command, delivery);
|
|
481
|
+
}
|
|
474
482
|
const launchMode = meta.launch_mode || "";
|
|
475
483
|
const adapterRouter = createTerminalAdapterRouter();
|
|
476
484
|
const adapter = adapterRouter.getAdapter({ launchMode, agentId: subscriber, meta });
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
const fs = require("fs");
|
|
2
|
+
const path = require("path");
|
|
3
|
+
const crypto = require("crypto");
|
|
4
|
+
const { getUfooPaths } = require("../state/paths");
|
|
5
|
+
const { withFileLock } = require("../state/fileLock");
|
|
6
|
+
const { writeFileAtomic, subscriberToSafeName, isPidAlive } = require("./utils");
|
|
7
|
+
|
|
8
|
+
function submissionId(value) {
|
|
9
|
+
const bytes = crypto.createHash("sha256").update(String(value)).digest().subarray(0, 16);
|
|
10
|
+
bytes[6] = (bytes[6] & 0x0f) | 0x50;
|
|
11
|
+
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
|
12
|
+
const hex = bytes.toString("hex");
|
|
13
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function receiptDirectory(projectRoot, subscriber) {
|
|
17
|
+
if (!/^[a-zA-Z0-9._:-]+$/.test(subscriber) || [".", ".."].includes(subscriber)) throw new Error("Invalid subscriber ID");
|
|
18
|
+
return path.join(getUfooPaths(projectRoot).busQueuesDir, subscriberToSafeName(subscriber), "native-receipts");
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function receiptFile(projectRoot, subscriber, id) {
|
|
22
|
+
if (!/^[a-f0-9-]{36}$/.test(id)) throw new Error("Invalid receipt ID");
|
|
23
|
+
return path.join(receiptDirectory(projectRoot, subscriber), `${id}.json`);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function readNativeReceipt(projectRoot, subscriber, deliveryId) {
|
|
27
|
+
const file = receiptFile(projectRoot, subscriber, submissionId(deliveryId));
|
|
28
|
+
try { return JSON.parse(fs.readFileSync(file, "utf8")); }
|
|
29
|
+
catch (error) { if (error.code === "ENOENT") return null; throw error; }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function listNativeReceipts(projectRoot, subscriber) {
|
|
33
|
+
const dir = receiptDirectory(projectRoot, subscriber);
|
|
34
|
+
if (!fs.existsSync(dir)) return [];
|
|
35
|
+
return fs.readdirSync(dir).filter((name) => /^[a-f0-9-]{36}\.json$/.test(name))
|
|
36
|
+
.map((name) => JSON.parse(fs.readFileSync(path.join(dir, name), "utf8")));
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function writeReceipt(file, receipt) {
|
|
40
|
+
writeFileAtomic(file, JSON.stringify({ ...receipt, updated_at: new Date().toISOString() }), { mode: 0o600 });
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function resolveNativeReceipt(projectRoot, subscriber, id, resolution) {
|
|
44
|
+
if (!["accepted", "retry"].includes(resolution)) throw new Error("Resolution must be accepted or retry");
|
|
45
|
+
const file = receiptFile(projectRoot, subscriber, id);
|
|
46
|
+
return withFileLock(file, () => {
|
|
47
|
+
const receipt = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
48
|
+
if (!["unknown", "inflight"].includes(receipt.state)) throw new Error("Only uncertain receipts can be resolved");
|
|
49
|
+
if (receipt.state === "inflight" && isPidAlive(receipt.owner_pid)) throw new Error("Delivery is still in flight; wait for its response");
|
|
50
|
+
const next = { ...receipt, state: resolution === "accepted" ? "accepted" : "retry_allowed",
|
|
51
|
+
resolution, resolved_at: new Date().toISOString(), result: resolution === "accepted" ? { queued: true, resolved_by: "operator" } : undefined };
|
|
52
|
+
writeReceipt(file, next);
|
|
53
|
+
return next;
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function withNativeReceipts({ projectRoot, subscriber, send }) {
|
|
58
|
+
const dir = receiptDirectory(projectRoot, subscriber);
|
|
59
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
60
|
+
const inflight = new Map();
|
|
61
|
+
return async (request) => {
|
|
62
|
+
if (!request.deliveryId) throw Object.assign(new Error("Native delivery requires a stable delivery ID; use the updated daemon"), { code: "native_not_ready" });
|
|
63
|
+
const deliveryId = String(request.deliveryId);
|
|
64
|
+
const digest = crypto.createHash("sha256").update(request.command).digest("hex");
|
|
65
|
+
if (inflight.has(deliveryId)) {
|
|
66
|
+
const previous = inflight.get(deliveryId);
|
|
67
|
+
if (previous.digest !== digest) throw Object.assign(new Error("Delivery ID was reused for different content"), { code: "native_not_ready" });
|
|
68
|
+
return previous.operation;
|
|
69
|
+
}
|
|
70
|
+
const id = submissionId(deliveryId);
|
|
71
|
+
const file = receiptFile(projectRoot, subscriber, id);
|
|
72
|
+
const cached = withFileLock(file, () => {
|
|
73
|
+
const receipt = readNativeReceipt(projectRoot, subscriber, deliveryId);
|
|
74
|
+
if (receipt && receipt.digest !== digest) throw Object.assign(new Error("Delivery ID was reused for different content"), { code: "native_not_ready" });
|
|
75
|
+
if (receipt?.state === "accepted") return receipt.result;
|
|
76
|
+
if (receipt && receipt.state !== "retry_allowed") throw Object.assign(new Error(`Delivery outcome is unknown; inspect ufoo bus deliveries ${subscriber}`), { code: "native_outcome_unknown" });
|
|
77
|
+
writeReceipt(file, { ...receipt, id, delivery_id: deliveryId, digest, state: "inflight", owner_pid: process.pid,
|
|
78
|
+
retry_authorized: receipt?.state === "retry_allowed", attempt: (receipt?.attempt || 0) + 1 });
|
|
79
|
+
return null;
|
|
80
|
+
});
|
|
81
|
+
if (cached) return cached;
|
|
82
|
+
const operation = (async () => {
|
|
83
|
+
try {
|
|
84
|
+
const result = await send({ ...request, deliveryId, retryAuthorized: readNativeReceipt(projectRoot, subscriber, deliveryId)?.retry_authorized === true });
|
|
85
|
+
withFileLock(file, () => writeReceipt(file, { ...readNativeReceipt(projectRoot, subscriber, deliveryId), id, delivery_id: deliveryId, digest, state: "accepted", result }));
|
|
86
|
+
return result;
|
|
87
|
+
} catch (error) {
|
|
88
|
+
withFileLock(file, () => {
|
|
89
|
+
if (error.remoteRejected || error.code === "native_not_ready") fs.rmSync(file, { force: true });
|
|
90
|
+
else writeReceipt(file, { ...readNativeReceipt(projectRoot, subscriber, deliveryId), id, delivery_id: deliveryId, digest, state: "unknown", error: error.message });
|
|
91
|
+
});
|
|
92
|
+
throw error;
|
|
93
|
+
} finally { inflight.delete(deliveryId); }
|
|
94
|
+
})();
|
|
95
|
+
inflight.set(deliveryId, { digest, operation });
|
|
96
|
+
return operation;
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
module.exports = { submissionId, readNativeReceipt, listNativeReceipts, resolveNativeReceipt, withNativeReceipts };
|
|
@@ -3,7 +3,6 @@ const path = require("path");
|
|
|
3
3
|
const {
|
|
4
4
|
subscriberToSafeName,
|
|
5
5
|
ensureDir,
|
|
6
|
-
truncateFile,
|
|
7
6
|
} = require("./utils");
|
|
8
7
|
const {
|
|
9
8
|
DeliveryQueue,
|
|
@@ -116,8 +115,7 @@ class QueueManager {
|
|
|
116
115
|
* 清空待处理消息
|
|
117
116
|
*/
|
|
118
117
|
async clearPending(subscriber) {
|
|
119
|
-
|
|
120
|
-
truncateFile(pendingPath);
|
|
118
|
+
this.getDeliveryQueue(subscriber).writePending([]);
|
|
121
119
|
}
|
|
122
120
|
|
|
123
121
|
/**
|
|
@@ -184,12 +184,16 @@ function appendFileAtomic(filePath, content) {
|
|
|
184
184
|
/**
|
|
185
185
|
* 原子性地写入文件
|
|
186
186
|
*/
|
|
187
|
-
function writeFileAtomic(filePath, content) {
|
|
187
|
+
function writeFileAtomic(filePath, content, options = {}) {
|
|
188
188
|
ensureDir(path.dirname(filePath));
|
|
189
189
|
// Include pid + random suffix to avoid collisions across concurrent writers in the same millisecond.
|
|
190
190
|
const tmpFile = `${filePath}.tmp.${process.pid}.${Date.now()}.${crypto.randomBytes(4).toString("hex")}`;
|
|
191
|
-
|
|
192
|
-
|
|
191
|
+
try {
|
|
192
|
+
fs.writeFileSync(tmpFile, content, { encoding: "utf8", ...options });
|
|
193
|
+
fs.renameSync(tmpFile, filePath);
|
|
194
|
+
} finally {
|
|
195
|
+
fs.rmSync(tmpFile, { force: true });
|
|
196
|
+
}
|
|
193
197
|
}
|
|
194
198
|
|
|
195
199
|
/**
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const fs = require("fs");
|
|
4
|
+
const path = require("path");
|
|
5
|
+
const MessageManager = require("../bus/message");
|
|
6
|
+
const { getUfooPaths } = require("../state/paths");
|
|
7
|
+
const { redactSecrets } = require("../../runtime/privacy/redactor");
|
|
8
|
+
|
|
9
|
+
// Display events are observations, not messages. They never enter an agent's
|
|
10
|
+
// inbox and never depend on which peer receives the task's final reply.
|
|
11
|
+
function createAgentSurfacePublisher(projectRoot, subscriber) {
|
|
12
|
+
const paths = getUfooPaths(projectRoot);
|
|
13
|
+
const sequence = new MessageManager(paths.busDir, {}, null);
|
|
14
|
+
let pending = Promise.resolve();
|
|
15
|
+
let batch = [];
|
|
16
|
+
let timer = null;
|
|
17
|
+
let lastError = "";
|
|
18
|
+
function reportError(error) {
|
|
19
|
+
const message = redactSecrets(String(error?.message || "unknown display stream error"));
|
|
20
|
+
if (message !== lastError) process.stderr.write(`[internal] display stream unavailable: ${message}\n`);
|
|
21
|
+
lastError = message;
|
|
22
|
+
}
|
|
23
|
+
function drain() {
|
|
24
|
+
if (timer) clearTimeout(timer);
|
|
25
|
+
timer = null;
|
|
26
|
+
const events = batch;
|
|
27
|
+
batch = [];
|
|
28
|
+
for (const safeEvent of events) {
|
|
29
|
+
pending = pending.then(async () => {
|
|
30
|
+
fs.mkdirSync(paths.busEventsDir, { recursive: true });
|
|
31
|
+
const seq = await sequence.getNextSeq();
|
|
32
|
+
const timestamp = new Date().toISOString();
|
|
33
|
+
fs.appendFileSync(path.join(paths.busEventsDir, `${timestamp.slice(0, 10)}.jsonl`), JSON.stringify({
|
|
34
|
+
seq, timestamp, type: "status/agent-surface", event: "agent_surface",
|
|
35
|
+
publisher: subscriber, target: "*", data: { subscriber, surface: safeEvent },
|
|
36
|
+
}) + "\n");
|
|
37
|
+
lastError = "";
|
|
38
|
+
}).catch(reportError);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
function enqueue(event) {
|
|
42
|
+
let safeEvent;
|
|
43
|
+
try { safeEvent = JSON.parse(redactSecrets(JSON.stringify(event))); }
|
|
44
|
+
catch (error) { reportError(error); return; }
|
|
45
|
+
const last = batch.at(-1);
|
|
46
|
+
if (["text_delta", "thinking_delta"].includes(safeEvent.type) && last?.type === safeEvent.type
|
|
47
|
+
&& String(last.delta || "").length < 32000) last.delta = String(last.delta || "") + String(safeEvent.delta || "");
|
|
48
|
+
else batch.push(safeEvent);
|
|
49
|
+
if (!timer) { timer = setTimeout(drain, 40); timer.unref?.(); }
|
|
50
|
+
}
|
|
51
|
+
return { enqueue, flush: () => { drain(); return pending; } };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function readAgentSurfaceEvents(projectRoot, agentIds, maxBytes = 2 * 1024 * 1024) {
|
|
55
|
+
const accepted = new Set(agentIds);
|
|
56
|
+
const dir = getUfooPaths(projectRoot).busEventsDir;
|
|
57
|
+
let files;
|
|
58
|
+
try { files = fs.readdirSync(dir).filter((file) => file.endsWith(".jsonl")).sort().slice(-2); }
|
|
59
|
+
catch { return []; }
|
|
60
|
+
const events = [];
|
|
61
|
+
for (const file of files) {
|
|
62
|
+
let fd;
|
|
63
|
+
try {
|
|
64
|
+
fd = fs.openSync(path.join(dir, file), "r");
|
|
65
|
+
const size = fs.fstatSync(fd).size;
|
|
66
|
+
const start = Math.max(0, size - maxBytes);
|
|
67
|
+
const buffer = Buffer.alloc(Math.min(size, maxBytes));
|
|
68
|
+
fs.readSync(fd, buffer, 0, buffer.length, start);
|
|
69
|
+
const lines = buffer.toString("utf8").split("\n");
|
|
70
|
+
if (start) lines.shift();
|
|
71
|
+
for (const line of lines) {
|
|
72
|
+
try {
|
|
73
|
+
const event = JSON.parse(line);
|
|
74
|
+
if (event.event === "agent_surface" && accepted.has(event.publisher) && event.data?.surface?.type) events.push(event);
|
|
75
|
+
} catch { /* An incomplete tail is picked up by the live bridge. */ }
|
|
76
|
+
}
|
|
77
|
+
} catch { /* History can rotate while a pane attaches. */ }
|
|
78
|
+
finally { if (fd !== undefined) fs.closeSync(fd); }
|
|
79
|
+
}
|
|
80
|
+
return events.sort((a, b) => (a.seq || 0) - (b.seq || 0));
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// Keep partial rows as bytes: a provider can append in the middle of a UTF-8
|
|
84
|
+
// character. File offsets, rather than sequence high-water marks, retain late
|
|
85
|
+
// appends from concurrent writers.
|
|
86
|
+
function createAgentSurfaceReader(projectRoot, maxBytes = 2 * 1024 * 1024) {
|
|
87
|
+
const cursors = new Map();
|
|
88
|
+
const dir = getUfooPaths(projectRoot).busEventsDir;
|
|
89
|
+
return {
|
|
90
|
+
read(agentIds) {
|
|
91
|
+
const accepted = new Set(agentIds);
|
|
92
|
+
let files;
|
|
93
|
+
try { files = fs.readdirSync(dir).filter((name) => name.endsWith(".jsonl")).sort().slice(-2); }
|
|
94
|
+
catch { return []; }
|
|
95
|
+
const events = [];
|
|
96
|
+
for (const name of files) {
|
|
97
|
+
let fd;
|
|
98
|
+
try {
|
|
99
|
+
fd = fs.openSync(path.join(dir, name), "r");
|
|
100
|
+
const stat = fs.fstatSync(fd);
|
|
101
|
+
let cursor = cursors.get(name);
|
|
102
|
+
if (!cursor || cursor.ino !== stat.ino || stat.size < cursor.offset) {
|
|
103
|
+
cursor = { ino: stat.ino, offset: Math.max(0, stat.size - maxBytes), partial: Buffer.alloc(0) };
|
|
104
|
+
cursor.skipFirst = cursor.offset > 0;
|
|
105
|
+
}
|
|
106
|
+
if (stat.size - cursor.offset > maxBytes) {
|
|
107
|
+
cursor.offset = stat.size - maxBytes;
|
|
108
|
+
cursor.partial = Buffer.alloc(0);
|
|
109
|
+
cursor.skipFirst = true;
|
|
110
|
+
}
|
|
111
|
+
const buffer = Buffer.alloc(Math.max(0, stat.size - cursor.offset));
|
|
112
|
+
const read = fs.readSync(fd, buffer, 0, buffer.length, cursor.offset);
|
|
113
|
+
cursor.offset += read;
|
|
114
|
+
const content = Buffer.concat([cursor.partial, buffer.subarray(0, read)]);
|
|
115
|
+
const end = content.lastIndexOf(10);
|
|
116
|
+
const skipFirst = cursor.skipFirst;
|
|
117
|
+
if (end >= 0) cursor.skipFirst = false;
|
|
118
|
+
cursor.partial = content.subarray(end + 1);
|
|
119
|
+
if (cursor.partial.length > maxBytes) {
|
|
120
|
+
cursor.partial = cursor.partial.subarray(-maxBytes);
|
|
121
|
+
cursor.skipFirst = true;
|
|
122
|
+
}
|
|
123
|
+
cursors.set(name, cursor);
|
|
124
|
+
if (end < 0) continue;
|
|
125
|
+
const lines = content.subarray(0, end).toString("utf8").split("\n");
|
|
126
|
+
if (skipFirst) lines.shift();
|
|
127
|
+
for (const line of lines) {
|
|
128
|
+
try {
|
|
129
|
+
const event = JSON.parse(line);
|
|
130
|
+
if (event.event === "agent_surface" && accepted.has(event.publisher) && event.data?.surface?.type) events.push(event);
|
|
131
|
+
} catch { /* Ignore unrelated or malformed observations. */ }
|
|
132
|
+
}
|
|
133
|
+
} catch { /* A writer can rotate the file between stat and read. */ }
|
|
134
|
+
finally { if (fd !== undefined) fs.closeSync(fd); }
|
|
135
|
+
}
|
|
136
|
+
for (const name of cursors.keys()) if (!files.includes(name)) cursors.delete(name);
|
|
137
|
+
return events;
|
|
138
|
+
},
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
module.exports = { createAgentSurfacePublisher, readAgentSurfaceEvents, createAgentSurfaceReader };
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
const fs = require("fs");
|
|
3
|
+
const path = require("path");
|
|
4
|
+
|
|
5
|
+
/** Legacy output is evidence, never a fabricated native tool transcript. */
|
|
6
|
+
function readControllerSummary(projectRoot) {
|
|
7
|
+
const file = path.join(projectRoot, ".ufoo", "agent", "ufoo-agent.history.jsonl");
|
|
8
|
+
let fd;
|
|
9
|
+
try {
|
|
10
|
+
fd = fs.openSync(file, "r");
|
|
11
|
+
const size = fs.fstatSync(fd).size;
|
|
12
|
+
const length = Math.min(size, 65536);
|
|
13
|
+
const buffer = Buffer.alloc(length); fs.readSync(fd, buffer, 0, length, size - length);
|
|
14
|
+
const lines = buffer.toString("utf8").split("\n");
|
|
15
|
+
if (size > length) lines.shift();
|
|
16
|
+
return { source: "legacy-controller-history", trust: "untrusted", entries: lines.filter(Boolean).slice(-6).flatMap((line) => {
|
|
17
|
+
try { const item = JSON.parse(line); return [{ prompt: String(item.prompt || "").slice(0, 2000), reply: String(item.reply || "").slice(0, 4000) }]; }
|
|
18
|
+
catch { return []; }
|
|
19
|
+
}) };
|
|
20
|
+
} catch (error) { return { source: "legacy-controller-history", entries: [], error: error.code === "ENOENT" ? "" : "unreadable" }; }
|
|
21
|
+
finally { if (fd !== undefined) fs.closeSync(fd); }
|
|
22
|
+
}
|
|
23
|
+
module.exports = { readControllerSummary };
|