u-foo 4.0.5 → 4.0.10

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 (149) hide show
  1. package/README.md +224 -19
  2. package/README.zh-CN.md +3 -3
  3. package/bin/ucode.js +10 -2
  4. package/bin/ufoo.js +3 -0
  5. package/dist/tui/darwin-arm64/ufoo-tui +0 -0
  6. package/dist/tui/darwin-x64/ufoo-tui +0 -0
  7. package/dist/tui/linux-arm64/ufoo-tui +0 -0
  8. package/dist/tui/linux-x64/ufoo-tui +0 -0
  9. package/{OBSERVABILITY.md → docs/OBSERVABILITY.md} +3 -3
  10. package/docs/README.md +27 -0
  11. package/extensions/ufoo-browser/LICENSE +152 -0
  12. package/extensions/ufoo-browser/NOTICE +10 -0
  13. package/extensions/ufoo-browser/README.md +30 -0
  14. package/extensions/ufoo-browser/background.js +409 -0
  15. package/extensions/ufoo-browser/icons/icon-128.png +0 -0
  16. package/extensions/ufoo-browser/icons/icon-16.png +0 -0
  17. package/extensions/ufoo-browser/icons/icon-256.png +0 -0
  18. package/extensions/ufoo-browser/icons/icon-32.png +0 -0
  19. package/extensions/ufoo-browser/icons/icon-48.png +0 -0
  20. package/extensions/ufoo-browser/icons/logo.png +0 -0
  21. package/extensions/ufoo-browser/icons/toolbar-16.png +0 -0
  22. package/extensions/ufoo-browser/icons/toolbar-32.png +0 -0
  23. package/extensions/ufoo-browser/icons/toolbar-logo.png +0 -0
  24. package/extensions/ufoo-browser/manifest.json +30 -0
  25. package/extensions/ufoo-browser/popup.css +71 -0
  26. package/extensions/ufoo-browser/popup.html +44 -0
  27. package/extensions/ufoo-browser/popup.js +153 -0
  28. package/package.json +5 -3
  29. package/scripts/postinstall.js +6 -0
  30. package/src/agents/capabilities/browser/index.js +49 -0
  31. package/src/agents/capabilities/coding/backgroundHooks.js +94 -0
  32. package/src/agents/capabilities/coding/index.js +30 -1
  33. package/src/agents/capabilities/index.js +5 -2
  34. package/src/agents/capabilities/planning/index.js +44 -5
  35. package/src/agents/capabilities/turnRecall/index.js +341 -0
  36. package/src/agents/controller/controllerToolExecutor.js +2 -2
  37. package/src/agents/internal/internalRunner.js +30 -8
  38. package/src/agents/internal/taskControl.js +107 -0
  39. package/src/agents/profiles/coding.js +1 -1
  40. package/src/agents/profiles/main.js +1 -1
  41. package/src/agents/prompts/mainAgent.js +1 -0
  42. package/src/agents/prompts/native/toolDescriptions/bash.js +7 -1
  43. package/src/agents/providers/claudeSessionFiles.js +1 -1
  44. package/src/agents/providers/codexThreadProvider.js +6 -1
  45. package/src/agents/providers/credentials/agy.js +171 -0
  46. package/src/agents/providers/directAuthStatus.js +20 -2
  47. package/src/agents/providers/modelsCatalog.js +26 -5
  48. package/src/agents/providers/nativeTransport.js +36 -20
  49. package/src/agents/providers/providerId.js +17 -0
  50. package/src/agents/providers/runtimeConfig.js +26 -19
  51. package/src/agents/providers/transports/antigravityTransport.js +242 -0
  52. package/src/agents/providers/transports/index.js +1 -0
  53. package/src/agents/providers/transports/openaiChatTransport.js +3 -2
  54. package/src/agents/providers/transports/openaiResponsesTransport.js +2 -1
  55. package/src/agents/providers/transports/responsesProtocol.js +119 -18
  56. package/src/agents/providers/transports/transportContract.js +1 -0
  57. package/src/agents/providers/upstreamRuntime.js +3 -1
  58. package/src/agents/runtime/context/contextBudget.js +1 -19
  59. package/src/agents/runtime/context/contextWindow.js +5 -0
  60. package/src/agents/runtime/context/replayHistory.js +16 -10
  61. package/src/agents/runtime/context/runtimeStore.js +0 -2
  62. package/src/agents/runtime/context/sessionJournal.js +1 -1
  63. package/src/agents/runtime/context/slidingWindowManager.js +792 -0
  64. package/src/agents/runtime/context/topicSelector.js +338 -0
  65. package/src/agents/runtime/context/turnAnalyzer.js +767 -0
  66. package/src/agents/runtime/context/turnIndexStore.js +515 -0
  67. package/src/agents/runtime/core/agentLoop.js +95 -32
  68. package/src/agents/runtime/core/executionBudget.js +2 -1
  69. package/src/agents/runtime/core/toolErrorGuard.js +39 -0
  70. package/src/agents/runtime/createAgentRuntime.js +80 -7
  71. package/src/agents/runtime/index.js +5 -0
  72. package/src/agents/runtime/protocol/materialize.js +1 -1
  73. package/src/agents/runtime/tasks/hooks.js +137 -0
  74. package/src/app/chat/ChatController.js +8 -4
  75. package/src/app/chat/daemonMessageRouter.js +3 -1
  76. package/src/app/chat/inputSubmitHandler.js +2 -2
  77. package/src/app/chat/transport.js +1 -1
  78. package/src/app/cli/browserCommands.js +340 -0
  79. package/src/app/cli/features/doctor.js +21 -0
  80. package/src/app/cli/metricsCommands.js +1 -1
  81. package/src/app/cli/run.js +80 -1
  82. package/src/app/cli/setupCommands.js +200 -0
  83. package/src/code/UcodeController.js +31 -1
  84. package/src/code/agent.js +41 -7
  85. package/src/code/busConsumer.js +13 -12
  86. package/src/code/commands.js +0 -1
  87. package/src/code/context/assembler.js +11 -88
  88. package/src/code/context/planGraphService.js +83 -9
  89. package/src/code/context/planProjection.js +10 -2
  90. package/src/code/context/reducers.js +172 -4
  91. package/src/code/context/stateCommit.js +0 -32
  92. package/src/code/context/transcript.js +7 -4
  93. package/src/code/internalThread.js +9 -1
  94. package/src/code/launcher/ucode.js +4 -2
  95. package/src/code/nativeRunner.js +221 -10
  96. package/src/code/repl.js +27 -1
  97. package/src/code/runtime/agentWakeup.js +20 -3
  98. package/src/code/runtime/backgroundWakeHost.js +45 -0
  99. package/src/code/runtime/taskFocusContext.js +7 -0
  100. package/src/code/runtime/taskLoop.js +24 -1
  101. package/src/code/sessionStore.js +14 -10
  102. package/src/code/taskDecomposer.js +13 -7
  103. package/src/code/tools/backgroundProcess.js +23 -0
  104. package/src/code/tools/bash.js +764 -12
  105. package/src/code/tools/executor.js +12 -4
  106. package/src/code/tools/specs.js +60 -3
  107. package/src/code/tools/taskRun.js +38 -0
  108. package/src/config.js +92 -6
  109. package/src/coordination/bus/subscriber.js +1 -1
  110. package/src/coordination/history/agentPerformance.js +18 -18
  111. package/src/coordination/history/agentTrace.js +7 -3
  112. package/src/coordination/state/workspaceAccess.js +3 -1
  113. package/src/orchestration/groups/modelConfig.js +66 -0
  114. package/src/orchestration/groups/validateTemplate.js +2 -0
  115. package/src/runtime/browser/broker.js +1027 -0
  116. package/src/runtime/browser/brokerClient.js +108 -0
  117. package/src/runtime/browser/componentInstaller.js +275 -0
  118. package/src/runtime/browser/installState.js +329 -0
  119. package/src/runtime/browser/manifest.js +145 -0
  120. package/src/runtime/browser/native-host-runner.js +198 -0
  121. package/src/runtime/browser/nativeHost.js +213 -0
  122. package/src/runtime/browser/nativeMessagingProtocol.js +50 -0
  123. package/src/runtime/browser/paths.js +134 -0
  124. package/src/runtime/browser/playwrightSession.js +614 -0
  125. package/src/runtime/daemon/agentHost.js +175 -30
  126. package/src/runtime/daemon/busBridge.js +2 -1
  127. package/src/runtime/daemon/globalDaemon.js +20 -0
  128. package/src/runtime/daemon/groupOrchestrator.js +20 -1
  129. package/src/runtime/daemon/index.js +5 -4
  130. package/src/runtime/daemon/ops.js +14 -8
  131. package/src/tools/handlers/listAgents.js +1 -1
  132. package/src/tools/handlers/readBusSummary.js +1 -1
  133. package/src/tools/handlers/routeAgent.js +122 -5
  134. package/src/tools/schemaFixtures.js +1 -1
  135. package/src/ui/agentSurface.js +26 -3
  136. package/src/ui/format/index.js +34 -2
  137. package/src/ui/rustChatHost.js +22 -7
  138. package/src/ui/rustMultiSession.js +14 -2
  139. package/src/ui/rustUcodeHost.js +246 -77
  140. package/src/ui/ucodeAgentSession.js +88 -0
  141. package/templates/groups/build-lane.json +57 -3
  142. package/templates/groups/build-ultra.json +114 -6
  143. package/templates/groups/design-system.json +57 -3
  144. package/templates/groups/product-discovery.json +57 -3
  145. package/templates/groups/ui-plan-review.json +57 -3
  146. package/templates/groups/ui-polish.json +57 -3
  147. package/templates/groups/verify-ship.json +57 -3
  148. package/src/agents/runtime/context/checkpointStore.js +0 -52
  149. package/src/agents/runtime/context/compaction.js +0 -171
@@ -7,7 +7,10 @@ const { createAgentRuntime } = require("../agents/runtime/createAgentRuntime");
7
7
  const { createCodingCapability } = require("../agents/capabilities/coding");
8
8
  const { createPlanningCapability } = require("../agents/capabilities/planning");
9
9
  const { createSkillsCapability } = require("../agents/capabilities/skills");
10
+ const { createTurnRecallCapability } = require("../agents/capabilities/turnRecall");
11
+ const { createBrowserCapability } = require("../agents/capabilities/browser");
10
12
  const codingProfile = require("../agents/profiles/coding");
13
+ const { loadConfig, defaultAuxModelForProvider, sameModelProvider } = require("../config");
11
14
  const { runCoreToolAsync } = require("./tools/executor");
12
15
  const { sanitizeModelMessages } = require("./context/assembler");
13
16
  const { retireMessageImages } = require("../agents/providers/transports/visionBlocks");
@@ -16,8 +19,10 @@ const { clearUserPrompts } = require("./context/userNudge");
16
19
  const { runProviderTurnGate, resolveCall, checkFaultPoint, materializeAnswerToolResult } = require("./protocol");
17
20
  const { appendUsageRecord } = require("./usageStore");
18
21
  const { buildCoreToolSpecs, buildAnthropicToolSpecs } = require("./tools/specs");
19
- const { createContextManager } = require("../agents/runtime/context/compaction");
20
- const { createCheckpointStore } = require("../agents/runtime/context/checkpointStore");
22
+ const { createTurnIndexStore } = require("../agents/runtime/context/turnIndexStore");
23
+ const { buildDeterministicTurnRecord, backfillMissingTurns, createAsyncTurnEnricher } = require("../agents/runtime/context/turnAnalyzer");
24
+ const { createTopicSelector } = require("../agents/runtime/context/topicSelector");
25
+ const { createSlidingWindowManager } = require("../agents/runtime/context/slidingWindowManager");
21
26
  const { createRuntimeStore } = require("../agents/runtime/context/runtimeStore");
22
27
  const { normalizeTraceContext } = require("../agents/runtime/protocol/traceContext");
23
28
  const { redactSecrets } = require("../runtime/privacy/redactor");
@@ -49,12 +54,39 @@ function createGuards({ signal = null, timeoutMs = DEFAULT_NATIVE_TIMEOUT_MS } =
49
54
  };
50
55
  }
51
56
 
57
+ function resolveDurableTurnSlice(resultObj = {}, { preTurnOffset = 0, resume = false, promptText = "" } = {}) {
58
+ const runNonSystem = Array.isArray(resultObj.messages)
59
+ ? resultObj.messages.filter((m) => m && m.role !== "system")
60
+ : [];
61
+ const rawSlice = runNonSystem.slice(preTurnOffset);
62
+ if (Array.isArray(resultObj.turnItems) && (resultObj.turnItems.length > 0 || !rawSlice.length)) {
63
+ const candidate = [
64
+ ...(!resume && promptText ? [{ role: "user", content: promptText }] : []),
65
+ ...resultObj.turnItems,
66
+ ];
67
+ const sanitized = sanitizeModelMessages(candidate);
68
+ if (sanitized.length > 0) return sanitized;
69
+ }
70
+ const sanitizedFallback = sanitizeModelMessages(rawSlice);
71
+ if (sanitizedFallback.length > 0) return sanitizedFallback;
72
+ if (!rawSlice.length && !resume && promptText) {
73
+ return [{ role: "user", content: promptText }];
74
+ }
75
+ return rawSlice;
76
+ }
77
+
52
78
  async function runNativeLoop(options = {}) {
53
79
  const runtime = createAgentRuntime({
54
80
  profile: codingProfile,
55
81
  transport: options.transport,
56
- capabilities: [createCodingCapability(), createPlanningCapability(), createSkillsCapability()],
57
- host: { grantedPermissions: ["workspace.read", "workspace.write", "workspace.execute", "execution.control", "interaction.request"] },
82
+ capabilities: [
83
+ createCodingCapability(),
84
+ createPlanningCapability(),
85
+ createSkillsCapability(),
86
+ createTurnRecallCapability({ projectRoot: options.workspaceRoot }, { defaultNamespace: "ucode" }),
87
+ createBrowserCapability(),
88
+ ],
89
+ host: { runtimeHooks: options.runtimeHooks, grantedPermissions: ["workspace.read", "workspace.write", "workspace.execute", "execution.control", "interaction.request", "browser.control"] },
58
90
  defaults: {
59
91
  sanitizeMessages: sanitizeModelMessages,
60
92
  retireImages: retireMessageImages,
@@ -110,16 +142,21 @@ async function runNativeAgentTask({
110
142
  runtimeContext = {},
111
143
  onRuntimeEvent = null,
112
144
  onConversationUpdate = null,
145
+ logicalTurnId = "",
146
+ historyOffset: restoredTurnOffset = null,
147
+ runtimeHooks = null,
113
148
  } = {}) {
114
149
  const guards = createGuards({ signal, timeoutMs });
115
150
  const nextSessionId = String(sessionId || "").trim() || `native-${randomUUID()}`;
116
151
  const promptText = String(prompt || "").trim();
117
152
  const ids = normalizeTraceContext(runtimeContext);
118
- ids.taskRunId ||= `native-run-${randomUUID()}`;
153
+ ids.taskRunId ||= String(logicalTurnId || "").trim() || `native-run-${randomUUID()}`;
119
154
  ids.taskId ||= ids.taskRunId;
120
155
  ids.traceId ||= ids.taskId;
121
156
  ids.requestId ||= ids.taskRunId;
122
157
  ids.attemptId ||= `attempt-${randomUUID()}`;
158
+ const effectiveTurnId = String(logicalTurnId || ids.taskRunId).trim();
159
+ const requestKind = runtimeContext.requestKind || (runtimeContext.taskRunId ? "unknown" : "user");
123
160
  const observation = createRuntimeStore({ workspaceRoot, namespace: "ucode", sessionId: nextSessionId, redact: redactSecrets });
124
161
  const observationWarnings = [];
125
162
  const observe = async event => {
@@ -153,6 +190,11 @@ async function runNativeAgentTask({
153
190
  }
154
191
  };
155
192
 
193
+ let turnIndexStore = null;
194
+ let enricher = null;
195
+ let abortEnricherListener = null;
196
+ let preTurnOffset = 0;
197
+
156
198
  try {
157
199
  await observe({ type: "request.accepted", request: { ...ids, text: promptText } });
158
200
  await observe({ type: "task.started" });
@@ -180,7 +222,97 @@ async function runNativeAgentTask({
180
222
  const transport = getNativeTransport(runtime.transport);
181
223
  await observe({ type: "runtime.binding", binding: { provider: runtime.provider, model: runtime.model, transport: runtime.transport } });
182
224
 
225
+ turnIndexStore = createTurnIndexStore({ workspaceRoot, namespace: "ucode", sessionId: nextSessionId, redact: redactSecrets });
226
+ const productConfig = loadConfig(workspaceRoot);
227
+ const effectivePolicy = {
228
+ ...(productConfig.context && typeof productConfig.context === "object" ? productConfig.context : {}),
229
+ ...(contextPolicy && typeof contextPolicy === "object" ? contextPolicy : {}),
230
+ };
231
+ const baseMessages = Array.isArray(messages) ? messages : [];
232
+ const nonSystemBase = baseMessages.filter((m) => m && m.role !== "system");
233
+ if (Number.isInteger(restoredTurnOffset) && restoredTurnOffset >= 0) {
234
+ preTurnOffset = restoredTurnOffset;
235
+ } else if (resume) {
236
+ try {
237
+ const existingTurn = turnIndexStore.getTurn(effectiveTurnId);
238
+ preTurnOffset = existingTurn && Number.isInteger(existingTurn.historyOffset) ? existingTurn.historyOffset : 0;
239
+ } catch {
240
+ preTurnOffset = 0;
241
+ }
242
+ } else {
243
+ preTurnOffset = nonSystemBase.length;
244
+ }
245
+ try {
246
+ backfillMissingTurns({ store: turnIndexStore, journalMessages: nonSystemBase.slice(0, preTurnOffset) });
247
+ } catch {
248
+ turnIndexStore = null;
249
+ }
250
+
251
+ const useConfiguredAuxModel = runtime.provider !== "agy" || sameModelProvider(productConfig.ucodeProvider, "agy");
252
+ const explicitAuxModel = String(
253
+ effectivePolicy?.auxModel
254
+ || (useConfiguredAuxModel ? productConfig.ucodeAuxModel : "")
255
+ || process.env.UFOO_UCODE_AUX_MODEL
256
+ || ""
257
+ ).trim();
258
+ const allowDefaultAux = !process.env.JEST_WORKER_ID
259
+ || Boolean(effectivePolicy?.enableModelSelector || effectivePolicy?.backgroundEnrich);
260
+ const configuredAuxModel = explicitAuxModel
261
+ || (allowDefaultAux ? String(runtime.auxModel || defaultAuxModelForProvider(runtime.provider) || "").trim() : "");
262
+ const runAuxModel = typeof effectivePolicy?.runAuxModel === "function"
263
+ ? effectivePolicy.runAuxModel
264
+ : configuredAuxModel
265
+ ? async ({ purpose, currentQuery, activeTopics, candidates, turn, existingTopics, signal: auxSignal }) => {
266
+ const url = typeof transport.resolveUrl === "function" ? transport.resolveUrl(runtime.baseUrl) : runtime.baseUrl;
267
+ if (!url) return null;
268
+ const sysPrompt = purpose === "topic_select"
269
+ ? "Select relevant historical turns and topics as strict JSON: {\"isNewTopic\":boolean,\"matchedTopics\":string[],\"referencedTurnIds\":string[]}. Do not include markdown or prose."
270
+ : "Summarize the completed agent turn as strict JSON: {\"topic\":string,\"userSummary\":string,\"assistantSummary\":string,\"decisions\":string[],\"keywords\":string[]}. Do not include markdown or prose.";
271
+ const userPayload = purpose === "topic_select"
272
+ ? { currentQuery, activeTopics, candidates }
273
+ : { turn, existingTopics };
274
+ const res = await transport.runTurn({
275
+ url,
276
+ apiKey: runtime.apiKey,
277
+ model: configuredAuxModel,
278
+ provider: runtime.provider,
279
+ accountId,
280
+ systemPrompt: sysPrompt,
281
+ messages: [{ role: "user", content: JSON.stringify(userPayload) }],
282
+ tools: [],
283
+ maxOutputTokens: 512,
284
+ sessionId: `${nextSessionId}:aux`,
285
+ signal: auxSignal,
286
+ });
287
+ return res && res.text ? res.text : "";
288
+ }
289
+ : null;
290
+ const topicSelector = createTopicSelector({
291
+ ...effectivePolicy,
292
+ runAuxModel,
293
+ enableModelSelector: Boolean(runAuxModel && (effectivePolicy?.enableModelSelector ?? true)),
294
+ });
295
+ enricher = createAsyncTurnEnricher({
296
+ store: turnIndexStore,
297
+ runAuxModel,
298
+ enabled: Boolean(runAuxModel && (effectivePolicy?.backgroundEnrich ?? true)),
299
+ timeoutMs: effectivePolicy?.enrichTimeoutMs || 8000,
300
+ onEvent: (ev) => {
301
+ observe({ ...ev, taskRunId: ids.taskRunId }).catch(() => {});
302
+ },
303
+ });
304
+ if (signal && typeof signal.addEventListener === "function") {
305
+ abortEnricherListener = () => { if (enricher) enricher.close(); };
306
+ signal.addEventListener("abort", abortEnricherListener, { once: true });
307
+ }
308
+ const contextManager = createSlidingWindowManager({
309
+ policy: effectivePolicy,
310
+ turnIndexStore,
311
+ topicSelector,
312
+ });
313
+
183
314
  const runResult = await runNativeLoop({
315
+ runtimeHooks,
184
316
  transport,
185
317
  workspaceRoot,
186
318
  prompt: resume ? "" : promptText,
@@ -188,7 +320,7 @@ async function runNativeAgentTask({
188
320
  systemBlocks,
189
321
  historyMessages: messages,
190
322
  model: runtime.model,
191
- requestKind: runtimeContext.requestKind || (runtimeContext.taskRunId ? "unknown" : "user"),
323
+ requestKind,
192
324
  baseUrl: runtime.baseUrl,
193
325
  apiKey: runtime.apiKey,
194
326
  provider: runtime.provider,
@@ -207,8 +339,8 @@ async function runNativeAgentTask({
207
339
  guards,
208
340
  executionState,
209
341
  resume: Boolean(resume),
210
- contextManager: createContextManager({ policy: contextPolicy,
211
- store: createCheckpointStore({ workspaceRoot, namespace: "ucode", sessionId: nextSessionId }) }),
342
+ ...(resume ? { historyOffset: preTurnOffset } : {}),
343
+ contextManager,
212
344
  ...ids,
213
345
  agentId: process.env.UFOO_SUBSCRIBER_ID || "ucode",
214
346
  onEvent: observe,
@@ -238,6 +370,48 @@ async function runNativeAgentTask({
238
370
  cacheRead: usage.cacheRead,
239
371
  cacheCreation: usage.cacheCreation,
240
372
  });
373
+ const settledOutcome = signal?.aborted || runResult.stopReason === "cancelled"
374
+ ? "cancelled"
375
+ : (runResult.waitingUserInteraction ? "paused" : (runResult.error || runResult.stopReason ? "failed" : "completed"));
376
+ if (turnIndexStore) {
377
+ try {
378
+ const existingTurns = turnIndexStore.listTurns();
379
+ const existing = existingTurns.find((item) => item.turnId === effectiveTurnId) || null;
380
+ const turnSlice = resolveDurableTurnSlice(runResult, {
381
+ preTurnOffset,
382
+ resume: Boolean(resume),
383
+ promptText,
384
+ });
385
+ const indexed = turnIndexStore.upsertTurn(buildDeterministicTurnRecord({
386
+ turnId: effectiveTurnId,
387
+ turnIndex: existing ? existing.turnIndex : existingTurns.length,
388
+ historyOffset: preTurnOffset,
389
+ historyEnd: preTurnOffset + turnSlice.length,
390
+ turnMessages: turnSlice,
391
+ requestKind,
392
+ prompt: promptText,
393
+ outcome: settledOutcome,
394
+ error: runResult.error || runResult.stopReason || "",
395
+ previousTurns: existingTurns,
396
+ resume: Boolean(resume),
397
+ }), { phase: "A" });
398
+ await observe({
399
+ type: "context.turn_indexed",
400
+ turnId: indexed.turnId,
401
+ topic: indexed.topic,
402
+ turnKind: indexed.turnKind,
403
+ outcome: indexed.outcome,
404
+ });
405
+ if (settledOutcome === "completed" && enricher) {
406
+ enricher.enqueue(indexed);
407
+ if (effectivePolicy?.awaitEnrich) {
408
+ await enricher.flush();
409
+ }
410
+ }
411
+ } catch {
412
+ // Read-only or unavailable context storage must not fail completed turns.
413
+ }
414
+ }
241
415
  await observe({ type: signal?.aborted || runResult.stopReason === "cancelled" ? "task.cancelled" : runResult.error || runResult.stopReason ? "task.failed" : runResult.waitingUserInteraction ? "task.paused" : "task.completed",
242
416
  error: runResult.error || runResult.stopReason || "", result: { text: runResult.finalText || outputText, usage } });
243
417
 
@@ -262,9 +436,41 @@ async function runNativeAgentTask({
262
436
  ...(observationWarnings.length ? { observationWarnings } : {}),
263
437
  };
264
438
  } catch (err) {
265
- await observe({ type: signal?.aborted || err.code === "cancelled" ? "task.cancelled" : "task.failed", error: err.message || "native runner failed" });
266
- const message = err && err.message ? err.message : "native runner failed";
267
439
  const recovered = err.result || {};
440
+ const cancelled = Boolean(signal?.aborted || err.code === "cancelled");
441
+ if (turnIndexStore) {
442
+ try {
443
+ const existingTurns = turnIndexStore.listTurns();
444
+ const existing = existingTurns.find((item) => item.turnId === effectiveTurnId) || null;
445
+ const turnSlice = resolveDurableTurnSlice(recovered, {
446
+ preTurnOffset,
447
+ resume: Boolean(resume),
448
+ promptText,
449
+ });
450
+ const indexed = turnIndexStore.upsertTurn(buildDeterministicTurnRecord({
451
+ turnId: effectiveTurnId,
452
+ turnIndex: existing ? existing.turnIndex : existingTurns.length,
453
+ historyOffset: preTurnOffset,
454
+ historyEnd: preTurnOffset + turnSlice.length,
455
+ turnMessages: turnSlice,
456
+ requestKind,
457
+ prompt: promptText,
458
+ outcome: cancelled ? "cancelled" : "failed",
459
+ error: (err && err.message) || "native runner failed",
460
+ previousTurns: existingTurns,
461
+ resume: Boolean(resume),
462
+ }), { phase: "A" });
463
+ await observe({
464
+ type: "context.turn_indexed",
465
+ turnId: indexed.turnId,
466
+ topic: indexed.topic,
467
+ turnKind: indexed.turnKind,
468
+ outcome: indexed.outcome,
469
+ });
470
+ } catch {}
471
+ }
472
+ await observe({ type: cancelled ? "task.cancelled" : "task.failed", error: err.message || "native runner failed" });
473
+ const message = err && err.message ? err.message : "native runner failed";
268
474
  const recoveredState = recovered.executionState || executionState;
269
475
  if (recoveredState && typeof recoveredState === "object") {
270
476
  clearUserPrompts(recoveredState);
@@ -282,6 +488,11 @@ async function runNativeAgentTask({
282
488
  executionState: recoveredState || null,
283
489
  ...(observationWarnings.length ? { observationWarnings } : {}),
284
490
  };
491
+ } finally {
492
+ if (abortEnricherListener && signal && typeof signal.removeEventListener === "function") {
493
+ signal.removeEventListener("abort", abortEnricherListener);
494
+ }
495
+ if (enricher && (signal?.aborted || enricher.pendingCount() === 0)) enricher.close();
285
496
  }
286
497
  }
287
498
 
package/src/code/repl.js CHANGED
@@ -404,6 +404,31 @@ async function runUcodeCoreAgent({
404
404
  let queuedWork = 0;
405
405
  let queueGeneration = 0;
406
406
  let activeAbortController = null;
407
+ const wakeHost = require("./runtime/backgroundWakeHost").createUcodeWakeHost({ state,
408
+ canDeliver: () => !closing && !taskInFlight && !queuedWork && !autoBusQueued,
409
+ deliver: (event, claim, text) => {
410
+ const pending = chain.then(async () => {
411
+ const { hasPendingUserInteraction } = require("./context/userInteraction");
412
+ if (closing || hasPendingUserInteraction(state.executionState) || !claim()) return false;
413
+ const abort = new AbortController();
414
+ activeAbortController = abort;
415
+ taskInFlight = true;
416
+ try {
417
+ stdout.write(`\n[${event.type}]\n`);
418
+ const result = await runNaturalLanguageTask(text, state, { signal: abort.signal,
419
+ runtimeContext: { requestKind: "system_wake", parentTaskRunId: event.ownerTaskRunId } });
420
+ stdout.write(`${formatNlResult(result, state.jsonOutput)}\n`);
421
+ persistSessionState(state);
422
+ printPrompt(stdout);
423
+ } finally { taskInFlight = false; if (activeAbortController === abort) activeAbortController = null; }
424
+ return true;
425
+ });
426
+ chain = pending.catch(() => {});
427
+ return pending;
428
+ },
429
+ onError: error => stdout.write(`Background notification: ${error.message}\n`),
430
+ });
431
+ wakeHost.start();
407
432
 
408
433
  function formatCoreQueueStatus() {
409
434
  return `Queue: ${taskInFlight ? "active" : "idle"} · pending ${queuedWork}`;
@@ -801,7 +826,8 @@ async function runUcodeCoreAgent({
801
826
 
802
827
  rl.on("close", () => {
803
828
  closing = true;
804
- if (activeAbortController) activeAbortController.abort();
829
+ wakeHost.close();
830
+ if (activeAbortController) activeAbortController.abort("runtime_closed");
805
831
  if (autoBusTimer) {
806
832
  clearInterval(autoBusTimer);
807
833
  autoBusTimer = null;
@@ -94,18 +94,35 @@ function shouldAutoContinueForTaskWake(executionState = null) {
94
94
  function buildTaskRunWakeReminder(executionState = null) {
95
95
  const runs = listTaskRunsAwaitingModel(executionState);
96
96
  if (runs.length === 0 && !hasPendingAgentMailbox(executionState)) return "";
97
+ const graphs = executionState && executionState.graphs && typeof executionState.graphs === "object"
98
+ ? executionState.graphs
99
+ : {};
97
100
  const lines = [
98
101
  "Runtime wake (not a user message): active TaskRun(s) still need the Agent Loop.",
99
- "Continue serving them now. For a TaskLoop child graph waiting on root:",
100
- "call plan_graph operation=patch with graphId=<childGraphId> and expand_node on nodeId=root",
101
- "(tool children). Do not ask the user to /plan off. Do not end with text only.",
102
+ "Continue serving them now. Do not ask the user to /plan off. Do not end with text only.",
102
103
  ];
103
104
  for (const run of runs.slice(0, 4)) {
104
105
  const label = run.title || run.objective || run.parentNodeId || run.id;
106
+ const child = run.childGraphId ? graphs[run.childGraphId] : null;
107
+ const childWaiting = child && child.waitingFor && child.waitingFor.id
108
+ ? String(child.waitingFor.id)
109
+ : "";
110
+ const childNodes = child && Array.isArray(child.nodes) ? child.nodes : [];
111
+ let actionHint = "";
112
+ if (run.childGraphId && childWaiting) {
113
+ actionHint = ` -> call plan_graph operation="patch" graphId="${run.childGraphId}" with expand_node on nodeId="${childWaiting}" (tool children)`;
114
+ } else if (run.childGraphId && childNodes.length > 0 && !childWaiting) {
115
+ actionHint = run.parentNodeId
116
+ ? ` -> all child nodes finished; call plan_graph operation="control" actions=[{"op":"complete_task","taskRunId":"${run.id}","result":{"summary":"..."}}] (or patch graphId="${run.childGraphId}" to add more steps)`
117
+ : ` -> all child nodes finished; call task_run operation="complete" taskRunId="${run.id}" result={"summary":"..."} (or patch graphId="${run.childGraphId}" to add more steps)`;
118
+ } else if (run.childGraphId) {
119
+ actionHint = ` -> call plan_graph operation="patch" graphId="${run.childGraphId}" with expand_node on nodeId="root" (tool children)`;
120
+ }
105
121
  lines.push(
106
122
  `- taskRunId=${run.id} phase=${run.phase || ""} status=${run.status || ""}`
107
123
  + (run.childGraphId ? ` childGraphId=${run.childGraphId}` : "")
108
124
  + (label ? ` — ${String(label).slice(0, 120)}` : "")
125
+ + actionHint
109
126
  );
110
127
  }
111
128
  return lines.join("\n");
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+
3
+ const { createRuntimeHooks, formatWakeEvent } = require("../../agents/runtime/tasks/hooks");
4
+ const { createRuntimeStore } = require("../../agents/runtime/context/runtimeStore");
5
+ const { createBackgroundHookSource } = require("../../agents/capabilities/coding/backgroundHooks");
6
+ const { hasPendingUserInteraction } = require("../context/userInteraction");
7
+
8
+ /** A coding host outlives individual native loops and binds wakes to an exact session. */
9
+ function createUcodeWakeHost({ state, canDeliver = () => true, deliver, onError = () => {} }) {
10
+ let hooks = null;
11
+ let identity = "";
12
+ let closed = false;
13
+ let timer = null;
14
+ function current() {
15
+ if (closed || !state.sessionId || !state.workspaceRoot) return null;
16
+ const next = JSON.stringify([state.workspaceRoot, state.sessionId]);
17
+ if (next === identity) return hooks;
18
+ hooks?.close();
19
+ hooks = null;
20
+ hooks = createRuntimeHooks({
21
+ store: createRuntimeStore({ workspaceRoot: state.workspaceRoot, namespace: "ucode-hooks", sessionId: state.sessionId }),
22
+ sources: { background: createBackgroundHookSource(state.workspaceRoot) },
23
+ canDeliver: () => !closed && next === JSON.stringify([state.workspaceRoot, state.sessionId]) && !hasPendingUserInteraction(state.executionState) && canDeliver(),
24
+ deliver: (event, claim) => deliver(event, claim, formatWakeEvent(event)), onError,
25
+ });
26
+ identity = next;
27
+ hooks.start();
28
+ return hooks;
29
+ }
30
+ Object.defineProperty(state, "runtimeHooks", { configurable: true, enumerable: false, get: current });
31
+ const api = {
32
+ get hooks() { return current(); },
33
+ async tick() { return current()?.tick(); },
34
+ start() {
35
+ if (timer || closed) return;
36
+ current();
37
+ timer = setInterval(() => { try { current(); } catch (error) { onError(error); } }, 500);
38
+ timer.unref?.();
39
+ },
40
+ close() { closed = true; clearInterval(timer); hooks?.close(); },
41
+ };
42
+ return api;
43
+ }
44
+
45
+ module.exports = { createUcodeWakeHost };
@@ -97,6 +97,13 @@ function compactChildGraphHint(executionState = null, run = null) {
97
97
  ];
98
98
  if (waiting && waiting.id) {
99
99
  lines.push(` waitingFor: ${waiting.type || "node"}:${waiting.id}`);
100
+ } else if (nodes.length > 0) {
101
+ const failedCount = nodes.filter((n) => n && (n.status === "failed" || n.status === "blocked")).length;
102
+ lines.push(
103
+ failedCount > 0
104
+ ? ` status: stopped (${failedCount} failed/blocked node(s)) — complete_task / fail_task or patch ${child.graphId}`
105
+ : ` status: all child nodes completed — awaiting complete_task for taskRunId=${run.id}`,
106
+ );
100
107
  }
101
108
  const pending = nodes
102
109
  .filter((n) => n && (n.status === "pending" || n.status === "ready" || n.status === "waiting_llm"))
@@ -115,17 +115,29 @@ function syncParentNodeFromRun(executionState = null, run = null) {
115
115
  node.runtime.phase = run.phase;
116
116
  if (run.status === "running" || run.status === "queued" || run.status === "cancelling") {
117
117
  node.status = "running";
118
+ if (parent.waitingFor && parent.waitingFor.id === node.id) {
119
+ parent.waitingFor = null;
120
+ }
118
121
  } else if (run.status === "succeeded") {
119
122
  node.status = "succeeded";
120
123
  node.result = run.result;
121
124
  node.runtime.result = run.result;
125
+ if (parent.waitingFor && parent.waitingFor.id === node.id) {
126
+ parent.waitingFor = null;
127
+ }
122
128
  } else if (run.status === "failed") {
123
129
  node.status = "failed";
124
130
  node.error = (run.error && run.error.message) || run.error || "task failed";
125
131
  node.runtime.error = run.error;
132
+ if (parent.waitingFor && parent.waitingFor.id === node.id) {
133
+ parent.waitingFor = null;
134
+ }
126
135
  } else if (run.status === "cancelled") {
127
136
  node.status = "cancelled";
128
137
  node.runtime.error = run.error;
138
+ if (parent.waitingFor && parent.waitingFor.id === node.id) {
139
+ parent.waitingFor = null;
140
+ }
129
141
  }
130
142
  setGraph(executionState, parent);
131
143
  if (executionState.planGraph && executionState.planGraph.graphId === parent.graphId) {
@@ -133,6 +145,15 @@ function syncParentNodeFromRun(executionState = null, run = null) {
133
145
  }
134
146
  }
135
147
 
148
+ function clearLeakedChildFromPrimarySlot(executionState = null, taskRunId = "") {
149
+ if (!executionState || !executionState.planGraph || !executionState.planGraph.graphId) return;
150
+ const owner = executionState.planGraph.owner;
151
+ if (!owner || owner.kind !== "task_loop") return;
152
+ if (taskRunId && owner.taskRunId && owner.taskRunId !== taskRunId) return;
153
+ executionState.planGraph = emptyPlanGraphState();
154
+ executionState.mode = "single_action";
155
+ }
156
+
136
157
  function finalizeSuccess(executionState = null, taskRunId = "", result = {}) {
137
158
  const provenanceFiles = getProvenanceChangedFiles(executionState, taskRunId);
138
159
  const mergedResult = result && typeof result === "object" ? { ...result } : {};
@@ -148,6 +169,7 @@ function finalizeSuccess(executionState = null, taskRunId = "", result = {}) {
148
169
  if (!cas.ok) return cas;
149
170
  releaseTaskWriteLease(executionState, taskRunId);
150
171
  syncParentNodeFromRun(executionState, cas.run);
172
+ clearLeakedChildFromPrimarySlot(executionState, taskRunId);
151
173
  enqueueAgentRuntime(executionState, createRuntimeEvent("task_succeeded", {
152
174
  taskId: cas.run.parentNodeId,
153
175
  taskRunId: cas.run.id,
@@ -178,6 +200,7 @@ function finalizeFailure(executionState = null, taskRunId = "", error = {}, expe
178
200
  }
179
201
  releaseTaskWriteLease(executionState, taskRunId);
180
202
  syncParentNodeFromRun(executionState, cas.run);
203
+ clearLeakedChildFromPrimarySlot(executionState, taskRunId);
181
204
  const eventType = cas.run.status === "cancelled" ? "task_cancelled" : "task_failed";
182
205
  enqueueAgentRuntime(executionState, createRuntimeEvent(eventType, {
183
206
  taskId: cas.run.parentNodeId,
@@ -317,7 +340,7 @@ function processTaskRun(executionState = null, taskRunId = "", options = {}) {
317
340
  casTaskRunStatus(executionState, live.id, {
318
341
  expectedStatus: "running",
319
342
  nextStatus: "running",
320
- phase: after && after.waitingFor ? "waiting_model" : "executing_tools",
343
+ phase: "waiting_model",
321
344
  });
322
345
  syncParentNodeFromRun(executionState, getTaskRun(executionState, taskRunId));
323
346
 
@@ -11,7 +11,6 @@ const {
11
11
  const { getJournalPath, deleteSessionJournal } = require("./conversation/sessionJournal");
12
12
  const { deleteSessionArtifacts } = require("./context/artifacts");
13
13
  const { deleteSessionCommitLog, maybeGcSessionArtifacts } = require("./context/artifactGc");
14
- const { defaultContextPolicy } = require("./context/assembler");
15
14
  const { emptyTaskContract } = require("./context/stateCommit");
16
15
  const { emptyWorkingSet } = require("./context/workingSet");
17
16
  const { emptyExecutionState } = require("./context/executionSegment");
@@ -69,14 +68,19 @@ function cloneMessages(value = []) {
69
68
  }
70
69
 
71
70
  function normalizeContextPolicy(value = {}) {
72
- const defaults = defaultContextPolicy();
73
- const source = value && typeof value === "object" ? value : {};
74
- return {
75
- ...defaults,
76
- ...source,
77
- maxMessages: Number.isFinite(source.maxMessages) ? Math.max(1, Math.floor(source.maxMessages)) : defaults.maxMessages,
78
- keepRecentUnits: Number.isFinite(source.keepRecentUnits) ? Math.max(1, Math.floor(source.keepRecentUnits)) : defaults.keepRecentUnits,
79
- };
71
+ const source = value && typeof value === "object" && !Array.isArray(value) ? value : {};
72
+ const out = { ...source };
73
+ if (Number.isFinite(source.maxMessages)) {
74
+ out.maxMessages = Math.max(1, Math.floor(source.maxMessages));
75
+ } else {
76
+ delete out.maxMessages;
77
+ }
78
+ if (Number.isFinite(source.keepRecentUnits)) {
79
+ out.keepRecentUnits = Math.max(1, Math.floor(source.keepRecentUnits));
80
+ } else {
81
+ delete out.keepRecentUnits;
82
+ }
83
+ return out;
80
84
  }
81
85
 
82
86
  function buildSessionSnapshot(input = {}) {
@@ -267,7 +271,7 @@ function deleteSessionData(workspaceRoot = process.cwd(), sessionId = "") {
267
271
  deleteTranscript(workspaceRoot, normalizedId);
268
272
  deleteSessionArtifacts(workspaceRoot, normalizedId);
269
273
  deleteSessionCommitLog(workspaceRoot, normalizedId);
270
- require("../agents/runtime/context/checkpointStore").createCheckpointStore({ workspaceRoot, namespace: "ucode", sessionId: normalizedId }).remove();
274
+ require("../agents/runtime/context/turnIndexStore").createTurnIndexStore({ workspaceRoot, namespace: "ucode", sessionId: normalizedId }).remove();
271
275
  return { ok: true, error: "" };
272
276
  } catch (err) {
273
277
  return {
@@ -13,6 +13,7 @@ const {
13
13
  const { sanitizeSkillContent } = require("./skills/injection");
14
14
  const { randomUUID } = require("crypto");
15
15
  const { normalizeTraceContext } = require("../agents/runtime/protocol/traceContext");
16
+ const { resolveTaskTimeoutMs } = require("../agents/runtime/core/executionBudget");
16
17
 
17
18
  function renderActiveSkillBodiesFromState(state = {}) {
18
19
  const skills = Array.isArray(state.activeSkills) ? state.activeSkills : [];
@@ -51,7 +52,6 @@ function decomposeBugFixTask(task) {
51
52
  id: "identify",
52
53
  name: "Identifying the issue",
53
54
  prompt: `Task context:\n${taskContext}\n\nIdentify the specific problem.\n\nBe concise. Focus only on:\n1. What is broken\n2. What file/function is likely involved\n3. What the expected behavior should be\n\nDo NOT analyze entire codebases. Find the specific issue quickly.`,
54
- timeoutMs: 30000, // 30 seconds
55
55
  earlyExit: true,
56
56
  });
57
57
 
@@ -59,7 +59,6 @@ function decomposeBugFixTask(task) {
59
59
  id: "locate",
60
60
  name: "Locating relevant code",
61
61
  prompt: `Task context:\n${taskContext}\n\nBased on the identified issue, find the exact location of the bug.\n\nSearch for and read ONLY the relevant function/file. Stop as soon as you find the problematic code.`,
62
- timeoutMs: 30000,
63
62
  earlyExit: true,
64
63
  });
65
64
 
@@ -67,7 +66,6 @@ function decomposeBugFixTask(task) {
67
66
  id: "fix",
68
67
  name: "Applying the fix",
69
68
  prompt: `Task context:\n${taskContext}\n\nApply the minimal fix needed. Do NOT refactor or improve unrelated code. Just fix the specific issue.`,
70
- timeoutMs: 60000,
71
69
  earlyExit: false,
72
70
  });
73
71
 
@@ -75,7 +73,6 @@ function decomposeBugFixTask(task) {
75
73
  id: "verify",
76
74
  name: "Verifying the fix",
77
75
  prompt: `Task context:\n${taskContext}\n\nVerify the fix resolves the issue. Check that:\n1. The specific problem is fixed\n2. No new issues were introduced\n\nBe brief.`,
78
- timeoutMs: 20000,
79
76
  earlyExit: false,
80
77
  });
81
78
  } else {
@@ -84,7 +81,6 @@ function decomposeBugFixTask(task) {
84
81
  id: "execute",
85
82
  name: "Executing task",
86
83
  prompt: task,
87
- timeoutMs: 120000,
88
84
  earlyExit: false,
89
85
  });
90
86
  }
@@ -172,7 +168,10 @@ async function runDecomposedTask({
172
168
  onPhase = null,
173
169
  onContextUsage = null,
174
170
  contextPolicy = {},
171
+ timeoutMs,
175
172
  }) {
173
+ const budgetMs = resolveTaskTimeoutMs(timeoutMs ?? state?.timeoutMs);
174
+ const deadline = Date.now() + budgetMs;
176
175
  const steps = decomposeBugFixTask(task);
177
176
  const results = [];
178
177
  const turnItems = [];
@@ -204,7 +203,7 @@ async function runDecomposedTask({
204
203
  });
205
204
 
206
205
  try {
207
- // Run the step with its own timeout
206
+ // All steps share one deadline, including context assembly between steps.
208
207
  const stepPrompt = buildStepPrompt(step, results);
209
208
  let stepMessages = messages;
210
209
  let stepSystemPrompt = systemPrompt;
@@ -222,7 +221,14 @@ async function runDecomposedTask({
222
221
  stepSystemBlocks = assembled.systemBlocks;
223
222
  }
224
223
  const inherited = normalizeTraceContext(runtimeContext);
224
+ const remainingMs = deadline - Date.now();
225
+ // Native transports clamp timeouts to at least one second. Do not start
226
+ // another step if that minimum would extend the task deadline.
227
+ if (remainingMs < 1000) {
228
+ throw new Error(`agent timeout (${budgetMs}ms)`);
229
+ }
225
230
  const stepResult = await runNativeAgentTask({
231
+ runtimeHooks: state?.runtimeHooks,
226
232
  workspaceRoot,
227
233
  provider,
228
234
  model,
@@ -231,7 +237,7 @@ async function runDecomposedTask({
231
237
  systemBlocks: stepSystemBlocks,
232
238
  messages: stepMessages,
233
239
  sessionId,
234
- timeoutMs: step.timeoutMs,
240
+ timeoutMs: remainingMs,
235
241
  maxToolCalls: state ? state.maxToolCalls : undefined,
236
242
  onToolEvent,
237
243
  runtimeContext: inherited.taskRunId ? { ...inherited, parentTaskRunId: inherited.taskRunId,