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.
Files changed (266) hide show
  1. package/OBSERVABILITY.md +65 -0
  2. package/README.md +238 -21
  3. package/README.zh-CN.md +165 -20
  4. package/SKILLS/ufoo/SKILL.md +40 -4
  5. package/SKILLS/ufoo-bus/SKILL.md +46 -3
  6. package/bin/uclaude.js +4 -0
  7. package/bin/ucodex.js +4 -0
  8. package/bin/ufoo.js +6 -4
  9. package/dist/tui/darwin-arm64/ufoo-tui +0 -0
  10. package/dist/tui/darwin-x64/ufoo-tui +0 -0
  11. package/dist/tui/linux-arm64/ufoo-tui +0 -0
  12. package/dist/tui/linux-x64/ufoo-tui +0 -0
  13. package/package.json +14 -7
  14. package/scripts/postinstall-skills.js +53 -0
  15. package/scripts/postinstall.js +11 -16
  16. package/scripts/smoke-native-messages.js +214 -0
  17. package/src/agents/activity/activityDetector.js +1 -1
  18. package/src/agents/activity/activityStateWriter.js +37 -38
  19. package/src/agents/capabilities/agentManagement/index.js +4 -0
  20. package/src/agents/capabilities/agentManagement/service.js +140 -0
  21. package/src/agents/capabilities/agentRouting/index.js +4 -0
  22. package/src/agents/capabilities/coding/index.js +32 -0
  23. package/src/agents/capabilities/coordination/index.js +37 -0
  24. package/src/agents/capabilities/globalRouting/index.js +5 -0
  25. package/src/agents/capabilities/groups/index.js +3 -0
  26. package/src/agents/capabilities/index.js +25 -0
  27. package/src/agents/capabilities/planning/index.js +123 -0
  28. package/src/agents/capabilities/planning/main.js +28 -0
  29. package/src/agents/capabilities/projectDiscovery/index.js +3 -0
  30. package/src/agents/capabilities/scheduling/index.js +3 -0
  31. package/src/agents/capabilities/sharedMemory/index.js +4 -0
  32. package/src/agents/capabilities/skills/index.js +12 -0
  33. package/src/agents/capabilities/taskExecution/index.js +3 -0
  34. package/src/agents/capabilities/taskReports/index.js +6 -0
  35. package/src/agents/controller/controllerToolExecutor.js +40 -22
  36. package/src/agents/controller/index.js +1 -6
  37. package/src/agents/internal/internalRunner.js +181 -76
  38. package/src/agents/launch/index.js +0 -1
  39. package/src/agents/launch/launcher.js +96 -14
  40. package/src/agents/launch/nativeCapabilities.js +40 -0
  41. package/src/agents/launch/nativeMessages.js +362 -0
  42. package/src/agents/launch/notifier.js +15 -20
  43. package/src/agents/launch/readyDetector.js +28 -14
  44. package/src/agents/profiles/coding.js +6 -0
  45. package/src/agents/profiles/globalRouter.js +2 -0
  46. package/src/agents/profiles/main.js +5 -0
  47. package/src/agents/prompts/cooperation.js +14 -0
  48. package/src/agents/prompts/defaultBootstrap.js +1 -1
  49. package/src/agents/prompts/groupBootstrap.js +32 -6
  50. package/src/agents/prompts/mainAgent.js +48 -0
  51. package/src/agents/prompts/native/system.js +4 -1
  52. package/src/agents/prompts/native/tasks.js +2 -2
  53. package/src/agents/prompts/native/ufoo.js +14 -3
  54. package/src/agents/prompts/promptProfiles.js +2 -0
  55. package/src/agents/prompts/reporting.js +16 -0
  56. package/src/agents/providers/claudeEventTranslator.js +9 -1
  57. package/src/agents/providers/claudeThreadProvider.js +47 -4
  58. package/src/agents/providers/clientIdentity.js +75 -0
  59. package/src/agents/providers/codexEventTranslator.js +68 -7
  60. package/src/agents/providers/codexThreadProvider.js +18 -8
  61. package/src/agents/providers/credentials/claude.js +10 -3
  62. package/src/agents/providers/credentials/index.js +2 -0
  63. package/src/agents/providers/directAuthStatus.js +1 -1
  64. package/src/agents/providers/index.js +1 -1
  65. package/src/agents/providers/modelSettings.js +34 -0
  66. package/src/agents/providers/modelsCatalog.js +379 -0
  67. package/src/agents/providers/nativeTransport.js +1146 -0
  68. package/src/agents/providers/runtimeConfig.js +188 -0
  69. package/src/agents/providers/thinkingLevels.js +106 -0
  70. package/src/agents/providers/transports/anthropicMessagesTransport.js +121 -0
  71. package/src/agents/providers/transports/index.js +10 -0
  72. package/src/agents/providers/transports/openaiChatTransport.js +117 -0
  73. package/src/agents/providers/transports/openaiResponsesTransport.js +120 -0
  74. package/src/agents/providers/transports/responsesProtocol.js +504 -0
  75. package/src/agents/providers/transports/systemBlocks.js +16 -0
  76. package/src/agents/providers/transports/transportContract.js +50 -0
  77. package/src/agents/providers/transports/visionBlocks.js +151 -0
  78. package/src/agents/providers/upstreamRuntime.js +135 -0
  79. package/src/agents/runtime/composeCapabilities.js +89 -0
  80. package/src/agents/runtime/context/checkpointStore.js +38 -0
  81. package/src/agents/runtime/context/commandStore.js +43 -0
  82. package/src/agents/runtime/context/compaction.js +151 -0
  83. package/src/agents/runtime/context/contextBudget.js +93 -0
  84. package/src/agents/runtime/context/contextWindow.js +119 -0
  85. package/src/agents/runtime/context/fileLock.js +36 -0
  86. package/src/agents/runtime/context/replayHistory.js +28 -0
  87. package/src/agents/runtime/context/runtimeStore.js +127 -0
  88. package/src/agents/runtime/context/sessionJournal.js +360 -0
  89. package/src/agents/runtime/context/sessionStore.js +57 -0
  90. package/src/agents/runtime/core/agentLoop.js +351 -0
  91. package/src/agents/runtime/core/executionBudget.js +36 -0
  92. package/src/agents/runtime/core/stableJson.js +29 -0
  93. package/src/agents/runtime/core/toolLoopGuard.js +55 -0
  94. package/src/agents/runtime/createAgentRuntime.js +259 -0
  95. package/src/agents/runtime/index.js +14 -0
  96. package/src/agents/runtime/prompts/responseLanguage.js +12 -0
  97. package/src/agents/runtime/protocol/faultHarness.js +90 -0
  98. package/src/agents/runtime/protocol/materialize.js +107 -0
  99. package/src/agents/runtime/protocol/runObservation.js +24 -0
  100. package/src/agents/runtime/protocol/toolCallLedger.js +221 -0
  101. package/src/agents/runtime/protocol/traceContext.js +9 -0
  102. package/src/agents/runtime/tasks/resourceLease.js +66 -0
  103. package/src/agents/runtime/tasks/scheduler.js +73 -0
  104. package/src/agents/runtime/tools/registry.js +57 -0
  105. package/src/app/chat/ChatController.js +29 -45
  106. package/src/app/chat/agentDirectory.js +9 -18
  107. package/src/app/chat/bootstrap.js +1 -2
  108. package/src/app/chat/commandExecutor.js +111 -313
  109. package/src/app/chat/commands.js +39 -45
  110. package/src/app/chat/daemonConnection.js +58 -5
  111. package/src/app/chat/daemonMessageRouter.js +61 -48
  112. package/src/app/chat/historyStore.js +12 -48
  113. package/src/app/chat/inputSubmitHandler.js +21 -35
  114. package/src/app/chat/internalAgentLogHistory.js +19 -60
  115. package/src/app/chat/launchRequestContext.js +42 -0
  116. package/src/app/chat/multiWindow/paneManager.js +91 -164
  117. package/src/app/chat/streamState.js +3 -7
  118. package/src/app/chat/transport.js +1 -1
  119. package/src/app/cli/busCoreCommands.js +9 -0
  120. package/src/app/cli/features/doctor.js +33 -0
  121. package/src/app/cli/features/init.js +5 -5
  122. package/src/app/cli/features/skills.js +16 -4
  123. package/src/app/cli/metricsCommands.js +68 -0
  124. package/src/app/cli/reportCoreCommands.js +37 -0
  125. package/src/app/cli/run.js +82 -42
  126. package/src/app/cli/traceCommands.js +36 -0
  127. package/src/code/agent.js +34 -17
  128. package/src/code/busConsumer.js +1 -3
  129. package/src/code/commands.js +1 -1
  130. package/src/code/context/artifacts.js +12 -11
  131. package/src/code/context/assembler.js +9 -9
  132. package/src/code/context/promptLayers.js +1 -13
  133. package/src/code/context/stableJson.js +2 -27
  134. package/src/code/context/stateCommit.js +2 -1
  135. package/src/code/contextWindow.js +2 -117
  136. package/src/code/conversation/sessionJournal.js +3 -349
  137. package/src/code/internalThread.js +107 -0
  138. package/src/code/launcher/ucode.js +1 -1
  139. package/src/code/launcher/ucodeBootstrap.js +1 -1
  140. package/src/code/modelCommand.js +11 -35
  141. package/src/code/nativeRunner.js +104 -2697
  142. package/src/code/protocol/faultHarness.js +2 -88
  143. package/src/code/protocol/materialize.js +2 -105
  144. package/src/code/protocol/toolCallLedger.js +5 -215
  145. package/src/code/providers/anthropicMessagesTransport.js +2 -118
  146. package/src/code/providers/modelsCatalog.js +1 -317
  147. package/src/code/providers/openaiChatTransport.js +2 -114
  148. package/src/code/providers/openaiResponsesTransport.js +2 -117
  149. package/src/code/providers/responsesProtocol.js +2 -497
  150. package/src/code/providers/transportContract.js +2 -48
  151. package/src/code/providers/visionBlocks.js +2 -149
  152. package/src/code/repl.js +2 -11
  153. package/src/code/sessionStore.js +27 -99
  154. package/src/code/taskDecomposer.js +18 -0
  155. package/src/code/thinkingLevels.js +1 -130
  156. package/src/code/toolBudget.js +1 -17
  157. package/src/code/toolLoopGuard.js +3 -49
  158. package/src/code/tools/artifactRead.js +1 -1
  159. package/src/code/tools/executor.js +373 -0
  160. package/src/code/tools/specs.js +312 -0
  161. package/src/config.js +95 -131
  162. package/src/coordination/bus/deliveryQueue.js +16 -2
  163. package/src/coordination/bus/index.js +14 -9
  164. package/src/coordination/bus/inject.js +15 -7
  165. package/src/coordination/bus/message.js +15 -1
  166. package/src/coordination/bus/nativeReceipts.js +100 -0
  167. package/src/coordination/bus/nickname.js +1 -1
  168. package/src/coordination/bus/queue.js +1 -3
  169. package/src/coordination/bus/subscriber.js +3 -2
  170. package/src/coordination/bus/utils.js +8 -4
  171. package/src/coordination/history/agentPerformance.js +279 -0
  172. package/src/coordination/history/agentSurface.js +142 -0
  173. package/src/coordination/history/agentTrace.js +249 -0
  174. package/src/coordination/memory/index.js +5 -21
  175. package/src/coordination/report/store.js +103 -83
  176. package/src/coordination/state/agentsStore.js +57 -3
  177. package/src/coordination/state/fileLock.js +2 -0
  178. package/src/coordination/state/workspaceAccess.js +36 -0
  179. package/src/orchestration/controller/index.js +1 -8
  180. package/src/orchestration/controller/launchRouting.js +1 -1
  181. package/src/orchestration/solo/commands.js +3 -1
  182. package/src/runtime/contracts/agentMode.js +26 -0
  183. package/src/runtime/contracts/eventContract.js +3 -0
  184. package/src/runtime/contracts/uiProtocol.js +20 -17
  185. package/src/runtime/daemon/agentHost.js +407 -0
  186. package/src/runtime/daemon/agentRecoveryGroups.js +70 -0
  187. package/src/runtime/daemon/busBridge.js +396 -0
  188. package/src/runtime/daemon/claudeChannel.js +159 -0
  189. package/src/runtime/daemon/controlPlaneService.js +28 -18
  190. package/src/runtime/daemon/cronOps.js +25 -17
  191. package/src/runtime/daemon/deliveryScheduler.js +32 -5
  192. package/src/runtime/daemon/globalDaemon.js +28 -1
  193. package/src/runtime/daemon/groupOrchestrator.js +21 -5
  194. package/src/runtime/daemon/groupStatus.js +20 -0
  195. package/src/runtime/daemon/index.js +120 -375
  196. package/src/runtime/daemon/ipcServer.js +32 -10
  197. package/src/runtime/daemon/mcpConfigure.js +113 -20
  198. package/src/runtime/daemon/mcpHttpServer.js +27 -5
  199. package/src/runtime/daemon/mcpServer.js +8 -5
  200. package/src/runtime/daemon/mcpStdioProxy.js +127 -10
  201. package/src/runtime/daemon/nicknameScope.js +1 -1
  202. package/src/runtime/daemon/ops.js +68 -40
  203. package/src/runtime/daemon/projectRuntimeGateway.js +2 -0
  204. package/src/runtime/daemon/promptRequest.js +92 -570
  205. package/src/runtime/daemon/providerSessions.js +67 -33
  206. package/src/runtime/daemon/reportControlBus.js +59 -25
  207. package/src/runtime/daemon/status.js +9 -6
  208. package/src/runtime/privacy/redactor.js +2 -2
  209. package/src/runtime/projects/identity.js +2 -1
  210. package/src/runtime/projects/registry.js +98 -38
  211. package/src/tools/controllerSchemas.js +28 -0
  212. package/src/tools/handlers/dispatchMessage.js +5 -2
  213. package/src/tools/handlers/listAgents.js +3 -1
  214. package/src/tools/handlers/readBusSummary.js +3 -1
  215. package/src/tools/handlers/readProjectRegistry.js +29 -2
  216. package/src/tools/handlers/routeAgent.js +35 -0
  217. package/src/tools/handlers/tier2.js +4 -2
  218. package/src/tools/index.js +1 -0
  219. package/src/tools/registry.js +6 -0
  220. package/src/tools/schemaFixtures.js +42 -5
  221. package/src/tools/tier0/readAgentMetrics.js +14 -0
  222. package/src/tools/tier0/readAgentTrace.js +12 -0
  223. package/src/tools/tier1/routeAgent.js +2 -2
  224. package/src/tools/tier2/runtimeCoordination.js +38 -0
  225. package/src/tools/types.js +2 -0
  226. package/src/ui/agentPresentation.js +109 -0
  227. package/src/ui/agentSettingsController.js +107 -0
  228. package/src/ui/agentSurface.js +270 -0
  229. package/src/ui/dashboardBridge.js +1 -1
  230. package/src/ui/format/banner.js +9 -15
  231. package/src/ui/format/index.js +14 -10
  232. package/src/ui/format/loopSummary.js +50 -0
  233. package/src/ui/format/markdownRenderer.js +3 -4
  234. package/src/ui/format/startupBanner.js +50 -0
  235. package/src/ui/multiPaneBusMirror.js +29 -3
  236. package/src/ui/rustChatHost.js +316 -599
  237. package/src/ui/rustMultiSession.js +288 -73
  238. package/src/ui/rustUcodeHost.js +21 -88
  239. package/src/ui/settingsBridge.js +34 -14
  240. package/src/ui/toolMergeBridge.js +0 -4
  241. package/src/ui/uiHostServer.js +5 -8
  242. package/src/agents/controller/loopObservability.js +0 -200
  243. package/src/agents/controller/loopRuntime.js +0 -472
  244. package/src/agents/controller/ufooAgent.js +0 -829
  245. package/src/agents/launch/ptyRunner.js +0 -1135
  246. package/src/agents/providers/upstreamTransport.js +0 -689
  247. package/src/app/chat/agentBar.js +0 -135
  248. package/src/app/chat/agentEnter.js +0 -70
  249. package/src/app/chat/agentSockets.js +0 -225
  250. package/src/app/chat/dashboardView.js +0 -405
  251. package/src/app/chat/multiWindow/index.js +0 -310
  252. package/src/app/chat/multiWindow/paneLayout.js +0 -84
  253. package/src/app/chat/multiWindow/renderer.js +0 -420
  254. package/src/app/chat/multiWindow/virtualTerminal.js +0 -327
  255. package/src/app/chat/multiWindow/vtFrame.js +0 -93
  256. package/src/app/chat/rawKeyMap.js +0 -42
  257. package/src/app/chat/settingsController.js +0 -111
  258. package/src/orchestration/controller/flags.js +0 -167
  259. package/src/orchestration/controller/gateRouter.js +0 -211
  260. package/src/orchestration/controller/routerFastPath.js +0 -22
  261. package/src/orchestration/controller/routerFinalize.js +0 -222
  262. package/src/orchestration/controller/shadowGuard.js +0 -280
  263. package/src/runtime/daemon/promptLoop.js +0 -136
  264. package/src/runtime/privacy/shadowDiff.js +0 -174
  265. package/src/ui/multiWindowHandoff.js +0 -232
  266. package/src/ui/ptyHandoff.js +0 -23
@@ -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,9 @@
1
+ "use strict";
2
+
3
+ // Correlation metadata is observational. It never grants authority or identity.
4
+ const TRACE_FIELDS = Object.freeze(["traceId", "taskId", "taskRunId", "parentTaskRunId", "parentSessionId", "parentRequestId", "requestId", "attemptId"]);
5
+ function normalizeTraceContext(input = {}) {
6
+ return Object.fromEntries(TRACE_FIELDS.filter(key => typeof input?.[key] === "string" && input[key].length <= 256 && input[key].trim())
7
+ .map(key => [key, input[key].trim()]));
8
+ }
9
+ module.exports = { normalizeTraceContext };
@@ -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 };
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
 
3
3
  /**
4
- * Headless ChatController — composition root for Ink + Rust chat adapters.
4
+ * Headless ChatController — composition root for Rust chat.
5
5
  *
6
6
  * Owns stream state, STATUS→agents snapshot, slash/submit wiring ports.
7
7
  * View adapters attach via `ports` (dispatch / publish / log / setStatus).
@@ -21,7 +21,6 @@ const {
21
21
  buildAgentMaps,
22
22
  resolveAgentId,
23
23
  normalizeStatusToAgentsSnapshot,
24
- toInkAgentsDispatchList,
25
24
  } = require("./agentDirectory");
26
25
  const { buildPromptIpcRequest, buildDirectBusSendRequest } = require("./ipcBuilders");
27
26
  const { IPC_REQUEST_TYPES } = require("../../runtime/contracts/eventContract");
@@ -37,9 +36,6 @@ function createChatController({
37
36
  setStatus: typeof ports.setStatus === "function" ? ports.setStatus : () => {},
38
37
  publish: typeof ports.publish === "function" ? ports.publish : () => {},
39
38
  getState: typeof ports.getState === "function" ? ports.getState : () => ({}),
40
- mapAgentsForDispatch: typeof ports.mapAgentsForDispatch === "function"
41
- ? ports.mapAgentsForDispatch
42
- : (snapshot) => snapshot.agents,
43
39
  appendHistory: typeof ports.appendHistory === "function"
44
40
  ? ports.appendHistory
45
41
  : (type, text, meta) => appendChatHistory(projectRoot, type, text, meta, { globalMode }),
@@ -66,14 +62,18 @@ function createChatController({
66
62
  loop: null,
67
63
  targetAgent: null,
68
64
  pending: null,
65
+ runtimeSessionId: "main-default",
69
66
  };
70
67
 
71
68
  function setSend(fn) {
72
- daemonSend = typeof fn === "function" ? fn : () => {};
69
+ daemonSend = typeof fn === "function" ? (req) => fn(req.type === IPC_REQUEST_TYPES.PROMPT || req.type === IPC_REQUEST_TYPES.AGENT_RUNTIME
70
+ ? { ...req, request_id: req.request_id || require("crypto").randomUUID(), session_id: req.session_id
71
+ || require("../../config").loadConfig(ports.getActiveProjectRoot?.() || projectRoot).agentConversationId || session.runtimeSessionId } : req) : () => {};
73
72
  }
73
+ setSend(view.send);
74
74
 
75
75
  function applyStatus(data = {}) {
76
- const snapshot = normalizeStatusToAgentsSnapshot(data);
76
+ const snapshot = normalizeStatusToAgentsSnapshot(data, { internalOnly: true });
77
77
  session.agents = snapshot.agents.map((row) => row.id || row.fullId);
78
78
  session.metaMap = snapshot.metaMap;
79
79
  session.labelMap = snapshot.labelMap;
@@ -91,19 +91,20 @@ function createChatController({
91
91
  cron: snapshot.cron,
92
92
  loop: snapshot.loop,
93
93
  });
94
- view.dispatch({ type: "agents/set", list: view.mapAgentsForDispatch(snapshot) });
94
+ view.dispatch({ type: "agents/set", list: snapshot.agents });
95
95
  return snapshot;
96
96
  }
97
97
 
98
98
  function patchAgentActivity(agentId, patch = {}) {
99
99
  if (!agentId) return;
100
+ if (!session.metaMap.has(agentId)) return;
100
101
  const existing = session.metaMap.get(agentId) || { id: agentId };
101
102
  const next = { ...existing, ...patch };
102
103
  session.metaMap.set(agentId, next);
103
104
  const rebuilt = normalizeStatusToAgentsSnapshot({
104
105
  active: session.agents,
105
106
  active_meta: session.agents.map((id) => session.metaMap.get(id) || { id }),
106
- });
107
+ }, { internalOnly: true });
107
108
  session.footer = rebuilt.footer;
108
109
  view.publish("agents.patch", {
109
110
  agents: rebuilt.agents.map((row) => ({
@@ -125,7 +126,6 @@ function createChatController({
125
126
  const { createCommandExecutor } = require("./commandExecutor");
126
127
  const { parseCommand } = require("./commands");
127
128
  const { startDaemon, stopDaemon } = require("./transport");
128
- const AgentActivator = require("../../coordination/bus/activate");
129
129
  const fs = require("fs");
130
130
 
131
131
  commandExecutor = createCommandExecutor({
@@ -168,14 +168,22 @@ function createChatController({
168
168
  ? ports.restartDaemon
169
169
  : async () => {},
170
170
  send: (req) => daemonSend(req),
171
+ setRuntimeSession: (id) => {
172
+ session.runtimeSessionId = id;
173
+ require("../../config").saveConfig(ports.getActiveProjectRoot?.() || projectRoot, { agentConversationId: id });
174
+ },
175
+ getRuntimeSession: () => require("../../config").loadConfig(ports.getActiveProjectRoot?.() || projectRoot).agentConversationId || session.runtimeSessionId,
176
+ openAgentSettings: ports.openAgentSettings,
177
+ applyAgentModel: ports.applyAgentModel,
178
+ applyAgentSettings: ports.applyAgentSettings,
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) => {
177
- const activator = new AgentActivator(projectRoot);
178
- await activator.activate(target);
185
+ if (!session.metaMap.has(target)) return;
186
+ return ports.activateInternalAgent?.(target);
179
187
  },
180
188
  globalMode: Boolean(globalMode),
181
189
  listProjects: typeof ports.listProjects === "function"
@@ -187,14 +195,15 @@ function createChatController({
187
195
  switchProject: typeof ports.switchProject === "function"
188
196
  ? ports.switchProject
189
197
  : async () => ({ ok: false, error: "project switching unavailable" }),
190
- toggleMultiWindow: typeof ports.toggleMultiWindow === "function"
191
- ? ports.toggleMultiWindow
198
+ setWindowLayout: typeof ports.setWindowLayout === "function"
199
+ ? ports.setWindowLayout
192
200
  : () => {
193
- view.logMessage("system", "Multi-window unavailable in this host.");
201
+ view.logMessage("system", "Window layouts unavailable in this host.");
194
202
  },
195
203
  applyChatSettings: typeof ports.applyChatSettings === "function"
196
204
  ? ports.applyChatSettings
197
205
  : null,
206
+ openResumeMenu: typeof ports.openResumeMenu === "function" ? ports.openResumeMenu : null,
198
207
  });
199
208
  return commandExecutor;
200
209
  }
@@ -223,6 +232,7 @@ function createChatController({
223
232
  });
224
233
  submitHandler = createInputSubmitHandler({
225
234
  state: submitState,
235
+ requireKnownTarget: true,
226
236
  parseAtTarget,
227
237
  resolveAgentId: (label) => resolveAgentId({
228
238
  label,
@@ -264,35 +274,10 @@ function createChatController({
264
274
  const label = getAgentLabel(agentId);
265
275
  view.publish("prompt.set_prefix", { prefix: `›@${label} ` });
266
276
  },
267
- enterAgentView: (agentId, options = {}) => {
268
- if (typeof ports.enterAgentView === "function") {
269
- return ports.enterAgentView(agentId, options);
270
- }
271
- view.logMessage("system", "Agent enter unavailable in this host.");
272
- },
273
- getAgentAdapter: (agentId) => {
274
- if (typeof ports.getAgentAdapter === "function") {
275
- return ports.getAgentAdapter(agentId);
276
- }
277
- try {
278
- const { createTerminalAdapterRouter } = require("../../runtime/terminal/adapterRouter");
279
- const meta = session.metaMap.get(agentId) || {};
280
- const launchMode = String(meta.launch_mode || meta.launchMode || "").trim();
281
- return createTerminalAdapterRouter().getAdapter({ launchMode, agentId, meta });
282
- } catch {
283
- return null;
284
- }
285
- },
286
- activateAgent: async (agentId) => {
287
- if (typeof ports.activateAgent === "function") {
288
- return ports.activateAgent(agentId);
289
- }
290
- const AgentActivator = require("../../coordination/bus/activate");
291
- const root = typeof ports.getActiveProjectRoot === "function"
292
- ? ports.getActiveProjectRoot()
293
- : projectRoot;
294
- const activator = new AgentActivator(root || projectRoot);
295
- await activator.activate(agentId);
277
+ activateInternalAgent: (agentId) => {
278
+ if (!session.metaMap.has(agentId)) return { ok: false, error: "Unknown internal agent" };
279
+ if (typeof ports.activateInternalAgent === "function") return ports.activateInternalAgent(agentId);
280
+ return { ok: false, error: "Internal pane unavailable in this host" };
296
281
  },
297
282
  focusMultiPane: typeof ports.focusMultiPane === "function"
298
283
  ? ports.focusMultiPane
@@ -429,5 +414,4 @@ function createChatController({
429
414
 
430
415
  module.exports = {
431
416
  createChatController,
432
- toInkAgentsDispatchList,
433
417
  };
@@ -1,3 +1,5 @@
1
+ const { isInternalAgentMeta } = require("../../runtime/contracts/agentMode");
2
+
1
3
  function buildAgentMaps(activeAgents = [], metaList = [], fallbackMap = null) {
2
4
  const labelMap = new Map();
3
5
  const metaMap = new Map();
@@ -81,11 +83,15 @@ function clampAgentWindowWithSelection({
81
83
 
82
84
  /**
83
85
  * Normalize daemon STATUS payload into agents list + footer string.
84
- * Shared by Ink dashboard and Rust `agents.snapshot`.
86
+ * Used by Rust `agents.snapshot`.
85
87
  */
86
- function normalizeStatusToAgentsSnapshot(data = {}) {
87
- const activeIds = Array.isArray(data.active) ? data.active : [];
88
+ function normalizeStatusToAgentsSnapshot(data = {}, { internalOnly = false } = {}) {
89
+ let activeIds = Array.isArray(data.active) ? data.active : [];
88
90
  const metaList = Array.isArray(data.active_meta) ? data.active_meta : [];
91
+ if (internalOnly) {
92
+ const internalIds = new Set(metaList.filter(isInternalAgentMeta).map((meta) => meta.id));
93
+ activeIds = activeIds.filter((id) => internalIds.has(id));
94
+ }
89
95
  const { labelMap, metaMap } = buildAgentMaps(activeIds, metaList);
90
96
  const agents = activeIds.map((id) => {
91
97
  const meta = metaMap.get(id) || {};
@@ -126,20 +132,6 @@ function normalizeStatusToAgentsSnapshot(data = {}) {
126
132
  };
127
133
  }
128
134
 
129
- /**
130
- * Ink chatReducer expects `id` as the short agent id and `fullId` as the key.
131
- * Shared so ChatController and ChatApp stay aligned.
132
- */
133
- function toInkAgentsDispatchList(snapshot = {}) {
134
- const agents = Array.isArray(snapshot.agents) ? snapshot.agents : [];
135
- return agents.map((row) => ({
136
- ...row,
137
- fullId: row.fullId || row.id,
138
- id: row.agentId || row.id,
139
- nickname: row.label || row.nickname,
140
- }));
141
- }
142
-
143
135
  module.exports = {
144
136
  buildAgentMaps,
145
137
  getAgentLabel,
@@ -147,5 +139,4 @@ module.exports = {
147
139
  resolveAgentDisplayName,
148
140
  clampAgentWindowWithSelection,
149
141
  normalizeStatusToAgentsSnapshot,
150
- toInkAgentsDispatchList,
151
142
  };
@@ -1,8 +1,7 @@
1
1
  "use strict";
2
2
 
3
3
  /**
4
- * Chat bootstrap helpers (Phase 0B extraction from ChatApp).
5
- * Headless — safe for ChatController and unit tests without Ink.
4
+ * Headless chat bootstrap helpers shared by ChatController and tests.
6
5
  */
7
6
 
8
7
  const path = require("path");