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
@@ -67,6 +67,7 @@ class SkillsManager {
67
67
  * 查找技能路径
68
68
  */
69
69
  findSkill(name) {
70
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(name)) throw new Error(`Invalid skill name: ${name}`);
70
71
  for (const root of [...this.skillRoots, ...this.optionalSkillRoots]) {
71
72
  const skillPath = path.join(root, name);
72
73
  if (fs.existsSync(skillPath)) {
@@ -103,7 +104,12 @@ class SkillsManager {
103
104
 
104
105
  if (name === "all") {
105
106
  // 安装所有技能
106
- const skills = this.list();
107
+ const skills = [
108
+ ...this.list(),
109
+ ...this.list({ optionalOnly: true }).filter((skill) => {
110
+ try { return Boolean(fs.lstatSync(path.join(target, skill))); } catch { return false; }
111
+ }),
112
+ ];
107
113
  for (const skill of skills) {
108
114
  await this.installOne(skill, target);
109
115
  }
@@ -126,9 +132,15 @@ class SkillsManager {
126
132
 
127
133
  const targetPath = path.join(target, name);
128
134
 
129
- // 如果目标已存在,先删除
130
- if (fs.existsSync(targetPath)) {
131
- fs.rmSync(targetPath, { recursive: true, force: true });
135
+ // Explicit installs preserve the previous skill, including custom files and
136
+ // symlinks. npm postinstall uses the stricter managed-link policy instead.
137
+ try {
138
+ fs.lstatSync(targetPath);
139
+ const backup = `${targetPath}.backup-${Date.now()}-${require("crypto").randomBytes(4).toString("hex")}`;
140
+ fs.renameSync(targetPath, backup);
141
+ console.log(` Previous skill saved to: ${backup}`);
142
+ } catch (error) {
143
+ if (error.code !== "ENOENT") throw error;
132
144
  }
133
145
 
134
146
  // 复制技能目录
@@ -0,0 +1,68 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const { readAgentPerformance } = require("../../coordination/history/agentTrace");
5
+
6
+ const ratio = (n, d) => n != null && d ? n / d : null;
7
+ const display = value => value == null ? "unknown" : Number(value).toFixed(1);
8
+ const duration = value => value == null ? "unknown" : `${display(value)}ms`;
9
+ const percentage = value => value == null ? "unknown" : `${display(value * 100)}%`;
10
+
11
+ function comparePerformance(current, baseline) {
12
+ if (baseline?.version !== 1 || !baseline.summary?.latency || !baseline.summary?.usage || !Number.isFinite(baseline.summary.runs)) {
13
+ throw new Error("baseline must be a ufoo metrics --json report (version 1)");
14
+ }
15
+ const values = report => ({
16
+ completedOfFinished: report.summary.completedOfFinished,
17
+ modelCallsPerRun: ratio(report.summary.counts.modelCalls || 0, report.summary.runs),
18
+ toolErrorsPerRun: ratio(report.summary.counts.toolErrors || 0, report.summary.runs),
19
+ elapsedP50Ms: report.summary.latency.elapsedMs?.p50 ?? null,
20
+ elapsedP95Ms: report.summary.latency.elapsedMs?.p95 ?? null,
21
+ firstTextP50Ms: report.summary.latency.firstTextMs?.p50 ?? null,
22
+ inputTokensPerObservedRun: report.coverage?.runsWithCompleteUsage === report.summary.runs ? ratio(report.summary.usage.input?.sum, report.summary.usage.input?.samples) : null,
23
+ outputTokensPerObservedRun: report.coverage?.runsWithCompleteUsage === report.summary.runs ? ratio(report.summary.usage.output?.sum, report.summary.usage.output?.samples) : null,
24
+ cacheHitRate: report.coverage?.runsWithCompleteCache === report.summary.runs ? report.summary.cache?.hitRate ?? null : null,
25
+ acceptedOfReviewed: report.delegations?.acceptedOfReviewed ?? null,
26
+ });
27
+ const before = values(baseline), after = values(current);
28
+ const metrics = Object.fromEntries(Object.keys(after).map(key => {
29
+ const a = before[key], b = after[key];
30
+ return [key, { before: a, after: b, delta: a == null || b == null ? null : b - a,
31
+ changeRatio: a == null || b == null || a === 0 ? null : (b - a) / Math.abs(a) }];
32
+ }));
33
+ return { baselineRuns: baseline.summary.runs, currentRuns: current.summary.runs,
34
+ incomplete: Boolean(current.incomplete || baseline.incomplete), metrics,
35
+ note: "Observed samples may contain different tasks; these deltas are not a causal or quality verdict." };
36
+ }
37
+
38
+ function runMetricsCommand(taskId, options = {}) {
39
+ const report = readAgentPerformance(options.project || process.cwd(), { task_id: options.task || taskId || "",
40
+ agent_id: options.agent, session_id: options.session, since: options.since, until: options.until,
41
+ provider: options.provider, model: options.model, limit: options.limit });
42
+ if (options.baseline) {
43
+ if (fs.statSync(options.baseline).size > 16 * 1024 * 1024) throw new Error("baseline exceeds 16 MiB");
44
+ report.comparison = comparePerformance(report, JSON.parse(fs.readFileSync(options.baseline, "utf8")));
45
+ }
46
+ if (options.json) console.log(JSON.stringify(report, null, 2));
47
+ else {
48
+ const summary = report.summary;
49
+ console.log(`Agent performance: ${summary.runs} observed runs${report.incomplete ? " (partial evidence)" : ""}`);
50
+ console.log(`Execution: ${summary.outcomes.completed} completed, ${summary.outcomes.failed} failed, ${summary.outcomes.cancelled} cancelled; completed/finished ${percentage(summary.completedOfFinished)}`);
51
+ console.log(`Latency: p50 ${duration(summary.latency.elapsedMs.p50)}, p95 ${duration(summary.latency.elapsedMs.p95)}; first text p50 ${duration(summary.latency.firstTextMs.p50)} (${summary.latency.firstTextMs.samples} samples)`);
52
+ console.log(`Models: ${summary.counts.modelCalls || 0} API attempts, ${summary.counts.sdkTurns || 0} SDK turns, ${summary.counts.modelFailures || 0} failures, ${summary.counts.modelRetries || 0} retries`);
53
+ console.log(`Usage: input ${display(summary.usage.input.sum)}, output ${display(summary.usage.output.sum)}; compaction input ${display(summary.compactionUsage.input.sum)}, output ${display(summary.compactionUsage.output.sum)}`);
54
+ console.log(`Cache: ${percentage(summary.cache.hitRate)} hit; read ${display(summary.cache.cachedTokens)}/${display(summary.cache.promptTokens)} prompt tokens, written ${display(summary.usage.cacheCreation.sum)} (${summary.cache.samples}/${summary.cache.usageSamples} usage samples)`);
55
+ console.log(`Tools: ${summary.counts.toolCalls || 0} executed, ${summary.counts.toolErrors || 0} errors, ${summary.counts.toolRejections || 0} rejected, ${summary.counts.repeatedToolCalls || 0} repeated arguments`);
56
+ console.log(`Delegation: ${report.delegations.accepted} accepted, ${report.delegations.rejected} rejected, ${report.delegations.awaitingAcceptance} awaiting acceptance`);
57
+ for (const cohort of report.cohorts) console.log(` ${cohort.provider}/${cohort.model} ${cohort.thinkingLevel} ${cohort.executionKind} ${cohort.requestKind} v${cohort.runtimeVersion} engine=${cohort.engineFingerprint.slice(0, 8)}: ${cohort.runs} runs, p50 ${duration(cohort.latency.elapsedMs.p50)}, cache ${percentage(cohort.cache.hitRate)}`);
58
+ if (report.comparison) {
59
+ for (const [name, value] of Object.entries(report.comparison.metrics)) console.log(` ${name}: ${display(value.before)} -> ${display(value.after)} (delta ${display(value.delta)})`);
60
+ console.log(report.comparison.note);
61
+ }
62
+ if (report.warnings.length) console.log(`Warnings: ${report.warnings.map(w => w.code).join(", ")}; --json includes source details`);
63
+ console.log(`Configuration coverage: ${report.coverage.runsWithConfiguration}/${summary.runs}; complete usage coverage: ${report.coverage.runsWithCompleteUsage}/${summary.runs}; complete cache coverage: ${report.coverage.runsWithCompleteCache}/${summary.runs}`);
64
+ }
65
+ return report;
66
+ }
67
+
68
+ module.exports = { runMetricsCommand, comparePerformance };
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+
3
+ async function sendAgentReportRequest(projectRoot, report) {
4
+ const { enqueueAgentReport } = require("../../runtime/daemon/reportControlBus");
5
+ const queued = await enqueueAgentReport(projectRoot, report);
6
+ const entry = queued.report;
7
+ return {
8
+ type: "response",
9
+ data: {
10
+ reply: `Report queued (${entry.phase})`,
11
+ report: entry,
12
+ queued,
13
+ },
14
+ };
15
+ }
16
+
17
+ function getReportDetail(out = {}) {
18
+ if (out.phase === "error") {
19
+ return out.error || out.summary || out.message || out.task_id;
20
+ }
21
+ return out.summary || out.message || out.task_id;
22
+ }
23
+
24
+ function printReportOutput(out, json = false, queued = null) {
25
+ if (json) {
26
+ console.log(JSON.stringify({
27
+ status: "queued",
28
+ report: out,
29
+ queued,
30
+ }, null, 2));
31
+ return;
32
+ }
33
+ const detail = getReportDetail(out);
34
+ console.log(`[report] queued ${out.phase} ${out.agent_id} ${out.task_id} ${detail}`);
35
+ }
36
+
37
+ module.exports = { sendAgentReportRequest, printReportOutput };
@@ -8,6 +8,7 @@ const {
8
8
  resolveDaemonEndpoint,
9
9
  routeDaemonRequest,
10
10
  } = require("../../runtime/daemon/endpoint");
11
+ const { sendAgentReportRequest, printReportOutput } = require("./reportCoreCommands");
11
12
  const { runBusCoreCommand } = require("./busCoreCommands");
12
13
  const { runCtxCommand } = require("./ctxCoreCommands");
13
14
  const { runOnlineCommand } = require("./onlineCoreCommands");
@@ -15,7 +16,7 @@ const { runGroupCoreCommand } = require("./groupCoreCommands");
15
16
  const { loadConfig } = require("../../config");
16
17
  const { loadPromptProfileRegistry } = require("../../orchestration/groups/promptProfiles");
17
18
  const { resolveSoloAgentType } = require("../../orchestration/solo/commands");
18
- const { listProjectRuntimes, getCurrentProjectRuntime } = require("../../runtime/projects/registry");
19
+ const { listProjectRuntimes, getCurrentProjectRuntime, archiveMissingProjectRuntimes } = require("../../runtime/projects/registry");
19
20
  const { canonicalProjectRoot, buildProjectId } = require("../../runtime/projects/projectId");
20
21
  const { getUfooPaths } = require("../../coordination/state/paths");
21
22
  const { resolveNodeExecutable } = require("../../runtime/process/nodeExecutable");
@@ -148,41 +149,6 @@ async function sendDaemonRequest(projectRoot, payload) {
148
149
  });
149
150
  }
150
151
 
151
- async function sendAgentReportRequest(projectRoot, report) {
152
- const { normalizeReportInput } = require("../../coordination/report/store");
153
- const { enqueueAgentReport } = require("../../runtime/daemon/reportControlBus");
154
- const entry = normalizeReportInput(report);
155
- const queued = await enqueueAgentReport(projectRoot, entry);
156
- return {
157
- type: "response",
158
- data: {
159
- reply: `Report queued (${entry.phase})`,
160
- report: entry,
161
- queued,
162
- },
163
- };
164
- }
165
-
166
- function getReportDetail(out = {}) {
167
- if (out.phase === "error") {
168
- return out.error || out.summary || out.message || out.task_id;
169
- }
170
- return out.summary || out.message || out.task_id;
171
- }
172
-
173
- function printReportOutput(out, json = false, queued = null) {
174
- if (json) {
175
- console.log(JSON.stringify({
176
- status: "queued",
177
- report: out,
178
- queued,
179
- }, null, 2));
180
- return;
181
- }
182
- const detail = getReportDetail(out);
183
- console.log(`[report] queued ${out.phase} ${out.agent_id} ${out.task_id} ${detail}`);
184
- }
185
-
186
152
  function requireOptional(name) {
187
153
  try {
188
154
  // eslint-disable-next-line global-require, import/no-dynamic-require
@@ -487,6 +453,7 @@ function runMemoryCommand({
487
453
  function runProjectCommand({
488
454
  subcommand = "list",
489
455
  outputJson = false,
456
+ apply = false,
490
457
  cwd = process.cwd(),
491
458
  write = (line) => console.log(line),
492
459
  writeError = (line) => console.error(line),
@@ -512,12 +479,21 @@ function runProjectCommand({
512
479
  printCurrentProject(current, write);
513
480
  return 0;
514
481
  }
482
+ if (sub === "prune") {
483
+ const result = archiveMissingProjectRuntimes({ dryRun: !apply });
484
+ if (outputJson) write(JSON.stringify({ ...result, dry_run: !apply }, null, 2));
485
+ else {
486
+ write(`${apply ? "Archived" : "Would archive"} ${result.count} abandoned project record(s).`);
487
+ write(apply ? `Archive: ${result.archive_dir}` : "Use --apply to archive these records; existing workspaces and live daemons are retained.");
488
+ }
489
+ return 0;
490
+ }
515
491
  if (sub === "switch") {
516
492
  const err = projectSwitchV1Error();
517
493
  writeError(err.message);
518
494
  return err.exitCode || 2;
519
495
  }
520
- writeError("project requires list|current|switch subcommand");
496
+ writeError("project requires list|current|prune|switch subcommand");
521
497
  return 1;
522
498
  } catch (err) {
523
499
  writeError(err.message || String(err));
@@ -650,6 +626,14 @@ async function runCli(argv) {
650
626
  cwd: process.cwd(),
651
627
  });
652
628
  });
629
+ project
630
+ .command("prune")
631
+ .description("Archive abandoned registrations for deleted workspaces")
632
+ .option("--apply", "Move records into the recoverable archive (default: preview)")
633
+ .option("--json", "Output as JSON")
634
+ .action((opts) => {
635
+ process.exitCode = runProjectCommand({ subcommand: "prune", apply: opts.apply === true, outputJson: opts.json === true });
636
+ });
653
637
  project
654
638
  .command("switch")
655
639
  .description("Switch active project (chat-only in v1)")
@@ -787,7 +771,7 @@ async function runCli(argv) {
787
771
  normalizedAgent = "grok";
788
772
  } else if (agentLower === "ukimi" || agentLower === "kimi" || agentLower === "kimi-cli" || agentLower === "kimi-code") {
789
773
  normalizedAgent = "kimi";
790
- } else if (agentLower === "ucode" || agentLower === "ufoo-code" || agentLower === "ufoo") {
774
+ } else if (agentLower === "ucode") {
791
775
  normalizedAgent = "ucode";
792
776
  } else {
793
777
  console.error(`Unknown agent type: ${agent}`);
@@ -861,7 +845,7 @@ async function runCli(argv) {
861
845
  }
862
846
  const resp = await sendDaemonRequest(projectRoot, {
863
847
  type: "launch_agent",
864
- agent: agent === "ucode" ? "ufoo" : agent,
848
+ agent,
865
849
  nickname: String(opts.nickname || "").trim(),
866
850
  prompt_profile: promptProfile,
867
851
  count: 1,
@@ -1043,7 +1027,7 @@ async function runCli(argv) {
1043
1027
  }
1044
1028
 
1045
1029
  const agentId = String(opts.agent || process.env.UFOO_SUBSCRIBER_ID || "unknown-agent").trim() || "unknown-agent";
1046
- const taskId = String(opts.task || `task-${Date.now()}`).trim();
1030
+ const taskId = String(opts.task || "").trim();
1047
1031
  const summary = String(opts.summary || (normalized === "done" ? text : "")).trim();
1048
1032
  const error = String(opts.error || (normalized === "error" ? text : "")).trim();
1049
1033
  const report = {
@@ -1515,6 +1499,21 @@ async function runCli(argv) {
1515
1499
  });
1516
1500
 
1517
1501
  const bus = program.command("bus").description("Project bus commands");
1502
+ bus
1503
+ .command("deliveries")
1504
+ .description("Inspect native receipts or explicitly resolve an uncertain delivery")
1505
+ .argument("<subscriber>", "Subscriber ID")
1506
+ .argument("[receipt-id]", "Uncertain receipt ID")
1507
+ .argument("[resolution]", "accepted|retry (retry can duplicate already accepted work)")
1508
+ .action(async (subscriber, id, resolution) => {
1509
+ const EventBus = require("../../coordination/bus");
1510
+ try {
1511
+ await runBusCoreCommand(new EventBus(process.cwd()), "deliveries", [subscriber, id, resolution].filter(Boolean));
1512
+ } catch (error) {
1513
+ console.error(error.message);
1514
+ process.exitCode = 1;
1515
+ }
1516
+ });
1518
1517
  bus
1519
1518
  .command("alert")
1520
1519
  .description("Start/stop background notification daemon")
@@ -1703,6 +1702,35 @@ async function runCli(argv) {
1703
1702
  }
1704
1703
  });
1705
1704
 
1705
+ program.command("trace").description("Inspect agent task, tool, report, queue and compaction events")
1706
+ .argument("[task-id]", "Delegated task ID or parent taskRunId")
1707
+ .option("--task <id>", "Filter task")
1708
+ .option("--agent <id>", "Filter subscriber ID or nickname")
1709
+ .option("--session <id>", "Filter runtime session")
1710
+ .option("--project <path>", "Project root (defaults to cwd)")
1711
+ .option("--since <time>", "ISO timestamp lower bound")
1712
+ .option("--limit <n>", "Maximum events (default: 200, follow: 2000)")
1713
+ .option("--offset <n>", "Oldest-first pagination offset; default shows newest events")
1714
+ .option("--details", "Include redacted arguments and results")
1715
+ .option("--json", "JSON output; with --follow emits JSONL")
1716
+ .option("--follow", "Observe new local events without model calls")
1717
+ .action((taskId, opts) => require("./traceCommands").runTraceCommand(taskId, opts));
1718
+
1719
+ program.command("metrics").description("Summarize observed agent performance without model calls")
1720
+ .argument("[task-id]", "Delegated task ID or parent taskRunId")
1721
+ .option("--task <id>", "Filter task")
1722
+ .option("--agent <id>", "Filter subscriber ID or nickname")
1723
+ .option("--session <id>", "Filter runtime session")
1724
+ .option("--project <path>", "Project root (defaults to cwd)")
1725
+ .option("--since <time>", "Include runs starting at or after ISO timestamp")
1726
+ .option("--until <time>", "Include runs starting before ISO timestamp")
1727
+ .option("--provider <name>", "Filter observed model provider")
1728
+ .option("--model <name>", "Filter observed model")
1729
+ .option("--limit <n>", "Recent run records to return (default: 20; maximum: 100)")
1730
+ .option("--baseline <path>", "Compare with a saved metrics JSON report")
1731
+ .option("--json", "Export a performance report")
1732
+ .action((taskId, opts) => require("./metricsCommands").runMetricsCommand(taskId, opts));
1733
+
1706
1734
  const history = program.command("history").description("Agent input history timeline");
1707
1735
  history
1708
1736
  .command("build")
@@ -1770,6 +1798,7 @@ async function runCli(argv) {
1770
1798
  console.log(" ufoo -g");
1771
1799
  console.log(" ufoo chat [-g]");
1772
1800
  console.log(" ufoo project list [--json]");
1801
+ console.log(" ufoo project prune [--apply] [--json]");
1773
1802
  console.log(" ufoo project current [--json]");
1774
1803
  console.log(" ufoo project switch <index|path>");
1775
1804
  console.log(" ufoo resume [nickname]");
@@ -1802,6 +1831,7 @@ async function runCli(argv) {
1802
1831
  console.log(" ufoo bus <args...> (JS bus implementation)");
1803
1832
  console.log(" ufoo ctx <subcmd> ... (doctor|lint|decisions|sync)");
1804
1833
  console.log(" ufoo history <build|show|prompt> [limit]");
1834
+ console.log(" ufoo trace [task-id] [--agent <id>] [--project <dir>] [--json] [--follow] [--details]");
1805
1835
  console.log("");
1806
1836
  console.log("Notes:");
1807
1837
  console.log(" - For Codex notifications, use ufoo bus alert / ufoo bus listen");
@@ -1857,6 +1887,7 @@ async function runCli(argv) {
1857
1887
  process.exitCode = runProjectCommand({
1858
1888
  subcommand: sub,
1859
1889
  outputJson,
1890
+ apply: rest.includes("--apply"),
1860
1891
  cwd: process.cwd(),
1861
1892
  });
1862
1893
  return;
@@ -1935,6 +1966,15 @@ async function runCli(argv) {
1935
1966
  })();
1936
1967
  return;
1937
1968
  }
1969
+ if (cmd === "trace") {
1970
+ const value = name => { const i = rest.indexOf(`--${name}`); return i < 0 ? undefined : rest[i + 1]; };
1971
+ const task = rest[0]?.startsWith("--") ? "" : rest[0];
1972
+ try { require("./traceCommands").runTraceCommand(task, {
1973
+ task: value("task"), agent: value("agent"), session: value("session"), project: value("project"), since: value("since"),
1974
+ limit: value("limit"), offset: value("offset"), json: rest.includes("--json"), follow: rest.includes("--follow"), details: rest.includes("--details"),
1975
+ }); } catch (error) { console.error(error.message); process.exitCode = 1; }
1976
+ return;
1977
+ }
1938
1978
  if (cmd === "report") {
1939
1979
  const action = String(rest[0] || "").toLowerCase();
1940
1980
  const normalized = normalizeReportPhase(action);
@@ -2016,7 +2056,7 @@ async function runCli(argv) {
2016
2056
 
2017
2057
  const report = {
2018
2058
  phase: normalized,
2019
- task_id: getOpt("--task", `task-${Date.now()}`),
2059
+ task_id: getOpt("--task", ""),
2020
2060
  agent_id: getOpt("--agent", process.env.UFOO_SUBSCRIBER_ID || "unknown-agent"),
2021
2061
  message,
2022
2062
  summary: getOpt("--summary", normalized === "done" ? message : ""),
@@ -2344,7 +2384,7 @@ async function runCli(argv) {
2344
2384
  const agent = resolveSoloAgentType(config, agentInput);
2345
2385
  const resp = await sendDaemonRequest(projectRoot, {
2346
2386
  type: "launch_agent",
2347
- agent: agent === "ucode" ? "ufoo" : agent,
2387
+ agent,
2348
2388
  nickname,
2349
2389
  prompt_profile: profile,
2350
2390
  count: 1,
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ const { readAgentTrace } = require("../../coordination/history/agentTrace");
3
+ function runTraceCommand(taskId, options = {}) {
4
+ const query = { task_id: options.task || taskId || "", agent_id: options.agent, session_id: options.session, since: options.since,
5
+ limit: options.limit || (options.follow ? 2000 : 200), offset: options.offset, details: options.details === true };
6
+ const root = options.project || process.cwd();
7
+ const seen = new Set();
8
+ let state = "";
9
+ const emit = () => {
10
+ const result = readAgentTrace(root, query);
11
+ if (options.json && !options.follow) { console.log(JSON.stringify(result, null, 2)); return; }
12
+ const signature = JSON.stringify({ tasks: result.tasks.map(t => [t.taskId || t.id, t.status, t.reportPhase || t.report?.phase]),
13
+ counts: result.counts, outcomes: result.performance.summary.outcomes, queues: result.queues, warnings: result.warnings });
14
+ if (signature !== state) {
15
+ if (options.json) console.log(JSON.stringify({ type: "trace.state", projectRoot: result.projectRoot, tasks: result.tasks,
16
+ counts: result.counts, performance: result.performance, queues: result.queues, warnings: result.warnings }));
17
+ else console.log(`Trace: ${result.total} events; ${result.tasks.map(t => `${t.taskId || t.id}=${t.status}`).join(", ") || "no delegated tasks"}${result.incomplete ? " (partial sources; use --json for warnings)" : ""}`);
18
+ state = signature;
19
+ }
20
+ for (const e of result.events) {
21
+ if (seen.has(e.id)) continue;
22
+ seen.add(e.id);
23
+ console.log(options.json ? JSON.stringify(e) : `${e.time} ${e.agentId || "runtime"} ${e.type} ${e.toolName || ""} ${e.summary || ""}${e.durationMs === undefined ? "" : ` (${e.durationMs}ms)`}`);
24
+ if (!options.json && options.details && (e.args || e.result)) console.log(JSON.stringify({ args: e.args, result: e.result }));
25
+ }
26
+ // Bound a long-lived follower's memory; retain the most recent event IDs.
27
+ if (seen.size > 10000) for (const id of [...seen].slice(0, seen.size - 10000)) seen.delete(id);
28
+ };
29
+ emit();
30
+ if (!options.follow) return;
31
+ const timer = setInterval(() => { try { emit(); } catch (error) { console.error(error.message); } }, 1000);
32
+ const stop = () => { clearInterval(timer); process.removeListener("SIGINT", stop); process.removeListener("SIGTERM", stop); };
33
+ process.once("SIGINT", stop); process.once("SIGTERM", stop);
34
+ return stop;
35
+ }
36
+ module.exports = { runTraceCommand };
package/src/code/agent.js CHANGED
@@ -3,6 +3,7 @@ const path = require("path");
3
3
  const { randomUUID } = require("crypto");
4
4
  const { runToolCall } = require("./dispatch");
5
5
  const { runNativeAgentTask } = require("./nativeRunner");
6
+ const { resolveTaskTimeoutMs: resolveNlTaskTimeoutMs, DEFAULT_TASK_TIMEOUT_MS: DEFAULT_NL_TASK_TIMEOUT_MS } = require("../agents/runtime/core/executionBudget");
6
7
  const { runDecomposedTask } = require("./taskDecomposer");
7
8
  const { loadConfig, defaultAgentModelForProvider, sameModelProvider } = require("../config");
8
9
  const {
@@ -11,7 +12,8 @@ const {
11
12
  saveSessionSnapshot,
12
13
  loadSessionSnapshot,
13
14
  } = require("./sessionStore");
14
- const { buildSkillInjections } = require("./skills");
15
+ const { createSkillsCapability } = require("../agents/capabilities/skills");
16
+ const skillContextSource = createSkillsCapability().contextSources[0];
15
17
  const {
16
18
  assembleModelContext,
17
19
  applyContextSideEffects,
@@ -335,18 +337,6 @@ function computeExtendedTimeout(baseTimeoutMs) {
335
337
  return Math.min(43200000, Math.max(base * 2, base + 120000));
336
338
  }
337
339
 
338
- // Reasoning models routinely blew the old 10min budget across a multi-turn
339
- // tool loop. Total per-task budget defaults to 12h and can be raised per
340
- // call, via --timeout-ms, or via UFOO_UCODE_TASK_TIMEOUT_MS.
341
- const DEFAULT_NL_TASK_TIMEOUT_MS = 43200000;
342
-
343
- function resolveNlTaskTimeoutMs(value) {
344
- if (Number.isFinite(value) && value > 0) return Math.max(1000, Math.floor(value));
345
- const env = Number(process.env.UFOO_UCODE_TASK_TIMEOUT_MS);
346
- if (Number.isFinite(env) && env > 0) return Math.max(1000, Math.floor(env));
347
- return DEFAULT_NL_TASK_TIMEOUT_MS;
348
- }
349
-
350
340
  function enrichNativeError(errorMessage = "") {
351
341
  const text = String(errorMessage || "").trim();
352
342
  if (!text) return "nl task failed";
@@ -362,7 +352,7 @@ function enrichNativeError(errorMessage = "") {
362
352
  return `${text}. Network connection to provider failed. Check VPN/proxy/network and verify endpoint/key via /settings ucode show.`;
363
353
  }
364
354
  if (lower.includes("model is not configured")) {
365
- return `${text}. Configure ucode with /settings ucode set provider=<openai|anthropic> model=<id> key=<apiKey> [url=<baseUrl>]`;
355
+ return `${text}. Configure ucode with /settings ucode set provider=openai model=<id> key=<apiKey> [url=<baseUrl>]`;
366
356
  }
367
357
  if (lower.includes("baseurl is not configured")) {
368
358
  return `${text}. Configure endpoint with /settings ucode set url=<baseUrl> (and key/model if missing).`;
@@ -570,7 +560,7 @@ async function runNaturalLanguageTask(task = "", state = {}, options = {}) {
570
560
  const taskPrompt = analysisTask
571
561
  ? `${taskText}\n\nAnalysis requirements:\n- Inspect repository evidence before concluding.\n- Cite concrete file observations.\n- Keep findings concise and actionable.`
572
562
  : taskText;
573
- const skillInjections = buildSkillInjections({
563
+ const skillInjections = skillContextSource({
574
564
  prompt: taskPrompt,
575
565
  workspaceRoot,
576
566
  sessionId: String(state.sessionId || ""),
@@ -674,9 +664,13 @@ async function runNaturalLanguageTask(task = "", state = {}, options = {}) {
674
664
  onContextUsage: applyContextMeter,
675
665
  executionState: state.executionState || null,
676
666
  onArtifactPersisted: (persisted) => recordToolCallInSession(state, persisted, workspaceRoot),
667
+ contextPolicy: state.contextPolicy || {},
668
+ runtimeContext: options.runtimeContext || {},
669
+ onRuntimeEvent: options.onRuntimeEvent,
677
670
  onToolEvent: (event) => {
678
671
  toolEventsThisAttempt += 1;
679
672
  pushToolLog(event);
673
+ if (typeof options.onToolEvent === "function") options.onToolEvent(event);
680
674
  },
681
675
  signal: options.signal,
682
676
  });
@@ -715,7 +709,10 @@ async function runNaturalLanguageTask(task = "", state = {}, options = {}) {
715
709
  const decomposedResult = await runDecomposedTask({
716
710
  task: effectiveTaskPrompt,
717
711
  onProgress: options.onProgress,
718
- onToolEvent: pushToolLog,
712
+ onToolEvent: (event) => {
713
+ pushToolLog(event);
714
+ if (typeof options.onToolEvent === "function") options.onToolEvent(event);
715
+ },
719
716
  signal: options.signal,
720
717
  workspaceRoot,
721
718
  provider,
@@ -725,6 +722,13 @@ async function runNaturalLanguageTask(task = "", state = {}, options = {}) {
725
722
  sessionId: String(state.sessionId || ""),
726
723
  state,
727
724
  systemBlocks: assembled.systemBlocks || null,
725
+ runtimeContext: options.runtimeContext || {},
726
+ onRuntimeEvent: options.onRuntimeEvent,
727
+ onStreamDelta: onStream,
728
+ onThinkingDelta,
729
+ onPhase,
730
+ onContextUsage: applyContextMeter,
731
+ contextPolicy: state.contextPolicy || {},
728
732
  });
729
733
 
730
734
  if (decomposedResult.ok) {
@@ -844,6 +848,7 @@ async function runNaturalLanguageTask(task = "", state = {}, options = {}) {
844
848
  return {
845
849
  ok: true,
846
850
  summary: resolvedSummary || "Waiting for your reply",
851
+ finalText: typeof cliRes.finalText === "string" ? extractJsonSummary(cliRes.finalText) : undefined,
847
852
  artifacts: artifactIds,
848
853
  logs: logs.slice(),
849
854
  error: "",
@@ -859,6 +864,7 @@ async function runNaturalLanguageTask(task = "", state = {}, options = {}) {
859
864
  return {
860
865
  ok: true,
861
866
  summary: resolvedSummary,
867
+ finalText: typeof cliRes.finalText === "string" ? extractJsonSummary(cliRes.finalText) : undefined,
862
868
  artifacts: artifactIds,
863
869
  logs: logs.slice(),
864
870
  error: "",
@@ -1178,9 +1184,19 @@ async function resumeAfterUserInteraction(answerText = "", state = {}, options =
1178
1184
  systemBlocks: assembled.systemBlocks || null,
1179
1185
  messages,
1180
1186
  sessionId: String(state.sessionId || ""),
1181
- onToolEvent: pushToolLog,
1187
+ onToolEvent: (event) => {
1188
+ pushToolLog(event);
1189
+ if (typeof options.onToolLog === "function") {
1190
+ const log = normalizeToolLogEvent(event);
1191
+ if (log) options.onToolLog(log);
1192
+ }
1193
+ if (typeof options.onToolEvent === "function") options.onToolEvent(event);
1194
+ },
1182
1195
  maxToolCalls: state.maxToolCalls,
1183
1196
  onStreamDelta: trackingOnDelta,
1197
+ contextPolicy: state.contextPolicy || {},
1198
+ runtimeContext: options.runtimeContext || {},
1199
+ onRuntimeEvent: options.onRuntimeEvent,
1184
1200
  onThinkingDelta: typeof options.onThinkingDelta === "function" ? options.onThinkingDelta : null,
1185
1201
  onPhase: typeof options.onPhase === "function" ? options.onPhase : null,
1186
1202
  onContextUsage: (meter) => {
@@ -1254,6 +1270,7 @@ async function resumeAfterUserInteraction(answerText = "", state = {}, options =
1254
1270
  return {
1255
1271
  ok: true,
1256
1272
  summary: String(cliRes.output || "").trim() || "continued",
1273
+ finalText: typeof cliRes.finalText === "string" ? extractJsonSummary(cliRes.finalText) : undefined,
1257
1274
  logs,
1258
1275
  waitingUserInteraction: false,
1259
1276
  streamed: Boolean(cliRes.streamed),
@@ -221,9 +221,7 @@ function extractTaskFromBusEvent(evt) {
221
221
  function shouldAutoConsumeBus(subscriberId = "") {
222
222
  const id = String(subscriberId || "").trim().toLowerCase();
223
223
  if (!id) return false;
224
- return id.startsWith("ufoo-code:")
225
- || id.startsWith("ucode:")
226
- || id.startsWith("ufoo:");
224
+ return id.startsWith("ucode:");
227
225
  }
228
226
 
229
227
  function extractBusMessageTask(contentRaw = "") {
@@ -72,7 +72,7 @@ function listUcodeCommandsForHelp() {
72
72
  " /ubus",
73
73
  " /status",
74
74
  " /queue [status|clear|cancel|stop]",
75
- " /model [model-id] [off|low|medium|high|max]",
75
+ " /model [model-id] [off|low|medium|high|xhigh|max]",
76
76
  " /plan [on|off|show|hide|focus|debug|clear]",
77
77
  " /skills [list]",
78
78
  " /skills show <name>",
@@ -5,11 +5,12 @@ const path = require("path");
5
5
  const crypto = require("crypto");
6
6
  const { randomUUID } = require("crypto");
7
7
 
8
- function getArtifactsDir(workspaceRoot = process.cwd(), sessionId = "") {
8
+ function getArtifactsDir(workspaceRoot = process.cwd(), sessionId = "", namespace = "ucode") {
9
9
  const root = path.resolve(workspaceRoot || process.cwd());
10
10
  const id = String(sessionId || "").trim();
11
- if (!id) return path.join(root, ".ufoo", "agent", "ucode", "artifacts");
12
- return path.join(root, ".ufoo", "agent", "ucode", "artifacts", id);
11
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(namespace) || id && !/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/.test(id)) throw new Error("invalid artifact storage identity");
12
+ if (!id) return path.join(root, ".ufoo", "agent", namespace, "artifacts");
13
+ return path.join(root, ".ufoo", "agent", namespace, "artifacts", id);
13
14
  }
14
15
 
15
16
  function createArtifactId(prefix = "artifact") {
@@ -21,10 +22,10 @@ function hashContent(value = "") {
21
22
  return crypto.createHash("sha256").update(String(value || ""), "utf8").digest("hex").slice(0, 16);
22
23
  }
23
24
 
24
- function getArtifactFilePath(workspaceRoot = process.cwd(), sessionId = "", artifactId = "") {
25
+ function getArtifactFilePath(workspaceRoot = process.cwd(), sessionId = "", artifactId = "", namespace = "ucode") {
25
26
  const id = String(artifactId || "").trim();
26
- if (!id) return "";
27
- return path.join(getArtifactsDir(workspaceRoot, sessionId), `${id}.json`);
27
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/.test(id)) return "";
28
+ return path.join(getArtifactsDir(workspaceRoot, sessionId, namespace), `${id}.json`);
28
29
  }
29
30
 
30
31
  function buildArtifactRecord({
@@ -66,15 +67,15 @@ function buildArtifactRecord({
66
67
  };
67
68
  }
68
69
 
69
- function saveArtifact(workspaceRoot = process.cwd(), sessionId = "", record = {}) {
70
+ function saveArtifact(workspaceRoot = process.cwd(), sessionId = "", record = {}, options = {}) {
70
71
  const payload = buildArtifactRecord(record);
71
- const filePath = getArtifactFilePath(workspaceRoot, sessionId, payload.artifactId);
72
+ const filePath = getArtifactFilePath(workspaceRoot, sessionId, payload.artifactId, options.namespace || "ucode");
72
73
  if (!filePath) {
73
74
  return { ok: false, error: "invalid artifact id", artifact: null };
74
75
  }
75
76
  try {
76
77
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
77
- fs.writeFileSync(filePath, `${JSON.stringify(payload, null, 2)}\n`, "utf8");
78
+ fs.writeFileSync(filePath, `${JSON.stringify(payload, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
78
79
  return { ok: true, error: "", artifact: payload, filePath };
79
80
  } catch (err) {
80
81
  return {
@@ -86,8 +87,8 @@ function saveArtifact(workspaceRoot = process.cwd(), sessionId = "", record = {}
86
87
  }
87
88
  }
88
89
 
89
- function loadArtifact(workspaceRoot = process.cwd(), sessionId = "", artifactId = "") {
90
- const filePath = getArtifactFilePath(workspaceRoot, sessionId, artifactId);
90
+ function loadArtifact(workspaceRoot = process.cwd(), sessionId = "", artifactId = "", options = {}) {
91
+ const filePath = getArtifactFilePath(workspaceRoot, sessionId, artifactId, options.namespace || "ucode");
91
92
  if (!filePath || !fs.existsSync(filePath)) {
92
93
  return { ok: false, error: `artifact not found: ${artifactId}`, artifact: null, filePath };
93
94
  }