u-foo 3.1.7 → 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.
Files changed (193) hide show
  1. package/README.md +172 -13
  2. package/README.zh-CN.md +108 -13
  3. package/SKILLS/ufoo/SKILL.md +15 -3
  4. package/SKILLS/ufoo-bus/SKILL.md +21 -1
  5. package/bin/uclaude.js +4 -0
  6. package/bin/ucodex.js +4 -0
  7. package/bin/ufoo.js +3 -1
  8. package/dist/tui/darwin-arm64/ufoo-tui +0 -0
  9. package/dist/tui/darwin-x64/ufoo-tui +0 -0
  10. package/dist/tui/linux-arm64/ufoo-tui +0 -0
  11. package/dist/tui/linux-x64/ufoo-tui +0 -0
  12. package/package.json +10 -3
  13. package/scripts/postinstall-skills.js +53 -0
  14. package/scripts/postinstall.js +11 -16
  15. package/scripts/smoke-native-messages.js +214 -0
  16. package/src/agents/activity/activityStateWriter.js +37 -38
  17. package/src/agents/capabilities/agentManagement/index.js +4 -0
  18. package/src/agents/capabilities/agentManagement/service.js +113 -0
  19. package/src/agents/capabilities/agentRouting/index.js +4 -0
  20. package/src/agents/capabilities/coding/index.js +32 -0
  21. package/src/agents/capabilities/coordination/index.js +37 -0
  22. package/src/agents/capabilities/globalRouting/index.js +5 -0
  23. package/src/agents/capabilities/groups/index.js +3 -0
  24. package/src/agents/capabilities/index.js +25 -0
  25. package/src/agents/capabilities/planning/index.js +123 -0
  26. package/src/agents/capabilities/planning/main.js +28 -0
  27. package/src/agents/capabilities/projectDiscovery/index.js +3 -0
  28. package/src/agents/capabilities/scheduling/index.js +3 -0
  29. package/src/agents/capabilities/sharedMemory/index.js +4 -0
  30. package/src/agents/capabilities/skills/index.js +12 -0
  31. package/src/agents/capabilities/taskExecution/index.js +3 -0
  32. package/src/agents/capabilities/taskReports/index.js +6 -0
  33. package/src/agents/controller/controllerToolExecutor.js +6 -4
  34. package/src/agents/controller/loopRuntime.js +85 -221
  35. package/src/agents/controller/ufooAgent.js +1 -0
  36. package/src/agents/internal/internalRunner.js +103 -32
  37. package/src/agents/launch/launcher.js +88 -6
  38. package/src/agents/launch/nativeCapabilities.js +40 -0
  39. package/src/agents/launch/nativeMessages.js +362 -0
  40. package/src/agents/launch/notifier.js +13 -18
  41. package/src/agents/launch/readyDetector.js +26 -12
  42. package/src/agents/profiles/coding.js +6 -0
  43. package/src/agents/profiles/globalRouter.js +2 -0
  44. package/src/agents/profiles/main.js +5 -0
  45. package/src/agents/prompts/groupBootstrap.js +10 -0
  46. package/src/agents/prompts/mainAgent.js +39 -0
  47. package/src/agents/prompts/native/tasks.js +2 -2
  48. package/src/agents/prompts/native/ufoo.js +3 -0
  49. package/src/agents/providers/claudeEventTranslator.js +6 -1
  50. package/src/agents/providers/claudeThreadProvider.js +44 -2
  51. package/src/agents/providers/codexEventTranslator.js +47 -7
  52. package/src/agents/providers/codexThreadProvider.js +3 -2
  53. package/src/agents/providers/controllerJsonTransport.js +28 -0
  54. package/src/agents/providers/credentials/claude.js +10 -3
  55. package/src/agents/providers/nativeTransport.js +1135 -0
  56. package/src/agents/providers/runtimeConfig.js +186 -0
  57. package/src/agents/providers/thinkingLevels.js +132 -0
  58. package/src/agents/providers/transports/anthropicMessagesTransport.js +121 -0
  59. package/src/agents/providers/transports/index.js +10 -0
  60. package/src/agents/providers/transports/openaiChatTransport.js +117 -0
  61. package/src/agents/providers/transports/openaiResponsesTransport.js +120 -0
  62. package/src/agents/providers/transports/responsesProtocol.js +499 -0
  63. package/src/agents/providers/transports/systemBlocks.js +16 -0
  64. package/src/agents/providers/transports/transportContract.js +50 -0
  65. package/src/agents/providers/transports/visionBlocks.js +151 -0
  66. package/src/agents/providers/upstreamTransport.js +13 -4
  67. package/src/agents/runtime/composeCapabilities.js +89 -0
  68. package/src/agents/runtime/context/commandStore.js +43 -0
  69. package/src/agents/runtime/context/contextWindow.js +119 -0
  70. package/src/agents/runtime/context/fileLock.js +36 -0
  71. package/src/agents/runtime/context/runtimeStore.js +126 -0
  72. package/src/agents/runtime/context/sessionJournal.js +360 -0
  73. package/src/agents/runtime/context/sessionStore.js +57 -0
  74. package/src/agents/runtime/core/agentLoop.js +270 -0
  75. package/src/agents/runtime/core/stableJson.js +29 -0
  76. package/src/agents/runtime/core/toolLoopGuard.js +55 -0
  77. package/src/agents/runtime/createAgentRuntime.js +247 -0
  78. package/src/agents/runtime/index.js +14 -0
  79. package/src/agents/runtime/protocol/faultHarness.js +90 -0
  80. package/src/agents/runtime/protocol/materialize.js +107 -0
  81. package/src/agents/runtime/protocol/toolCallLedger.js +221 -0
  82. package/src/agents/runtime/tasks/resourceLease.js +66 -0
  83. package/src/agents/runtime/tasks/scheduler.js +73 -0
  84. package/src/agents/runtime/tools/registry.js +57 -0
  85. package/src/app/chat/ChatController.js +14 -3
  86. package/src/app/chat/agentDirectory.js +8 -2
  87. package/src/app/chat/commandExecutor.js +36 -46
  88. package/src/app/chat/commands.js +14 -7
  89. package/src/app/chat/daemonConnection.js +58 -5
  90. package/src/app/chat/daemonMessageRouter.js +61 -3
  91. package/src/app/chat/inputSubmitHandler.js +14 -2
  92. package/src/app/chat/launchRequestContext.js +42 -0
  93. package/src/app/chat/multiWindow/paneManager.js +85 -165
  94. package/src/app/chat/streamState.js +3 -3
  95. package/src/app/chat/transport.js +1 -1
  96. package/src/app/cli/busCoreCommands.js +9 -0
  97. package/src/app/cli/features/doctor.js +33 -0
  98. package/src/app/cli/features/skills.js +16 -4
  99. package/src/app/cli/reportCoreCommands.js +37 -0
  100. package/src/app/cli/run.js +40 -39
  101. package/src/code/agent.js +16 -4
  102. package/src/code/context/artifacts.js +12 -11
  103. package/src/code/context/assembler.js +2 -1
  104. package/src/code/context/promptLayers.js +1 -13
  105. package/src/code/context/stableJson.js +2 -27
  106. package/src/code/contextWindow.js +2 -117
  107. package/src/code/conversation/sessionJournal.js +3 -349
  108. package/src/code/internalThread.js +100 -0
  109. package/src/code/nativeRunner.js +36 -2667
  110. package/src/code/protocol/faultHarness.js +2 -88
  111. package/src/code/protocol/materialize.js +2 -105
  112. package/src/code/protocol/toolCallLedger.js +5 -215
  113. package/src/code/providers/anthropicMessagesTransport.js +2 -118
  114. package/src/code/providers/openaiChatTransport.js +2 -114
  115. package/src/code/providers/openaiResponsesTransport.js +2 -117
  116. package/src/code/providers/responsesProtocol.js +2 -497
  117. package/src/code/providers/transportContract.js +2 -48
  118. package/src/code/providers/visionBlocks.js +2 -149
  119. package/src/code/sessionStore.js +24 -96
  120. package/src/code/thinkingLevels.js +1 -130
  121. package/src/code/toolLoopGuard.js +3 -49
  122. package/src/code/tools/artifactRead.js +1 -1
  123. package/src/code/tools/executor.js +373 -0
  124. package/src/code/tools/specs.js +312 -0
  125. package/src/config.js +81 -67
  126. package/src/coordination/bus/deliveryQueue.js +16 -2
  127. package/src/coordination/bus/index.js +2 -6
  128. package/src/coordination/bus/inject.js +13 -5
  129. package/src/coordination/bus/nativeReceipts.js +100 -0
  130. package/src/coordination/bus/queue.js +1 -3
  131. package/src/coordination/bus/utils.js +7 -3
  132. package/src/coordination/history/agentSurface.js +142 -0
  133. package/src/coordination/history/controllerSummary.js +23 -0
  134. package/src/coordination/memory/index.js +5 -21
  135. package/src/coordination/report/store.js +103 -83
  136. package/src/coordination/state/agentsStore.js +57 -3
  137. package/src/coordination/state/fileLock.js +2 -0
  138. package/src/coordination/state/workspaceAccess.js +36 -0
  139. package/src/runtime/contracts/agentMode.js +17 -0
  140. package/src/runtime/contracts/eventContract.js +3 -0
  141. package/src/runtime/contracts/uiProtocol.js +4 -0
  142. package/src/runtime/daemon/agentHost.js +375 -0
  143. package/src/runtime/daemon/busBridge.js +396 -0
  144. package/src/runtime/daemon/claudeChannel.js +159 -0
  145. package/src/runtime/daemon/controlPlaneService.js +27 -17
  146. package/src/runtime/daemon/cronOps.js +25 -17
  147. package/src/runtime/daemon/deliveryScheduler.js +32 -5
  148. package/src/runtime/daemon/executionPaths.js +30 -0
  149. package/src/runtime/daemon/globalDaemon.js +28 -1
  150. package/src/runtime/daemon/groupOrchestrator.js +1 -0
  151. package/src/runtime/daemon/index.js +114 -344
  152. package/src/runtime/daemon/ipcServer.js +32 -10
  153. package/src/runtime/daemon/mcpConfigure.js +113 -20
  154. package/src/runtime/daemon/mcpHttpServer.js +27 -5
  155. package/src/runtime/daemon/mcpServer.js +7 -4
  156. package/src/runtime/daemon/mcpStdioProxy.js +127 -10
  157. package/src/runtime/daemon/ops.js +22 -17
  158. package/src/runtime/daemon/promptRequest.js +23 -4
  159. package/src/runtime/daemon/providerSessions.js +67 -33
  160. package/src/runtime/daemon/reportControlBus.js +59 -25
  161. package/src/runtime/daemon/status.js +4 -0
  162. package/src/runtime/privacy/redactor.js +2 -2
  163. package/src/runtime/projects/identity.js +2 -1
  164. package/src/runtime/projects/registry.js +98 -38
  165. package/src/tools/controllerSchemas.js +24 -0
  166. package/src/tools/handlers/dispatchMessage.js +5 -2
  167. package/src/tools/handlers/listAgents.js +3 -1
  168. package/src/tools/handlers/readBusSummary.js +3 -1
  169. package/src/tools/handlers/readProjectRegistry.js +29 -2
  170. package/src/tools/handlers/routeAgent.js +35 -0
  171. package/src/tools/index.js +1 -0
  172. package/src/tools/registry.js +2 -0
  173. package/src/tools/schemaFixtures.js +16 -3
  174. package/src/tools/tier1/routeAgent.js +2 -2
  175. package/src/tools/tier2/runtimeCoordination.js +38 -0
  176. package/src/tools/types.js +2 -0
  177. package/src/ui/agentPresentation.js +109 -0
  178. package/src/ui/agentSurface.js +270 -0
  179. package/src/ui/format/banner.js +8 -11
  180. package/src/ui/format/startupBanner.js +50 -0
  181. package/src/ui/multiPaneBusMirror.js +29 -3
  182. package/src/ui/rustChatHost.js +170 -438
  183. package/src/ui/rustMultiSession.js +225 -51
  184. package/src/ui/rustUcodeHost.js +20 -87
  185. package/src/ui/settingsBridge.js +7 -4
  186. package/src/app/chat/agentEnter.js +0 -70
  187. package/src/app/chat/multiWindow/index.js +0 -310
  188. package/src/app/chat/multiWindow/paneLayout.js +0 -84
  189. package/src/app/chat/multiWindow/renderer.js +0 -420
  190. package/src/app/chat/multiWindow/virtualTerminal.js +0 -327
  191. package/src/app/chat/multiWindow/vtFrame.js +0 -93
  192. package/src/ui/multiWindowHandoff.js +0 -232
  193. package/src/ui/ptyHandoff.js +0 -23
@@ -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,221 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * Tool Call Ledger — authoritative record of declared tool calls for a turn.
5
+ *
6
+ * Shadow mode (Phase 0 / R1): ledger tracks declare/defer/resolve alongside the
7
+ * existing TRANSPORTS message assembly. Materialize-from-ledger comes later.
8
+ *
9
+ * Call states: declared | executing | deferred | resolved
10
+ */
11
+
12
+ const { createHash, randomUUID } = require("crypto");
13
+
14
+ const CALL_STATES = Object.freeze(["declared", "executing", "deferred", "resolved"]);
15
+
16
+ function digestValue(value) {
17
+ const raw = typeof value === "string" ? value : stableStringify(value);
18
+ return createHash("sha256").update(raw).digest("hex").slice(0, 16);
19
+ }
20
+
21
+ function stableStringify(value) {
22
+ if (value == null) return "null";
23
+ if (typeof value !== "object") return JSON.stringify(value);
24
+ if (Array.isArray(value)) {
25
+ return `[${value.map((entry) => stableStringify(entry)).join(",")}]`;
26
+ }
27
+ const keys = Object.keys(value).sort();
28
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(",")}}`;
29
+ }
30
+
31
+ function createTurnId() {
32
+ return `turn_${Date.now().toString(36)}_${randomUUID().slice(0, 8)}`;
33
+ }
34
+
35
+ /**
36
+ * @param {{ provider?: string, sessionId?: string, turnId?: string, assistantMessageId?: string }} opts
37
+ */
38
+ function createToolCallLedger(opts = {}) {
39
+ return {
40
+ turnId: String(opts.turnId || createTurnId()),
41
+ provider: String(opts.provider || "").trim(),
42
+ sessionId: String(opts.sessionId || "").trim(),
43
+ assistantMessageId: String(opts.assistantMessageId || "").trim(),
44
+ calls: Object.create(null),
45
+ deferableTools: new Set(opts.deferableTools || []),
46
+ violations: [],
47
+ createdAt: new Date().toISOString(),
48
+ };
49
+ }
50
+
51
+ function getCall(ledger, callId) {
52
+ if (!ledger || !ledger.calls) return null;
53
+ const id = String(callId || "").trim();
54
+ return id && ledger.calls[id] ? ledger.calls[id] : null;
55
+ }
56
+
57
+ function listCalls(ledger) {
58
+ if (!ledger || !ledger.calls) return [];
59
+ return Object.keys(ledger.calls).map((id) => ledger.calls[id]);
60
+ }
61
+
62
+ function listUnresolved(ledger) {
63
+ return listCalls(ledger).filter((call) => (
64
+ call.state === "declared" || call.state === "executing"
65
+ ));
66
+ }
67
+
68
+ function listDeferred(ledger) {
69
+ return listCalls(ledger).filter((call) => call.state === "deferred");
70
+ }
71
+
72
+ /**
73
+ * Declare one or more tool calls after prepareToolCalls.
74
+ * @param {object} ledger
75
+ * @param {Array<{ callId: string, name: string, args?: object }>} calls
76
+ */
77
+ function declareCalls(ledger, calls = []) {
78
+ if (!ledger || !ledger.calls) {
79
+ return { ok: false, error: "missing ledger" };
80
+ }
81
+ const list = Array.isArray(calls) ? calls : [];
82
+ for (const entry of list) {
83
+ const callId = String(entry && entry.callId || "").trim();
84
+ if (!callId) {
85
+ return { ok: false, error: "callId required" };
86
+ }
87
+ if (ledger.calls[callId]) {
88
+ return { ok: false, error: `duplicate callId: ${callId}`, code: "DUPLICATE_CALL_ID" };
89
+ }
90
+ const name = String(entry.name || "").trim().toLowerCase();
91
+ ledger.calls[callId] = {
92
+ callId,
93
+ name,
94
+ argsDigest: digestValue(entry.args == null ? {} : entry.args),
95
+ state: "declared",
96
+ resultDigest: "",
97
+ isError: false,
98
+ resolvedAt: "",
99
+ deferredAt: "",
100
+ executingAt: "",
101
+ };
102
+ }
103
+ if (!ledger.assistantMessageId && list.length > 0) {
104
+ ledger.assistantMessageId = String(list[0].callId || "");
105
+ }
106
+ return { ok: true, count: list.length };
107
+ }
108
+
109
+ function markExecuting(ledger, callId) {
110
+ const call = getCall(ledger, callId);
111
+ if (!call) return { ok: false, error: "call not found", code: "CALL_NOT_FOUND" };
112
+ if (call.state !== "declared") {
113
+ return { ok: false, error: `cannot execute from ${call.state}`, code: "INVALID_STATE" };
114
+ }
115
+ call.state = "executing";
116
+ call.executingAt = new Date().toISOString();
117
+ return { ok: true, call };
118
+ }
119
+
120
+ /**
121
+ * Defer a call authorized by the composed tool registry. Leaves assistant tool_call unpaired until resume.
122
+ */
123
+ function deferCall(ledger, callId, { reason = "" } = {}) {
124
+ const call = getCall(ledger, callId);
125
+ if (!call) return { ok: false, error: "call not found", code: "CALL_NOT_FOUND" };
126
+ if (call.state !== "declared" && call.state !== "executing") {
127
+ return { ok: false, error: `cannot defer from ${call.state}`, code: "INVALID_STATE" };
128
+ }
129
+ if (!(ledger.deferableTools instanceof Set && ledger.deferableTools.has(call.name))) {
130
+ return {
131
+ ok: false,
132
+ error: `tool ${call.name} cannot be deferred`,
133
+ code: "NOT_DEFERABLE",
134
+ };
135
+ }
136
+ call.state = "deferred";
137
+ call.deferredAt = new Date().toISOString();
138
+ call.deferReason = String(reason || "").trim();
139
+ return { ok: true, call };
140
+ }
141
+
142
+ /**
143
+ * Resolve a declared/executing/deferred call with exactly one result.
144
+ * Idempotent when resultDigest matches a prior resolve.
145
+ */
146
+ function resolveCall(ledger, callId, {
147
+ result = null,
148
+ isError = false,
149
+ allowFromDeferred = true,
150
+ } = {}) {
151
+ const call = getCall(ledger, callId);
152
+ if (!call) return { ok: false, error: "call not found", code: "CALL_NOT_FOUND" };
153
+
154
+ const resultDigest = digestValue(result);
155
+ if (call.state === "resolved") {
156
+ if (call.resultDigest === resultDigest) {
157
+ return { ok: true, call, idempotent: true };
158
+ }
159
+ return {
160
+ ok: false,
161
+ error: "call already resolved with different result",
162
+ code: "DUPLICATE_RESOLVE",
163
+ call,
164
+ };
165
+ }
166
+
167
+ if (call.state === "deferred" && !allowFromDeferred) {
168
+ return { ok: false, error: "call is deferred", code: "STILL_DEFERRED", call };
169
+ }
170
+ if (call.state !== "declared" && call.state !== "executing" && call.state !== "deferred") {
171
+ return { ok: false, error: `cannot resolve from ${call.state}`, code: "INVALID_STATE", call };
172
+ }
173
+
174
+ call.state = "resolved";
175
+ call.resultDigest = resultDigest;
176
+ call.resultPayload = result;
177
+ call.isError = Boolean(isError);
178
+ call.resolvedAt = new Date().toISOString();
179
+ return { ok: true, call, idempotent: false };
180
+ }
181
+
182
+ function recordViolation(ledger, violation = {}) {
183
+ if (!ledger) return;
184
+ if (!Array.isArray(ledger.violations)) ledger.violations = [];
185
+ ledger.violations.push({
186
+ code: String(violation.code || "PROTOCOL_VIOLATION"),
187
+ message: String(violation.message || ""),
188
+ callId: String(violation.callId || ""),
189
+ at: new Date().toISOString(),
190
+ });
191
+ }
192
+
193
+ function snapshotLedger(ledger) {
194
+ if (!ledger) return null;
195
+ return JSON.parse(JSON.stringify({
196
+ turnId: ledger.turnId,
197
+ provider: ledger.provider,
198
+ sessionId: ledger.sessionId,
199
+ assistantMessageId: ledger.assistantMessageId,
200
+ calls: ledger.calls,
201
+ violations: ledger.violations || [],
202
+ createdAt: ledger.createdAt,
203
+ }));
204
+ }
205
+
206
+ module.exports = {
207
+ CALL_STATES,
208
+ digestValue,
209
+ createTurnId,
210
+ createToolCallLedger,
211
+ getCall,
212
+ listCalls,
213
+ listUnresolved,
214
+ listDeferred,
215
+ declareCalls,
216
+ markExecuting,
217
+ deferCall,
218
+ resolveCall,
219
+ recordViolation,
220
+ snapshotLedger,
221
+ };
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const { randomUUID } = require("crypto");
6
+ const { withFileLock } = require("../context/fileLock");
7
+
8
+ const alive = (pid) => { try { process.kill(pid, 0); return true; } catch (error) { return error.code !== "ESRCH"; } };
9
+
10
+ /** Cross-process serialization mechanism; the host supplies resource identity and policy. */
11
+ function createResourceLease({ file } = {}) {
12
+ if (!file) throw new Error("resource lease file is required");
13
+ function transaction(mutator) {
14
+ return withFileLock(file, () => {
15
+ const state = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, "utf8")) : { version: 1, resources: {} };
16
+ if (state.version !== 1 || !state.resources || typeof state.resources !== "object") throw new Error("invalid resource lease store");
17
+ state.resources = Object.assign(Object.create(null), state.resources);
18
+ for (const owner of Object.values(state.resources)) {
19
+ if (!Number.isInteger(owner.pid) || owner.pid < 1 || typeof owner.token !== "string" || typeof owner.ownerId !== "string") throw new Error("invalid resource lease owner");
20
+ }
21
+ for (const [key, owner] of Object.entries(state.resources)) if (!alive(owner.pid)) delete state.resources[key];
22
+ const result = mutator(state);
23
+ fs.mkdirSync(path.dirname(file), { recursive: true });
24
+ const temporary = `${file}.${randomUUID()}.tmp`;
25
+ try { fs.writeFileSync(temporary, JSON.stringify(state), { mode: 0o600 }); fs.renameSync(temporary, file); }
26
+ finally { if (fs.existsSync(temporary)) fs.unlinkSync(temporary); }
27
+ return result;
28
+ });
29
+ }
30
+ const api = Object.freeze({
31
+ acquire({ key, ownerId }) {
32
+ if (!key || !ownerId) throw new Error("resource key and ownerId are required");
33
+ return transaction((state) => {
34
+ const existing = Object.prototype.hasOwnProperty.call(state.resources, key) ? state.resources[key] : null;
35
+ if (existing) return existing.ownerId === ownerId && existing.pid === process.pid
36
+ ? { ok: true, token: existing.token, reentrant: true }
37
+ : { ok: false, code: "workspace_busy", ownerId: existing.ownerId };
38
+ const token = randomUUID();
39
+ state.resources[key] = { token, ownerId, pid: process.pid };
40
+ return { ok: true, token, reentrant: false };
41
+ });
42
+ },
43
+ release({ key, token }) {
44
+ return transaction((state) => {
45
+ if (!Object.prototype.hasOwnProperty.call(state.resources, key) || state.resources[key].token !== token) return false;
46
+ delete state.resources[key]; return true;
47
+ });
48
+ },
49
+ async run({ key, ownerId, signal, wait = false, timeoutMs = 600000 }, operation) {
50
+ const started = Date.now();
51
+ let lease;
52
+ for (;;) {
53
+ if (signal && signal.aborted) throw Object.assign(new Error("resource acquisition cancelled"), { code: "cancelled" });
54
+ lease = api.acquire({ key, ownerId });
55
+ if (lease.ok) break;
56
+ if (!wait || Date.now() - started >= timeoutMs) return { ...lease, error: "workspace writer is active" };
57
+ await new Promise((resolve) => setTimeout(resolve, 50));
58
+ }
59
+ try { return await operation(); }
60
+ finally { if (!lease.reentrant) api.release({ key, token: lease.token }); }
61
+ },
62
+ });
63
+ return api;
64
+ }
65
+
66
+ module.exports = { createResourceLease };
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+
3
+ /** Bounded host scheduler. Resource keys serialize writers without blocking other work. */
4
+ function createTaskScheduler({ maxConcurrent = 2, maxQueued = 64 } = {}) {
5
+ if (!Number.isInteger(maxConcurrent) || maxConcurrent < 1 || !Number.isInteger(maxQueued) || maxQueued < 1) throw new Error("invalid scheduler limits");
6
+ const jobs = new Map();
7
+ const resources = new Set();
8
+ let active = 0;
9
+ let closed = false;
10
+ let order = 0;
11
+ function drain() {
12
+ if (closed) return;
13
+ const ready = [...jobs.values()].filter((job) => job.status === "queued").sort((a, b) => b.priority - a.priority || a.order - b.order);
14
+ for (const job of ready) {
15
+ if (active >= maxConcurrent) return;
16
+ if (job.resourceKey && resources.has(job.resourceKey)) continue;
17
+ active += 1;
18
+ if (job.resourceKey) resources.add(job.resourceKey);
19
+ job.status = "running";
20
+ Promise.resolve().then(() => job.work(job.controller.signal)).then(job.resolve, job.reject).finally(() => {
21
+ active -= 1;
22
+ if (job.resourceKey) resources.delete(job.resourceKey);
23
+ jobs.delete(job.id);
24
+ if (job.externalSignal) job.externalSignal.removeEventListener("abort", job.abort);
25
+ drain();
26
+ });
27
+ }
28
+ }
29
+ return Object.freeze({
30
+ schedule({ id, resourceKey = "", signal = null, priority = 0 }, work) {
31
+ if (closed) return Promise.reject(new Error("scheduler closed"));
32
+ if (!id || typeof work !== "function") return Promise.reject(new Error("scheduler requires id and work"));
33
+ if (jobs.has(id)) return jobs.get(id).promise;
34
+ if ([...jobs.values()].filter((job) => job.status === "queued").length >= maxQueued) return Promise.reject(Object.assign(new Error("scheduler queue is full"), { code: "queue_full" }));
35
+ const controller = new AbortController();
36
+ const job = { id, resourceKey, priority, work, controller, order: order++, status: "queued", externalSignal: signal };
37
+ job.promise = new Promise((resolve, reject) => { job.resolve = resolve; job.reject = reject; });
38
+ job.abort = () => {
39
+ controller.abort(signal && signal.reason);
40
+ if (job.status === "queued") {
41
+ jobs.delete(id);
42
+ job.reject(Object.assign(new Error("task cancelled before scheduling"), { code: "cancelled" }));
43
+ if (signal) signal.removeEventListener("abort", job.abort);
44
+ drain();
45
+ }
46
+ };
47
+ jobs.set(id, job);
48
+ if (signal) {
49
+ if (signal.aborted) job.abort();
50
+ else signal.addEventListener("abort", job.abort, { once: true });
51
+ }
52
+ drain();
53
+ return job.promise;
54
+ },
55
+ snapshot: () => ({ closed, active, queued: [...jobs.values()].filter((job) => job.status === "queued").length,
56
+ jobs: [...jobs.values()].map(({ id, resourceKey, status }) => ({ id, resourceKey, status })) }),
57
+ async close() {
58
+ closed = true;
59
+ const pending = [...jobs.values()];
60
+ for (const job of pending) {
61
+ job.controller.abort("scheduler_closed");
62
+ if (job.status === "queued") {
63
+ jobs.delete(job.id);
64
+ job.reject(Object.assign(new Error("scheduler closed"), { code: "cancelled" }));
65
+ if (job.externalSignal) job.externalSignal.removeEventListener("abort", job.abort);
66
+ }
67
+ }
68
+ await Promise.allSettled(pending.map((job) => job.promise));
69
+ },
70
+ });
71
+ }
72
+
73
+ module.exports = { createTaskScheduler };
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+
3
+ const { AjvJsonSchemaValidator } = require("@modelcontextprotocol/sdk/validation/ajv-provider.js");
4
+
5
+ /** Bind an explicit tool set. Host grants are independent of model/profile input. */
6
+ function createToolRegistry({ tools = [], grantedPermissions = [], authorize = null } = {}) {
7
+ const definitions = new Map();
8
+ const permissions = new Set(grantedPermissions);
9
+ const validator = new AjvJsonSchemaValidator();
10
+ if (authorize != null && typeof authorize !== "function") throw new Error("host authorizeTool must be a function");
11
+ for (const tool of tools) {
12
+ if (!tool || !/^[a-z][a-z0-9_-]*$/.test(tool.name || "")) {
13
+ throw new Error("invalid runtime tool name");
14
+ }
15
+ if (definitions.has(tool.name)) throw new Error(`duplicate runtime tool: ${tool.name}`);
16
+ if (typeof tool.handler !== "function") throw new Error(`missing handler: ${tool.name}`);
17
+ const requiredPermissions = [...(tool.permissions || [])];
18
+ for (const permission of requiredPermissions) {
19
+ if (!permissions.has(permission)) throw new Error(`tool ${tool.name} requires permission: ${permission}`);
20
+ }
21
+ const inputSchema = JSON.parse(JSON.stringify(tool.inputSchema || { type: "object" }));
22
+ definitions.set(tool.name, {
23
+ ...tool,
24
+ inputSchema,
25
+ permissions: requiredPermissions,
26
+ validateInput: validator.getValidator(inputSchema),
27
+ });
28
+ }
29
+
30
+ return Object.freeze({
31
+ names: () => [...definitions.keys()],
32
+ deferableTools: () => [...definitions.values()].filter((tool) => tool.deferable).map((tool) => tool.name),
33
+ tightTools: () => [...definitions.values()].filter((tool) => tool.tight).map((tool) => tool.name),
34
+ toOpenAiTools: () => [...definitions.values()].map((tool) => ({
35
+ type: "function",
36
+ function: {
37
+ name: tool.name,
38
+ description: tool.description || "",
39
+ parameters: JSON.parse(JSON.stringify(tool.inputSchema)),
40
+ },
41
+ })),
42
+ async execute(name, args, context = {}) {
43
+ const tool = definitions.get(String(name || "").trim());
44
+ if (!tool) return { ok: false, code: "unsupported_tool", error: `unsupported tool: ${name}` };
45
+ const validation = tool.validateInput(args);
46
+ if (!validation.valid) {
47
+ return { ok: false, code: "invalid_tool_arguments", error: validation.errorMessage };
48
+ }
49
+ if (authorize && await authorize({ name: tool.name, permissions: tool.permissions.slice(), context }) !== true) {
50
+ return { ok: false, code: "forbidden_tool", error: `host denied tool: ${name}` };
51
+ }
52
+ return tool.handler(args, context);
53
+ },
54
+ });
55
+ }
56
+
57
+ module.exports = { createToolRegistry };
@@ -29,6 +29,7 @@ const { IPC_REQUEST_TYPES } = require("../../runtime/contracts/eventContract");
29
29
  function createChatController({
30
30
  projectRoot = process.cwd(),
31
31
  globalMode = false,
32
+ internalOnly = false,
32
33
  ports = {},
33
34
  } = {}) {
34
35
  const view = {
@@ -66,14 +67,17 @@ function createChatController({
66
67
  loop: null,
67
68
  targetAgent: null,
68
69
  pending: null,
70
+ runtimeSessionId: "main-default",
69
71
  };
70
72
 
71
73
  function setSend(fn) {
72
- daemonSend = typeof fn === "function" ? fn : () => {};
74
+ daemonSend = typeof fn === "function" ? (req) => fn(req.type === IPC_REQUEST_TYPES.PROMPT || req.type === IPC_REQUEST_TYPES.AGENT_RUNTIME
75
+ ? { ...req, request_id: req.request_id || require("crypto").randomUUID(), session_id: req.session_id || session.runtimeSessionId } : req) : () => {};
73
76
  }
77
+ setSend(view.send);
74
78
 
75
79
  function applyStatus(data = {}) {
76
- const snapshot = normalizeStatusToAgentsSnapshot(data);
80
+ const snapshot = normalizeStatusToAgentsSnapshot(data, { internalOnly });
77
81
  session.agents = snapshot.agents.map((row) => row.id || row.fullId);
78
82
  session.metaMap = snapshot.metaMap;
79
83
  session.labelMap = snapshot.labelMap;
@@ -97,13 +101,14 @@ function createChatController({
97
101
 
98
102
  function patchAgentActivity(agentId, patch = {}) {
99
103
  if (!agentId) return;
104
+ if (internalOnly && !session.metaMap.has(agentId)) return;
100
105
  const existing = session.metaMap.get(agentId) || { id: agentId };
101
106
  const next = { ...existing, ...patch };
102
107
  session.metaMap.set(agentId, next);
103
108
  const rebuilt = normalizeStatusToAgentsSnapshot({
104
109
  active: session.agents,
105
110
  active_meta: session.agents.map((id) => session.metaMap.get(id) || { id }),
106
- });
111
+ }, { internalOnly });
107
112
  session.footer = rebuilt.footer;
108
113
  view.publish("agents.patch", {
109
114
  agents: rebuilt.agents.map((row) => ({
@@ -130,6 +135,7 @@ function createChatController({
130
135
 
131
136
  commandExecutor = createCommandExecutor({
132
137
  projectRoot,
138
+ internalOnly,
133
139
  getActiveProjectRoot: typeof ports.getActiveProjectRoot === "function"
134
140
  ? ports.getActiveProjectRoot
135
141
  : () => projectRoot,
@@ -168,12 +174,16 @@ function createChatController({
168
174
  ? ports.restartDaemon
169
175
  : async () => {},
170
176
  send: (req) => daemonSend(req),
177
+ setRuntimeSession: (id) => { session.runtimeSessionId = id; },
178
+ getRuntimeSession: () => session.runtimeSessionId,
171
179
  requestStatus: () => {
172
180
  if (typeof requestDaemonStatus === "function") requestDaemonStatus();
173
181
  else daemonSend({ type: IPC_REQUEST_TYPES.STATUS });
174
182
  },
175
183
  requestCron: (payload = {}) => daemonSend({ type: IPC_REQUEST_TYPES.CRON, ...payload }),
176
184
  activateAgent: async (target) => {
185
+ if (typeof ports.activateAgent === "function") return ports.activateAgent(target);
186
+ if (internalOnly) return;
177
187
  const activator = new AgentActivator(projectRoot);
178
188
  await activator.activate(target);
179
189
  },
@@ -223,6 +233,7 @@ function createChatController({
223
233
  });
224
234
  submitHandler = createInputSubmitHandler({
225
235
  state: submitState,
236
+ requireKnownTarget: internalOnly,
226
237
  parseAtTarget,
227
238
  resolveAgentId: (label) => resolveAgentId({
228
239
  label,