u-foo 3.1.7 → 4.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/OBSERVABILITY.md +65 -0
- package/README.md +238 -21
- package/README.zh-CN.md +165 -20
- package/SKILLS/ufoo/SKILL.md +40 -4
- package/SKILLS/ufoo-bus/SKILL.md +46 -3
- package/bin/uclaude.js +4 -0
- package/bin/ucodex.js +4 -0
- package/bin/ufoo.js +6 -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 +14 -7
- 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/activityDetector.js +1 -1
- package/src/agents/activity/activityStateWriter.js +37 -38
- package/src/agents/capabilities/agentManagement/index.js +4 -0
- package/src/agents/capabilities/agentManagement/service.js +140 -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 +40 -22
- package/src/agents/controller/index.js +1 -6
- package/src/agents/internal/internalRunner.js +181 -76
- package/src/agents/launch/index.js +0 -1
- package/src/agents/launch/launcher.js +96 -14
- package/src/agents/launch/nativeCapabilities.js +40 -0
- package/src/agents/launch/nativeMessages.js +362 -0
- package/src/agents/launch/notifier.js +15 -20
- package/src/agents/launch/readyDetector.js +28 -14
- 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/cooperation.js +14 -0
- package/src/agents/prompts/defaultBootstrap.js +1 -1
- package/src/agents/prompts/groupBootstrap.js +32 -6
- package/src/agents/prompts/mainAgent.js +48 -0
- package/src/agents/prompts/native/system.js +4 -1
- package/src/agents/prompts/native/tasks.js +2 -2
- package/src/agents/prompts/native/ufoo.js +14 -3
- package/src/agents/prompts/promptProfiles.js +2 -0
- package/src/agents/prompts/reporting.js +16 -0
- package/src/agents/providers/claudeEventTranslator.js +9 -1
- package/src/agents/providers/claudeThreadProvider.js +47 -4
- package/src/agents/providers/clientIdentity.js +75 -0
- package/src/agents/providers/codexEventTranslator.js +68 -7
- package/src/agents/providers/codexThreadProvider.js +18 -8
- package/src/agents/providers/credentials/claude.js +10 -3
- package/src/agents/providers/credentials/index.js +2 -0
- package/src/agents/providers/directAuthStatus.js +1 -1
- package/src/agents/providers/index.js +1 -1
- package/src/agents/providers/modelSettings.js +34 -0
- package/src/agents/providers/modelsCatalog.js +379 -0
- package/src/agents/providers/nativeTransport.js +1146 -0
- package/src/agents/providers/runtimeConfig.js +188 -0
- package/src/agents/providers/thinkingLevels.js +106 -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 +504 -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/upstreamRuntime.js +135 -0
- package/src/agents/runtime/composeCapabilities.js +89 -0
- package/src/agents/runtime/context/checkpointStore.js +38 -0
- package/src/agents/runtime/context/commandStore.js +43 -0
- package/src/agents/runtime/context/compaction.js +151 -0
- package/src/agents/runtime/context/contextBudget.js +93 -0
- package/src/agents/runtime/context/contextWindow.js +119 -0
- package/src/agents/runtime/context/fileLock.js +36 -0
- package/src/agents/runtime/context/replayHistory.js +28 -0
- package/src/agents/runtime/context/runtimeStore.js +127 -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 +351 -0
- package/src/agents/runtime/core/executionBudget.js +36 -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 +259 -0
- package/src/agents/runtime/index.js +14 -0
- package/src/agents/runtime/prompts/responseLanguage.js +12 -0
- package/src/agents/runtime/protocol/faultHarness.js +90 -0
- package/src/agents/runtime/protocol/materialize.js +107 -0
- package/src/agents/runtime/protocol/runObservation.js +24 -0
- package/src/agents/runtime/protocol/toolCallLedger.js +221 -0
- package/src/agents/runtime/protocol/traceContext.js +9 -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 +29 -45
- package/src/app/chat/agentDirectory.js +9 -18
- package/src/app/chat/bootstrap.js +1 -2
- package/src/app/chat/commandExecutor.js +111 -313
- package/src/app/chat/commands.js +39 -45
- package/src/app/chat/daemonConnection.js +58 -5
- package/src/app/chat/daemonMessageRouter.js +61 -48
- package/src/app/chat/historyStore.js +12 -48
- package/src/app/chat/inputSubmitHandler.js +21 -35
- package/src/app/chat/internalAgentLogHistory.js +19 -60
- package/src/app/chat/launchRequestContext.js +42 -0
- package/src/app/chat/multiWindow/paneManager.js +91 -164
- package/src/app/chat/streamState.js +3 -7
- 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/init.js +5 -5
- package/src/app/cli/features/skills.js +16 -4
- package/src/app/cli/metricsCommands.js +68 -0
- package/src/app/cli/reportCoreCommands.js +37 -0
- package/src/app/cli/run.js +82 -42
- package/src/app/cli/traceCommands.js +36 -0
- package/src/code/agent.js +34 -17
- package/src/code/busConsumer.js +1 -3
- package/src/code/commands.js +1 -1
- package/src/code/context/artifacts.js +12 -11
- package/src/code/context/assembler.js +9 -9
- package/src/code/context/promptLayers.js +1 -13
- package/src/code/context/stableJson.js +2 -27
- package/src/code/context/stateCommit.js +2 -1
- package/src/code/contextWindow.js +2 -117
- package/src/code/conversation/sessionJournal.js +3 -349
- package/src/code/internalThread.js +107 -0
- package/src/code/launcher/ucode.js +1 -1
- package/src/code/launcher/ucodeBootstrap.js +1 -1
- package/src/code/modelCommand.js +11 -35
- package/src/code/nativeRunner.js +104 -2697
- 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/modelsCatalog.js +1 -317
- 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/repl.js +2 -11
- package/src/code/sessionStore.js +27 -99
- package/src/code/taskDecomposer.js +18 -0
- package/src/code/thinkingLevels.js +1 -130
- package/src/code/toolBudget.js +1 -17
- 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 +95 -131
- package/src/coordination/bus/deliveryQueue.js +16 -2
- package/src/coordination/bus/index.js +14 -9
- package/src/coordination/bus/inject.js +15 -7
- package/src/coordination/bus/message.js +15 -1
- package/src/coordination/bus/nativeReceipts.js +100 -0
- package/src/coordination/bus/nickname.js +1 -1
- package/src/coordination/bus/queue.js +1 -3
- package/src/coordination/bus/subscriber.js +3 -2
- package/src/coordination/bus/utils.js +8 -4
- package/src/coordination/history/agentPerformance.js +279 -0
- package/src/coordination/history/agentSurface.js +142 -0
- package/src/coordination/history/agentTrace.js +249 -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/orchestration/controller/index.js +1 -8
- package/src/orchestration/controller/launchRouting.js +1 -1
- package/src/orchestration/solo/commands.js +3 -1
- package/src/runtime/contracts/agentMode.js +26 -0
- package/src/runtime/contracts/eventContract.js +3 -0
- package/src/runtime/contracts/uiProtocol.js +20 -17
- package/src/runtime/daemon/agentHost.js +407 -0
- package/src/runtime/daemon/agentRecoveryGroups.js +70 -0
- package/src/runtime/daemon/busBridge.js +396 -0
- package/src/runtime/daemon/claudeChannel.js +159 -0
- package/src/runtime/daemon/controlPlaneService.js +28 -18
- package/src/runtime/daemon/cronOps.js +25 -17
- package/src/runtime/daemon/deliveryScheduler.js +32 -5
- package/src/runtime/daemon/globalDaemon.js +28 -1
- package/src/runtime/daemon/groupOrchestrator.js +21 -5
- package/src/runtime/daemon/groupStatus.js +20 -0
- package/src/runtime/daemon/index.js +120 -375
- 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 +8 -5
- package/src/runtime/daemon/mcpStdioProxy.js +127 -10
- package/src/runtime/daemon/nicknameScope.js +1 -1
- package/src/runtime/daemon/ops.js +68 -40
- package/src/runtime/daemon/projectRuntimeGateway.js +2 -0
- package/src/runtime/daemon/promptRequest.js +92 -570
- package/src/runtime/daemon/providerSessions.js +67 -33
- package/src/runtime/daemon/reportControlBus.js +59 -25
- package/src/runtime/daemon/status.js +9 -6
- 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 +28 -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/handlers/tier2.js +4 -2
- package/src/tools/index.js +1 -0
- package/src/tools/registry.js +6 -0
- package/src/tools/schemaFixtures.js +42 -5
- package/src/tools/tier0/readAgentMetrics.js +14 -0
- package/src/tools/tier0/readAgentTrace.js +12 -0
- 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/agentSettingsController.js +107 -0
- package/src/ui/agentSurface.js +270 -0
- package/src/ui/dashboardBridge.js +1 -1
- package/src/ui/format/banner.js +9 -15
- package/src/ui/format/index.js +14 -10
- package/src/ui/format/loopSummary.js +50 -0
- package/src/ui/format/markdownRenderer.js +3 -4
- package/src/ui/format/startupBanner.js +50 -0
- package/src/ui/multiPaneBusMirror.js +29 -3
- package/src/ui/rustChatHost.js +316 -599
- package/src/ui/rustMultiSession.js +288 -73
- package/src/ui/rustUcodeHost.js +21 -88
- package/src/ui/settingsBridge.js +34 -14
- package/src/ui/toolMergeBridge.js +0 -4
- package/src/ui/uiHostServer.js +5 -8
- package/src/agents/controller/loopObservability.js +0 -200
- package/src/agents/controller/loopRuntime.js +0 -472
- package/src/agents/controller/ufooAgent.js +0 -829
- package/src/agents/launch/ptyRunner.js +0 -1135
- package/src/agents/providers/upstreamTransport.js +0 -689
- package/src/app/chat/agentBar.js +0 -135
- package/src/app/chat/agentEnter.js +0 -70
- package/src/app/chat/agentSockets.js +0 -225
- package/src/app/chat/dashboardView.js +0 -405
- 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/app/chat/rawKeyMap.js +0 -42
- package/src/app/chat/settingsController.js +0 -111
- package/src/orchestration/controller/flags.js +0 -167
- package/src/orchestration/controller/gateRouter.js +0 -211
- package/src/orchestration/controller/routerFastPath.js +0 -22
- package/src/orchestration/controller/routerFinalize.js +0 -222
- package/src/orchestration/controller/shadowGuard.js +0 -280
- package/src/runtime/daemon/promptLoop.js +0 -136
- package/src/runtime/privacy/shadowDiff.js +0 -174
- package/src/ui/multiWindowHandoff.js +0 -232
- package/src/ui/ptyHandoff.js +0 -23
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const { composeCapabilities } = require("./composeCapabilities");
|
|
4
|
+
const { runAgentLoop } = require("./core/agentLoop");
|
|
5
|
+
const { assertTransport } = require("../providers/transports/transportContract");
|
|
6
|
+
const { randomUUID, createHash } = require("crypto");
|
|
7
|
+
const { createCommandStore } = require("./context/commandStore");
|
|
8
|
+
const { stableStringify } = require("./core/stableJson");
|
|
9
|
+
|
|
10
|
+
const terminal = new Set(["completed", "failed", "cancelled", "interrupted", "waiting_user"]);
|
|
11
|
+
const pidAlive = (pid) => { try { process.kill(pid, 0); return true; } catch (error) { return error.code !== "ESRCH"; } };
|
|
12
|
+
|
|
13
|
+
function terminalResult(result) {
|
|
14
|
+
if (!Array.isArray(result?.messages) || !Number.isInteger(result.historyOffset)) return result;
|
|
15
|
+
// Persist this invocation once, rather than repeating all preceding turns.
|
|
16
|
+
// Paused invocations retain their full input separately for tool resume.
|
|
17
|
+
return { ...result, messages: result.messages.filter(message => message.role !== "system").slice(result.historyOffset), historyOffset: 0 };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** A host injects persistence and preparation; core owns accepted invocation lifecycle. */
|
|
21
|
+
function createAgentRuntime({ profile, transport, capabilities, host = {}, defaults = {} } = {}) {
|
|
22
|
+
assertTransport(transport);
|
|
23
|
+
const composition = composeCapabilities({ profile, capabilities, host, providerFeatures: transport.features || [] });
|
|
24
|
+
let running = false;
|
|
25
|
+
let closed = false;
|
|
26
|
+
let pumpPromise = null;
|
|
27
|
+
let controller = null;
|
|
28
|
+
let activeTask = "";
|
|
29
|
+
let activeRun = null;
|
|
30
|
+
let runController = null;
|
|
31
|
+
let closePromise = null;
|
|
32
|
+
const ownerId = randomUUID();
|
|
33
|
+
const waiters = new Map();
|
|
34
|
+
const storage = host.sessionStore;
|
|
35
|
+
const store = storage && Object.freeze({ ...storage,
|
|
36
|
+
transaction(mutator) {
|
|
37
|
+
return storage.transaction((state) => {
|
|
38
|
+
const additions = mutator(state) || [];
|
|
39
|
+
const events = [];
|
|
40
|
+
for (const event of additions) {
|
|
41
|
+
events.push(event);
|
|
42
|
+
for (const update of composition.reduceState(state.capabilityState, event)) {
|
|
43
|
+
events.push({ type: "capability.state_committed", ...update });
|
|
44
|
+
state.capabilityState[update.capabilityId] = { version: update.version, value: update.value };
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return events;
|
|
48
|
+
});
|
|
49
|
+
},
|
|
50
|
+
append(event) { return this.transaction(() => [event]); },
|
|
51
|
+
});
|
|
52
|
+
const commandStore = store && createCommandStore(store);
|
|
53
|
+
const requireStore = () => { if (!store) throw new Error("durable runtime requires host.sessionStore"); };
|
|
54
|
+
const notify = () => {
|
|
55
|
+
if (!store) return;
|
|
56
|
+
const state = store.read();
|
|
57
|
+
for (const [id, listeners] of waiters) {
|
|
58
|
+
const task = state.tasks[id];
|
|
59
|
+
if (task && terminal.has(task.status)) { listeners.forEach((resolve) => resolve(task)); waiters.delete(id); }
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
if (store) store.transaction((state) => {
|
|
63
|
+
if (state.profile && state.profile !== (profile && profile.id || "custom")) throw new Error("session profile is pinned; use a new session or explicit checkpoint migration");
|
|
64
|
+
if (state.owner && pidAlive(state.owner.pid)) throw Object.assign(new Error("runtime session already owned"), { code: "runtime_busy" });
|
|
65
|
+
const selectedCapabilities = composition.capabilities.map((capability) => capability.id);
|
|
66
|
+
if (state.capabilities && stableStringify(state.capabilities) !== stableStringify(selectedCapabilities)
|
|
67
|
+
&& Object.values(state.tasks).some((task) => ["queued", "running", "waiting_user"].includes(task.status))) throw new Error("cannot change capabilities with unfinished state; use a new session or explicit migration");
|
|
68
|
+
return [...Object.values(state.tasks).filter((task) => task.status === "running").map((task) => ({
|
|
69
|
+
type: "task.interrupted", taskRunId: task.taskRunId, error: "owner stopped; inspect effects before resubmitting",
|
|
70
|
+
})), { type: "runtime.opened", owner: { id: ownerId, pid: process.pid, profile: profile && profile.id || "custom", capabilities: selectedCapabilities } }];
|
|
71
|
+
});
|
|
72
|
+
const record = async (event) => {
|
|
73
|
+
const before = store.read();
|
|
74
|
+
const task = before.tasks[event.taskRunId];
|
|
75
|
+
event = { version: 1, projectId: host.projectId || "", agentId: host.agentId || "", sessionId: before.sessionId,
|
|
76
|
+
requestId: task?.request.requestId || "", taskId: task?.request.taskId || event.taskRunId || "", attemptId: task?.attemptId || "",
|
|
77
|
+
traceId: task?.request.traceId || task?.request.taskId || event.taskRunId || "",
|
|
78
|
+
parentTaskRunId: task?.request.parentTaskRunId || "", parentSessionId: task?.request.parentSessionId || "", ...event };
|
|
79
|
+
let sequence;
|
|
80
|
+
const snapshot = store.transaction((state) => { sequence = state.sequence + 1; return [event]; });
|
|
81
|
+
const committed = store.events({ after: sequence - 1 }).find((entry) => entry.sequence === sequence);
|
|
82
|
+
notify();
|
|
83
|
+
if (host.eventSink) {
|
|
84
|
+
try { await host.eventSink(committed); }
|
|
85
|
+
catch (error) { if (host.onObserverError) host.onObserverError(error); }
|
|
86
|
+
}
|
|
87
|
+
const proposals = await composition.handleEvent(committed);
|
|
88
|
+
for (let index = 0; index < proposals.length; index += 1) {
|
|
89
|
+
const command = proposals[index];
|
|
90
|
+
if (!host.commandExecutor) throw new Error("host.commandExecutor is required for capability commands");
|
|
91
|
+
if ((command.permissions || []).some((permission) => !(host.grantedPermissions || []).includes(permission))) throw new Error("capability command exceeds host permissions");
|
|
92
|
+
const commandId = `event-${createHash("sha256").update(`${sequence}:${command.capabilityId}:${index}`).digest("hex").slice(0, 32)}`;
|
|
93
|
+
await commandStore.execute({ commandId, kind: command.name, args: command.args }, () => host.commandExecutor(command));
|
|
94
|
+
}
|
|
95
|
+
return snapshot;
|
|
96
|
+
};
|
|
97
|
+
async function pump() {
|
|
98
|
+
while (!closed) {
|
|
99
|
+
const task = Object.values(store.read().tasks).filter((item) => item.status === "queued").sort((a, b) => a.sequence - b.sequence)[0];
|
|
100
|
+
if (!task) return;
|
|
101
|
+
activeTask = task.taskRunId;
|
|
102
|
+
controller = new AbortController();
|
|
103
|
+
const attemptId = `attempt_${randomUUID()}`;
|
|
104
|
+
try {
|
|
105
|
+
const execute = async (signal) => {
|
|
106
|
+
await record({ type: "task.started", taskRunId: activeTask, attemptId });
|
|
107
|
+
const prepared = task.answer !== undefined && task.result && host.resumeRequest
|
|
108
|
+
? await host.resumeRequest(task, task.answer)
|
|
109
|
+
: host.prepareRequest ? await host.prepareRequest(task.request, task) : { prompt: task.request.text };
|
|
110
|
+
return runtime.run({ ...prepared, requestId: task.request.requestId,
|
|
111
|
+
taskId: task.request.taskId || task.taskRunId, taskRunId: task.taskRunId, attemptId,
|
|
112
|
+
traceId: task.request.traceId || task.request.taskId || task.taskRunId,
|
|
113
|
+
parentTaskRunId: task.request.parentTaskRunId || "", parentSessionId: task.request.parentSessionId || "",
|
|
114
|
+
signal, onEvent: record });
|
|
115
|
+
};
|
|
116
|
+
const result = host.taskScheduler
|
|
117
|
+
? await host.taskScheduler.schedule({ id: task.taskRunId, resourceKey: task.request.resourceKey || "", signal: controller.signal }, execute)
|
|
118
|
+
: await execute(controller.signal);
|
|
119
|
+
if (controller.signal.aborted) throw Object.assign(new Error("agent cancelled"), { code: "cancelled" });
|
|
120
|
+
if (result.error || result.stopReason) throw Object.assign(new Error(result.error || `agent stopped: ${result.stopReason}`), { code: result.stopReason || "runtime_error", result });
|
|
121
|
+
await record({ type: result.waitingUserInteraction ? "task.paused" : "task.completed", taskRunId: activeTask,
|
|
122
|
+
result: result.waitingUserInteraction ? result : terminalResult(result) });
|
|
123
|
+
} catch (error) {
|
|
124
|
+
if (store.read().tasks[activeTask]?.status === "completed") {
|
|
125
|
+
if (host.onError) host.onError(error);
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
await record({ type: controller.signal.aborted || error.code === "cancelled" ? "task.cancelled" : "task.failed",
|
|
129
|
+
taskRunId: activeTask, error: error.message, code: error.code || "runtime_error", ...(error.result ? { result: terminalResult(error.result) } : {}) });
|
|
130
|
+
} finally { activeTask = ""; controller = null; }
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
function startPump() {
|
|
134
|
+
if (pumpPromise || closed) return;
|
|
135
|
+
pumpPromise = Promise.resolve().then(pump).catch((error) => {
|
|
136
|
+
if (host.onError) host.onError(error);
|
|
137
|
+
}).finally(() => {
|
|
138
|
+
pumpPromise = null;
|
|
139
|
+
notify();
|
|
140
|
+
if (!closed && Object.values(store.read().tasks).some((task) => task.status === "queued")) startPump();
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
const runtime = Object.freeze({
|
|
144
|
+
tools: composition.tools,
|
|
145
|
+
capabilities: composition.capabilities,
|
|
146
|
+
buildContext: composition.buildContext,
|
|
147
|
+
promptSections: composition.promptSections,
|
|
148
|
+
async run(input = {}) {
|
|
149
|
+
if (closed) throw Object.assign(new Error("agent runtime is closed"), { code: "runtime_closed" });
|
|
150
|
+
if (running) throw Object.assign(new Error("agent runtime is already running"), { code: "runtime_busy" });
|
|
151
|
+
running = true;
|
|
152
|
+
runController = new AbortController();
|
|
153
|
+
const externalSignal = input.signal || defaults.signal;
|
|
154
|
+
const forwardAbort = () => runController && runController.abort(externalSignal.reason);
|
|
155
|
+
if (externalSignal) {
|
|
156
|
+
if (externalSignal.aborted) forwardAbort();
|
|
157
|
+
else externalSignal.addEventListener("abort", forwardAbort, { once: true });
|
|
158
|
+
}
|
|
159
|
+
try {
|
|
160
|
+
activeRun = runAgentLoop({
|
|
161
|
+
...defaults, ...input, transport,
|
|
162
|
+
tools: composition.tools, policies: composition.policies,
|
|
163
|
+
signal: runController.signal,
|
|
164
|
+
});
|
|
165
|
+
return await activeRun;
|
|
166
|
+
} finally {
|
|
167
|
+
running = false;
|
|
168
|
+
activeRun = null;
|
|
169
|
+
runController = null;
|
|
170
|
+
if (externalSignal) externalSignal.removeEventListener("abort", forwardAbort);
|
|
171
|
+
}
|
|
172
|
+
},
|
|
173
|
+
submit(input = {}) {
|
|
174
|
+
requireStore();
|
|
175
|
+
if (closed) throw new Error("agent runtime is closed");
|
|
176
|
+
if (!/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/.test(input.requestId || "")) throw new Error("requestId is required and must be a safe identifier");
|
|
177
|
+
if (typeof input.text !== "string" || !input.text.trim()) throw new Error("request text is required");
|
|
178
|
+
const request = JSON.parse(JSON.stringify(input));
|
|
179
|
+
if (Array.isArray(request.attachments) && !request.attachments.length) delete request.attachments;
|
|
180
|
+
if (request.requestMeta && !Object.keys(request.requestMeta).length) delete request.requestMeta;
|
|
181
|
+
const fingerprint = createHash("sha256").update(stableStringify(request)).digest("hex");
|
|
182
|
+
let id;
|
|
183
|
+
const state = store.transaction((current) => {
|
|
184
|
+
id = Object.prototype.hasOwnProperty.call(current.requests, request.requestId) ? current.requests[request.requestId] : "";
|
|
185
|
+
if (id) {
|
|
186
|
+
if (current.tasks[id].request.fingerprint !== fingerprint) throw Object.assign(new Error("requestId reused with different content"), { code: "request_conflict" });
|
|
187
|
+
return [];
|
|
188
|
+
}
|
|
189
|
+
if (Object.values(current.tasks).filter((task) => task.status === "queued").length >= (host.maxQueuedTasks || 128)) throw Object.assign(new Error("runtime queue is full"), { code: "queue_full" });
|
|
190
|
+
id = `task_${randomUUID()}`;
|
|
191
|
+
return [{ type: "request.accepted", taskRunId: id, request: { ...request, fingerprint } }];
|
|
192
|
+
});
|
|
193
|
+
startPump();
|
|
194
|
+
return { accepted: true, requestId: request.requestId, taskRunId: id, status: state.tasks[id].status, sequence: state.sequence };
|
|
195
|
+
},
|
|
196
|
+
async resume({ interactionId, answer } = {}) {
|
|
197
|
+
requireStore();
|
|
198
|
+
if (closed) throw new Error("agent runtime is closed");
|
|
199
|
+
if (typeof host.resumeRequest !== "function") throw new Error("host.resumeRequest is required for interactions");
|
|
200
|
+
const state = store.read();
|
|
201
|
+
const task = Object.values(state.tasks).find((item) => item.status === "waiting_user" && item.interactionId === interactionId);
|
|
202
|
+
if (!task) {
|
|
203
|
+
const previous = Object.values(state.tasks).find((item) => item.answeredInteractionId === interactionId);
|
|
204
|
+
if (previous && stableStringify(previous.answer) === stableStringify(answer)) return { accepted: true, taskRunId: previous.taskRunId, status: previous.status };
|
|
205
|
+
throw new Error("interaction is not pending or its answer conflicts");
|
|
206
|
+
}
|
|
207
|
+
if (host.validateAnswer) await host.validateAnswer(task, answer);
|
|
208
|
+
store.transaction((current) => {
|
|
209
|
+
if (current.tasks[task.taskRunId].status !== "waiting_user") throw new Error("interaction already answered");
|
|
210
|
+
return [{ type: "interaction.answered", taskRunId: task.taskRunId, interactionId, answer }];
|
|
211
|
+
});
|
|
212
|
+
startPump();
|
|
213
|
+
return { accepted: true, taskRunId: task.taskRunId };
|
|
214
|
+
},
|
|
215
|
+
cancel({ taskRunId, reason = "user_cancel" } = {}) {
|
|
216
|
+
requireStore();
|
|
217
|
+
const task = store.read().tasks[taskRunId];
|
|
218
|
+
if (!task) throw new Error("task not found");
|
|
219
|
+
if (terminal.has(task.status) && task.status !== "waiting_user") return { taskRunId, status: task.status };
|
|
220
|
+
if (activeTask === taskRunId && controller) {
|
|
221
|
+
store.append({ type: "task.cancel_requested", taskRunId, reason });
|
|
222
|
+
controller.abort(reason);
|
|
223
|
+
} else store.append({ type: "task.cancelled", taskRunId, error: reason });
|
|
224
|
+
notify();
|
|
225
|
+
return { taskRunId, status: activeTask === taskRunId ? "cancelling" : "cancelled" };
|
|
226
|
+
},
|
|
227
|
+
snapshot() { return store ? store.read() : { running, closed }; },
|
|
228
|
+
events(input) { requireStore(); return store.events(input); },
|
|
229
|
+
wait(taskRunId) {
|
|
230
|
+
requireStore();
|
|
231
|
+
const task = store.read().tasks[taskRunId];
|
|
232
|
+
if (!task) return Promise.reject(new Error("task not found"));
|
|
233
|
+
if (terminal.has(task.status)) return Promise.resolve(task);
|
|
234
|
+
return new Promise((resolve) => { const listeners = waiters.get(taskRunId) || []; listeners.push(resolve); waiters.set(taskRunId, listeners); });
|
|
235
|
+
},
|
|
236
|
+
async close() {
|
|
237
|
+
if (closePromise) return closePromise;
|
|
238
|
+
closed = true;
|
|
239
|
+
if (controller) controller.abort("runtime_closed");
|
|
240
|
+
if (runController) runController.abort("runtime_closed");
|
|
241
|
+
closePromise = (async () => {
|
|
242
|
+
if (activeRun) await activeRun.catch(() => {});
|
|
243
|
+
if (pumpPromise) await pumpPromise;
|
|
244
|
+
let disposalError;
|
|
245
|
+
for (const capability of composition.capabilities.slice().reverse()) if (capability.dispose) {
|
|
246
|
+
try { await capability.dispose(); } catch (error) { disposalError = disposalError || error; }
|
|
247
|
+
}
|
|
248
|
+
if (store) store.transaction((state) => state.owner && state.owner.id === ownerId ? [{ type: "runtime.closed" }] : []);
|
|
249
|
+
notify();
|
|
250
|
+
if (disposalError) throw disposalError;
|
|
251
|
+
})();
|
|
252
|
+
return closePromise;
|
|
253
|
+
},
|
|
254
|
+
});
|
|
255
|
+
if (store) startPump();
|
|
256
|
+
return runtime;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
module.exports = { createAgentRuntime };
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
module.exports = {
|
|
4
|
+
...require("./createAgentRuntime"),
|
|
5
|
+
...require("./composeCapabilities"),
|
|
6
|
+
...require("./tools/registry"),
|
|
7
|
+
...require("./core/agentLoop"),
|
|
8
|
+
...require("./context/sessionJournal"),
|
|
9
|
+
...require("./context/sessionStore"),
|
|
10
|
+
...require("./context/runtimeStore"),
|
|
11
|
+
...require("./context/commandStore"),
|
|
12
|
+
...require("./tasks/scheduler"),
|
|
13
|
+
...require("./tasks/resourceLease"),
|
|
14
|
+
};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const RESPONSE_LANGUAGE_GUIDANCE = [
|
|
4
|
+
"Response language:",
|
|
5
|
+
"- Use the same natural language as the user's prompt for the current task, unless the user explicitly requests another language. This applies to replies, acknowledgements, progress updates, report summaries, handoffs, and final answers.",
|
|
6
|
+
"- For delegated work, follow the original user's language or the response-language requirement passed by the parent. English system instructions, tool output, and bus protocol text do not change the response language.",
|
|
7
|
+
"- When delegating, preserve the user's language in the task text or explicitly pass the required response language to the worker.",
|
|
8
|
+
"- For brief or ambiguous continuations, keep the language established by the user's substantive request. For multilingual prompts, follow an explicit language preference or the primary language of the user's prose.",
|
|
9
|
+
"- Keep code, commands, paths, identifiers, quoted error text, and required protocol keys and enum values literal.",
|
|
10
|
+
].join("\n");
|
|
11
|
+
|
|
12
|
+
module.exports = { RESPONSE_LANGUAGE_GUIDANCE };
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Minimal fault-injection harness for crash/restart tests (Phase 0 skeleton).
|
|
5
|
+
*
|
|
6
|
+
* Usage:
|
|
7
|
+
* armFault("after_prepare_tool_calls");
|
|
8
|
+
* await withFaultPoint("after_prepare_tool_calls", async () => { ... });
|
|
9
|
+
*
|
|
10
|
+
* Armed points throw FaultInjectedError once (or until disarmed).
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const armed = new Map();
|
|
14
|
+
|
|
15
|
+
class FaultInjectedError extends Error {
|
|
16
|
+
constructor(point = "") {
|
|
17
|
+
super(`fault injected at ${point}`);
|
|
18
|
+
this.name = "FaultInjectedError";
|
|
19
|
+
this.code = "FAULT_INJECTED";
|
|
20
|
+
this.point = String(point || "");
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Known hook names reserved for native loop / resume (R4 expands coverage). */
|
|
25
|
+
const FAULT_POINTS = Object.freeze([
|
|
26
|
+
"after_prepare_tool_calls",
|
|
27
|
+
"before_tool_exec",
|
|
28
|
+
"after_tool_effect",
|
|
29
|
+
"before_result_commit",
|
|
30
|
+
"after_answer_commit",
|
|
31
|
+
"before_provider_resume",
|
|
32
|
+
"after_taskrun_acquire_lease",
|
|
33
|
+
"before_parent_node_sync",
|
|
34
|
+
]);
|
|
35
|
+
|
|
36
|
+
function armFault(point = "", { times = 1, error = null } = {}) {
|
|
37
|
+
const name = String(point || "").trim();
|
|
38
|
+
if (!name) throw new Error("fault point name required");
|
|
39
|
+
armed.set(name, {
|
|
40
|
+
remaining: Math.max(1, Math.floor(Number(times) || 1)),
|
|
41
|
+
error: error || null,
|
|
42
|
+
});
|
|
43
|
+
return name;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function disarmFault(point = "") {
|
|
47
|
+
const name = String(point || "").trim();
|
|
48
|
+
if (!name) {
|
|
49
|
+
armed.clear();
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
armed.delete(name);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function isFaultArmed(point = "") {
|
|
56
|
+
return armed.has(String(point || "").trim());
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function checkFaultPoint(point = "") {
|
|
60
|
+
const name = String(point || "").trim();
|
|
61
|
+
const entry = armed.get(name);
|
|
62
|
+
if (!entry) return;
|
|
63
|
+
entry.remaining -= 1;
|
|
64
|
+
if (entry.remaining <= 0) armed.delete(name);
|
|
65
|
+
if (entry.error) throw entry.error;
|
|
66
|
+
throw new FaultInjectedError(name);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Run fn; if point is armed, throw before invoking fn.
|
|
71
|
+
*/
|
|
72
|
+
async function withFaultPoint(point = "", fn) {
|
|
73
|
+
checkFaultPoint(point);
|
|
74
|
+
return typeof fn === "function" ? fn() : undefined;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function listArmedFaults() {
|
|
78
|
+
return Array.from(armed.keys());
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
module.exports = {
|
|
82
|
+
FAULT_POINTS,
|
|
83
|
+
FaultInjectedError,
|
|
84
|
+
armFault,
|
|
85
|
+
disarmFault,
|
|
86
|
+
isFaultArmed,
|
|
87
|
+
checkFaultPoint,
|
|
88
|
+
withFaultPoint,
|
|
89
|
+
listArmedFaults,
|
|
90
|
+
};
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Materialize Provider tool-result messages from a resolved ledger turn.
|
|
5
|
+
* Business branches must resolve on the ledger; they must not hand-write
|
|
6
|
+
* unpaired tool results.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
const { listCalls } = require("./toolCallLedger");
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Clip helper kept local so protocol does not depend on nativeRunner.
|
|
13
|
+
*/
|
|
14
|
+
function clipText(value = "", maxChars = 12000) {
|
|
15
|
+
const text = String(value == null ? "" : value);
|
|
16
|
+
if (text.length <= maxChars) return text;
|
|
17
|
+
return `${text.slice(0, maxChars)}\n...[truncated ${text.length - maxChars} chars]`;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function toJsonString(value) {
|
|
21
|
+
try {
|
|
22
|
+
return JSON.stringify(value);
|
|
23
|
+
} catch {
|
|
24
|
+
return String(value);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* @param {object} ledger
|
|
30
|
+
* @param {{
|
|
31
|
+
* transport: object,
|
|
32
|
+
* messages: object[],
|
|
33
|
+
* pendingById: Record<string, object>,
|
|
34
|
+
* }} opts
|
|
35
|
+
* @returns {{ appended: number, flushed: boolean }}
|
|
36
|
+
*/
|
|
37
|
+
function materializeResolvedToolResults(ledger, {
|
|
38
|
+
transport = null,
|
|
39
|
+
messages = [],
|
|
40
|
+
pendingById = {},
|
|
41
|
+
} = {}) {
|
|
42
|
+
if (!ledger || !transport || typeof transport.appendToolResult !== "function") {
|
|
43
|
+
return { appended: 0, flushed: false };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const collected = [];
|
|
47
|
+
let appended = 0;
|
|
48
|
+
for (const call of listCalls(ledger)) {
|
|
49
|
+
if (call.state !== "resolved") continue;
|
|
50
|
+
const pending = pendingById[call.callId];
|
|
51
|
+
if (!pending) continue;
|
|
52
|
+
transport.appendToolResult({
|
|
53
|
+
messages,
|
|
54
|
+
collected,
|
|
55
|
+
call: pending,
|
|
56
|
+
toolResult: call.resultPayload,
|
|
57
|
+
});
|
|
58
|
+
appended += 1;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
let flushed = false;
|
|
62
|
+
if (
|
|
63
|
+
collected.length > 0
|
|
64
|
+
&& typeof transport.flushToolResults === "function"
|
|
65
|
+
) {
|
|
66
|
+
transport.flushToolResults({ messages, collected });
|
|
67
|
+
flushed = true;
|
|
68
|
+
}
|
|
69
|
+
return { appended, flushed };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Append a single resume answer as a tool result (idempotent via ledger resolve).
|
|
74
|
+
*/
|
|
75
|
+
function materializeAnswerToolResult(messages = [], resume = null, answer = {}, {
|
|
76
|
+
clip = clipText,
|
|
77
|
+
} = {}) {
|
|
78
|
+
const call = resume && resume.call ? resume.call : null;
|
|
79
|
+
if (!call || !call.source) return { ok: false, error: "missing deferred tool call" };
|
|
80
|
+
const transportName = String(resume.transport || "openai-chat");
|
|
81
|
+
const content = clip(toJsonString(answer), 12000);
|
|
82
|
+
if (transportName === "anthropic-messages") {
|
|
83
|
+
messages.push({
|
|
84
|
+
role: "user",
|
|
85
|
+
content: [{
|
|
86
|
+
type: "tool_result",
|
|
87
|
+
tool_use_id: String(call.source.id || resume.toolCallId || ""),
|
|
88
|
+
content,
|
|
89
|
+
is_error: false,
|
|
90
|
+
}],
|
|
91
|
+
});
|
|
92
|
+
} else {
|
|
93
|
+
messages.push({
|
|
94
|
+
role: "tool",
|
|
95
|
+
tool_call_id: String(call.source.id || resume.toolCallId || ""),
|
|
96
|
+
content,
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
return { ok: true };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
module.exports = {
|
|
103
|
+
materializeResolvedToolResults,
|
|
104
|
+
materializeAnswerToolResult,
|
|
105
|
+
clipText,
|
|
106
|
+
toJsonString,
|
|
107
|
+
};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const { createHash } = require("crypto");
|
|
4
|
+
const { stableStringify } = require("../core/stableJson");
|
|
5
|
+
const { version } = require("../../../../package.json");
|
|
6
|
+
|
|
7
|
+
function observationFingerprint(value) {
|
|
8
|
+
return createHash("sha256").update(stableStringify(value) || "null").digest("hex");
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
// Configuration evidence only: no credentials, headers, URLs or prompt bodies.
|
|
12
|
+
function buildRunObservation({ provider = "", model = "", transport = "", thinkingLevel = "",
|
|
13
|
+
systemPrompt = "", systemBlocks = null, prompt = "", tools = [], resume = false, executionKind = "native", engineFingerprint = null, requestKind = "unknown" } = {}) {
|
|
14
|
+
const config = { version: 1, runtimeVersion: version, engineFingerprint, executionKind, provider, model, transport,
|
|
15
|
+
thinkingLevel, requestKind, resumed: Boolean(resume),
|
|
16
|
+
promptFingerprint: observationFingerprint(systemBlocks || systemPrompt),
|
|
17
|
+
inputFingerprint: prompt ? observationFingerprint(prompt) : null,
|
|
18
|
+
toolSchemaFingerprint: tools.length ? observationFingerprint(tools) : null,
|
|
19
|
+
toolCount: executionKind === "sdk" && !tools.length ? null : tools.length,
|
|
20
|
+
toolInventoryScope: executionKind === "sdk" ? "ufoo-exposed" : "runtime" };
|
|
21
|
+
return { ...config, configurationFingerprint: observationFingerprint({ ...config, inputFingerprint: undefined, resumed: undefined }) };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
module.exports = { buildRunObservation, observationFingerprint };
|