u-foo 4.0.10 → 4.1.2

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 (71) hide show
  1. package/OPTIONAL_SKILLS/ufoo-bus-poll/SKILL.md +27 -0
  2. package/README.md +279 -789
  3. package/README.zh-CN.md +290 -439
  4. package/SKILLS/ufoo/SKILL.md +7 -0
  5. package/bin/ufoo.js +36 -3
  6. package/dist/tui/darwin-arm64/ufoo-tui +0 -0
  7. package/docs/OBSERVABILITY.md +4 -2
  8. package/docs/README.md +1 -0
  9. package/package.json +6 -2
  10. package/scripts/pack-desktop.js +174 -0
  11. package/src/agents/capabilities/coding/index.js +26 -3
  12. package/src/agents/capabilities/index.js +2 -1
  13. package/src/agents/capabilities/mac/index.js +145 -0
  14. package/src/agents/capabilities/planning/index.js +1 -1
  15. package/src/agents/capabilities/turnRecall/index.js +5 -16
  16. package/src/agents/profiles/coding.js +1 -1
  17. package/src/agents/profiles/main.js +1 -1
  18. package/src/agents/providers/nativeTransport.js +105 -116
  19. package/src/agents/providers/runtimeConfig.js +15 -4
  20. package/src/agents/providers/transports/anthropicCache.js +78 -0
  21. package/src/agents/providers/transports/antigravityTransport.js +3 -2
  22. package/src/agents/providers/transports/openaiResponsesTransport.js +7 -12
  23. package/src/agents/providers/transports/requestCacheObservation.js +61 -0
  24. package/src/agents/providers/transports/responsesProtocol.js +54 -46
  25. package/src/agents/providers/upstreamRuntime.js +2 -2
  26. package/src/agents/runtime/context/contextWindow.js +10 -0
  27. package/src/agents/runtime/context/slidingWindowManager.js +97 -41
  28. package/src/agents/runtime/context/topicSelector.js +4 -2
  29. package/src/agents/runtime/context/turnAnalyzer.js +17 -29
  30. package/src/agents/runtime/core/agentLoop.js +23 -7
  31. package/src/agents/runtime/createAgentRuntime.js +1 -1
  32. package/src/agents/runtime/protocol/auxiliaryModelRequest.js +28 -0
  33. package/src/app/chat/ChatController.js +1 -0
  34. package/src/app/chat/commandExecutor.js +25 -0
  35. package/src/app/chat/commands.js +2 -0
  36. package/src/app/chat/daemonMessageRouter.js +30 -3
  37. package/src/app/cli/appCommands.js +107 -0
  38. package/src/app/cli/features/skills.js +2 -0
  39. package/src/app/cli/macCommands.js +321 -0
  40. package/src/app/cli/metricsCommands.js +6 -1
  41. package/src/app/cli/run.js +26 -0
  42. package/src/app/cli/setupCommands.js +1 -0
  43. package/src/code/agent.js +1 -0
  44. package/src/code/context/assembler.js +8 -6
  45. package/src/code/context/promptLayers.js +3 -1
  46. package/src/code/context/stateCommit.js +2 -2
  47. package/src/code/context/transcript.js +11 -5
  48. package/src/code/nativeRunner.js +25 -5
  49. package/src/code/skills/loader.js +10 -2
  50. package/src/code/skills/render.js +8 -1
  51. package/src/config.js +42 -0
  52. package/src/coordination/bus/activate.js +44 -19
  53. package/src/coordination/history/agentPerformance.js +88 -11
  54. package/src/coordination/history/agentTrace.js +2 -0
  55. package/src/coordination/history/modelInputCost.js +52 -0
  56. package/src/runtime/contracts/uiProtocol.js +26 -0
  57. package/src/runtime/daemon/agentHost.js +35 -12
  58. package/src/runtime/daemon/mcpStdioProxy.js +3 -2
  59. package/src/runtime/mac/helperClient.js +279 -0
  60. package/src/runtime/mac/helperCompiler.js +235 -0
  61. package/src/runtime/mac/macSession.js +866 -0
  62. package/src/runtime/mac/native/ufoo_mac_helper.swift +2493 -0
  63. package/src/runtime/mac/paths.js +63 -0
  64. package/src/ui/agentSettingsController.js +12 -5
  65. package/src/ui/cliHandoff.js +484 -0
  66. package/src/ui/desktopArchive.js +41 -0
  67. package/src/ui/desktopUiHost.js +1601 -0
  68. package/src/ui/desktopUiHostCli.js +66 -0
  69. package/src/ui/format/index.js +17 -0
  70. package/src/ui/rustChatHost.js +45 -6
  71. package/src/ui/workspaceInspector.js +621 -0
@@ -166,9 +166,17 @@ function discoverSkillsUnderRoot(rootInfo = {}, options = {}) {
166
166
  }
167
167
 
168
168
  for (const entry of entries) {
169
- if (!entry.isDirectory()) continue;
170
169
  if (entry.name.startsWith(".")) continue;
171
- walk(path.join(dir, entry.name), depth + 1);
170
+ const child = path.join(dir, entry.name);
171
+ if (!entry.isDirectory()) {
172
+ if (!entry.isSymbolicLink() || depth !== 0 || rootInfo.scope !== "repo") continue;
173
+ const skillFile = path.join(child, SKILL_FILE);
174
+ if (!isFile(skillFile)) continue;
175
+ const workspace = canonicalPath(options.workspaceRoot || process.cwd());
176
+ const relative = path.relative(workspace, canonicalPath(skillFile));
177
+ if (relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) continue;
178
+ }
179
+ walk(child, depth + 1);
172
180
  }
173
181
  };
174
182
 
@@ -1,4 +1,5 @@
1
1
  const {
2
+ buildSkillManifest,
2
3
  buildSkillManifests,
3
4
  renderSkillManifestSection,
4
5
  } = require("./manifest");
@@ -16,6 +17,12 @@ function renderSkillsSection(skills = [], options = {}) {
16
17
  const pathText = String(skill.path || "").replace(/\\/g, "/");
17
18
  const desc = String(skill.description || skill.shortDescription || "").trim();
18
19
  lines.push(`- ${skill.name}: ${desc} (file: ${pathText})`);
20
+ if (options.compactManifests) {
21
+ const manifest = buildSkillManifest(skill);
22
+ if (manifest.workflowSummary && !desc.startsWith(manifest.workflowSummary)) lines.push(` Workflow: ${manifest.workflowSummary}`);
23
+ if (manifest.triggers.length) lines.push(` Triggers: ${manifest.triggers.join(", ")}`);
24
+ if (manifest.bodyArtifactId) lines.push(` Body artifact: artifact://${manifest.bodyArtifactId}`);
25
+ }
19
26
  }
20
27
 
21
28
  lines.push("### How to use skills");
@@ -24,7 +31,7 @@ function renderSkillsSection(skills = [], options = {}) {
24
31
  lines.push("- When a skill is selected, read only the specific skill body and nearby referenced files needed for the task.");
25
32
  lines.push("- If a skill is ambiguous, missing, or unreadable, say so briefly and continue with the best fallback.");
26
33
 
27
- if (options.includeManifests !== false) {
34
+ if (!options.compactManifests && options.includeManifests !== false) {
28
35
  const manifests = buildSkillManifests(list);
29
36
  const manifestSection = renderSkillManifestSection(manifests);
30
37
  if (manifestSection) {
package/src/config.js CHANGED
@@ -70,6 +70,13 @@ const DEFAULT_BROWSER_CONFIG = Object.freeze({
70
70
  profile: "",
71
71
  });
72
72
 
73
+ const DEFAULT_MAC_CONFIG = Object.freeze({
74
+ enabled: true,
75
+ hud: true,
76
+ takeoverGuard: true,
77
+ schemaVersion: 1,
78
+ });
79
+
73
80
  function normalizeAuxModel(value) {
74
81
  return typeof value === "string" ? value.trim() : "";
75
82
  }
@@ -189,6 +196,16 @@ function normalizeBrowserConfig(raw = {}) {
189
196
  return normalized;
190
197
  }
191
198
 
199
+ function normalizeMacConfig(raw = {}) {
200
+ const source = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
201
+ return {
202
+ enabled: typeof source.enabled === "boolean" ? source.enabled : DEFAULT_MAC_CONFIG.enabled,
203
+ hud: typeof source.hud === "boolean" ? source.hud : DEFAULT_MAC_CONFIG.hud,
204
+ takeoverGuard: typeof source.takeoverGuard === "boolean" ? source.takeoverGuard : DEFAULT_MAC_CONFIG.takeoverGuard,
205
+ schemaVersion: 1,
206
+ };
207
+ }
208
+
192
209
  function globalConfigPath() {
193
210
  const override = String(process.env.UFOO_GLOBAL_CONFIG_PATH || "").trim();
194
211
  if (override) return override;
@@ -382,9 +399,31 @@ function saveGlobalBrowserConfig(updates = {}) {
382
399
  });
383
400
  }
384
401
 
402
+ function loadGlobalMacConfig() {
403
+ const raw = loadJsonSafe(globalConfigPath());
404
+ return normalizeMacConfig(raw.mac);
405
+ }
406
+
407
+ function saveGlobalMacConfig(updates = {}) {
408
+ const target = globalConfigPath();
409
+ return withFileLock(target, () => {
410
+ fs.mkdirSync(path.dirname(target), { recursive: true });
411
+ const existing = loadJsonForUpdate(target);
412
+ const merged = withoutRemovedSettings(existing);
413
+ const nextMac = normalizeMacConfig({
414
+ ...(existing.mac && typeof existing.mac === "object" ? existing.mac : {}),
415
+ ...(updates && typeof updates === "object" ? updates : {}),
416
+ });
417
+ merged.mac = nextMac;
418
+ writeFileAtomic(target, JSON.stringify(merged, null, 2), { mode: 0o600 });
419
+ return nextMac;
420
+ });
421
+ }
422
+
385
423
  module.exports = {
386
424
  SETTINGS_MODEL_DEFAULTS,
387
425
  DEFAULT_BROWSER_CONFIG,
426
+ DEFAULT_MAC_CONFIG,
388
427
  globalConfigPath,
389
428
  loadConfig,
390
429
  saveConfig,
@@ -394,9 +433,12 @@ module.exports = {
394
433
  saveGlobalDaemonConfig,
395
434
  loadGlobalBrowserConfig,
396
435
  saveGlobalBrowserConfig,
436
+ loadGlobalMacConfig,
437
+ saveGlobalMacConfig,
397
438
  normalizeBrowserBackend,
398
439
  normalizeBrowserSetupChoice,
399
440
  normalizeBrowserConfig,
441
+ normalizeMacConfig,
400
442
  normalizeLaunchMode,
401
443
  normalizeDaemonTopology,
402
444
  normalizeAgentProvider,
@@ -8,7 +8,7 @@ const { createTerminalAdapterRouter } = require("../../runtime/terminal/adapterR
8
8
  *
9
9
  * 支持的方式:
10
10
  * - tmux: 使用 tmux select-pane 激活
11
- * - terminal: 使用 AppleScript 通过 tty 定位并激活 Terminal.app 的 tab/window
11
+ * - terminal: 使用 AppleScript 通过 tty 定位并激活 Terminal.app 或 iTerm2 的会话
12
12
  * - internal: 不支持自动激活(由 chat PTY view 处理)
13
13
  */
14
14
  class AgentActivator {
@@ -38,6 +38,7 @@ class AgentActivator {
38
38
  id: agentId,
39
39
  nickname: meta.nickname || "",
40
40
  tty: meta.tty || "",
41
+ terminal_app: meta.terminal_app || "",
41
42
  tmux_pane: meta.tmux_pane || "",
42
43
  launch_mode: meta.launch_mode || "",
43
44
  host_inject_sock: meta.host_inject_sock || "",
@@ -95,9 +96,9 @@ class AgentActivator {
95
96
  }
96
97
 
97
98
  /**
98
- * 通过 tty 激活 Terminal.app 中对应的 tab/window
99
+ * 通过 tty 激活外部终端中对应的会话
99
100
  */
100
- activateTerminalByTty(ttyPath) {
101
+ activateTerminalByTty(ttyPath, terminalApp = "Terminal") {
101
102
  if (process.platform !== "darwin") {
102
103
  throw new Error("Terminal activation is only supported on macOS");
103
104
  }
@@ -105,22 +106,46 @@ class AgentActivator {
105
106
  throw new Error("Cannot activate: tty path required");
106
107
  }
107
108
 
108
- const script = `
109
- tell application "Terminal"
110
- repeat with w in windows
111
- repeat with t in tabs of w
112
- if tty of t is "${ttyPath.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}" then
113
- set selected tab of w to t
114
- set index of w to 1
115
- activate
116
- return "ok"
117
- end if
109
+ const script = terminalApp === "iTerm" ? `
110
+ on run argv
111
+ set targetTTY to item 1 of argv
112
+ if application "iTerm2" is not running then return "not found"
113
+ tell application "iTerm2"
114
+ repeat with w in windows
115
+ repeat with t in tabs of w
116
+ repeat with s in sessions of t
117
+ if tty of s is targetTTY then
118
+ select s
119
+ select t
120
+ select w
121
+ activate
122
+ return "ok"
123
+ end if
124
+ end repeat
125
+ end repeat
118
126
  end repeat
119
- end repeat
127
+ end tell
120
128
  return "not found"
121
- end tell`;
129
+ end run` : `
130
+ on run argv
131
+ set targetTTY to item 1 of argv
132
+ if application "/System/Applications/Utilities/Terminal.app" is not running then return "not found"
133
+ tell application "/System/Applications/Utilities/Terminal.app"
134
+ repeat with w in windows
135
+ repeat with t in tabs of w
136
+ if tty of t is targetTTY then
137
+ set selected tab of w to t
138
+ set index of w to 1
139
+ activate
140
+ return "ok"
141
+ end if
142
+ end repeat
143
+ end repeat
144
+ end tell
145
+ return "not found"
146
+ end run`;
122
147
 
123
- const result = spawnSync("osascript", ["-e", script], {
148
+ const result = spawnSync("osascript", ["-e", script, ttyPath], {
124
149
  encoding: "utf8",
125
150
  timeout: 5000,
126
151
  });
@@ -130,8 +155,8 @@ end tell`;
130
155
  }
131
156
 
132
157
  const output = (result.stdout || "").trim();
133
- if (output === "not found") {
134
- throw new Error(`Terminal tab not found for tty: ${ttyPath}`);
158
+ if (output !== "ok") {
159
+ throw new Error(`${terminalApp} tab not found for tty: ${ttyPath}`);
135
160
  }
136
161
  }
137
162
 
@@ -143,7 +168,7 @@ end tell`;
143
168
 
144
169
  const activateTerminal = async () => {
145
170
  if (info.tty) {
146
- this.activateTerminalByTty(info.tty);
171
+ this.activateTerminalByTty(info.tty, info.terminal_app === "iterm2" ? "iTerm" : "Terminal");
147
172
  return;
148
173
  }
149
174
  throw new Error("Cannot activate: missing tty or tmux_pane for agent");
@@ -1,5 +1,13 @@
1
1
  "use strict";
2
2
 
3
+ const { estimateModelInputCost } = require("./modelInputCost");
4
+
5
+ const CACHE_TTLS = ["5m", "1h", "30m", "12h"];
6
+ const sumObserved = values => {
7
+ const observed = values.filter(value => value !== null);
8
+ return observed.length ? observed.reduce((a, b) => a + b, 0) : null;
9
+ };
10
+
3
11
  const terminal = new Set(["completed", "failed", "cancelled", "interrupted"]);
4
12
  const number = value => value != null && Number.isFinite(Number(value)) && Number(value) >= 0 ? Number(value) : null;
5
13
  const time = value => Number.isFinite(Date.parse(value)) ? Date.parse(value) : null;
@@ -21,10 +29,14 @@ function normalizedUsage(usage) {
21
29
  ?? usage.input_tokens_details?.cached_tokens ?? usage.input_token_details?.cached_tokens ?? usage.prompt_tokens_details?.cached_tokens),
22
30
  cacheCreation: number(usage.cacheCreation ?? usage.cache_creation_tokens ?? usage.cache_creation_input_tokens
23
31
  ?? usage.input_tokens_details?.cache_write_tokens ?? usage.prompt_tokens_details?.cache_write_tokens) };
24
- if (!Object.values(value).some(v => v !== null)) return null;
32
+ value.cacheWriteByTtl = Object.fromEntries(CACHE_TTLS.map(ttl => [ttl, number(usage.cacheWriteByTtl?.[ttl])]));
33
+ if (![value.input, value.output, value.cacheRead, value.cacheCreation, ...Object.values(value.cacheWriteByTtl)].some(v => v !== null)) return null;
25
34
  value.inputIncludesCache = typeof usage.inputIncludesCache === "boolean" ? usage.inputIncludesCache
26
35
  : usage.prompt_tokens != null || usage.input_tokens_details || usage.input_token_details || usage.cached_input_tokens != null ? true
27
36
  : usage.cache_read_input_tokens != null || usage.cache_creation_input_tokens != null ? false : null;
37
+ value.uncachedInput = value.inputIncludesCache === false ? value.input
38
+ : value.inputIncludesCache === true && [value.input, value.cacheRead, value.cacheCreation].every(tokenCount => tokenCount !== null)
39
+ ? number(value.input - value.cacheRead - value.cacheCreation) : null;
28
40
  return value;
29
41
  }
30
42
 
@@ -55,7 +67,30 @@ function aggregateCache(runs, scope) {
55
67
  cachedTokens, promptTokens, hitRate: rate(cachedTokens, promptTokens) };
56
68
  }
57
69
 
58
- function aggregate(runs) {
70
+ function requestTotals(requests) {
71
+ const knownInputCostUsd = sumObserved(requests.map(request => request.inputCostUsd));
72
+ const pricedRequests = requests.filter(request => request.inputCostUsd !== null).length;
73
+ return { requests: requests.length, pricedRequests, knownInputCostUsd,
74
+ inputCostUsd: pricedRequests === requests.length ? knownInputCostUsd : null,
75
+ uncachedInput: sumObserved(requests.map(request => request.usage?.uncachedInput ?? null)),
76
+ cacheRead: sumObserved(requests.map(request => request.usage?.cacheRead ?? null)),
77
+ cacheCreation: sumObserved(requests.map(request => request.usage?.cacheCreation ?? null)),
78
+ cacheWriteByTtl: Object.fromEntries(CACHE_TTLS.map(ttl => [ttl,
79
+ sumObserved(requests.map(request => request.usage?.cacheWriteByTtl[ttl] ?? null))])),
80
+ };
81
+ }
82
+
83
+ function requestCohorts(requests, field) {
84
+ const groups = new Map();
85
+ for (const request of requests) {
86
+ const key = request[field] || "unknown";
87
+ if (!groups.has(key)) groups.set(key, []);
88
+ groups.get(key).push(request);
89
+ }
90
+ return Object.fromEntries([...groups].map(([key, values]) => [key, requestTotals(values)]));
91
+ }
92
+
93
+ function aggregate(runs, requestsByRun) {
59
94
  const outcomes = Object.fromEntries(["completed", "failed", "cancelled", "interrupted", "running", "waiting_user", "queued", "unknown"].map(key => [key, runs.filter(r => r.status === key).length]));
60
95
  const finished = Object.entries(outcomes).filter(([key]) => terminal.has(key)).reduce((sum, [, count]) => sum + count, 0);
61
96
  const counts = {};
@@ -70,9 +105,18 @@ function aggregate(runs) {
70
105
  tokenTotals[scope][key] = { samples: observed.length, sum: observed.length ? observed.reduce((a, b) => a + b, 0) : null };
71
106
  }
72
107
  }
108
+ const completedRuns = runs.filter(run => run.status === "completed");
109
+ const completedTaskInputCost = requestTotals(completedRuns.flatMap(run => requestsByRun.get(run.taskRunId)));
110
+ completedTaskInputCost.tasks = completedRuns.length;
111
+ completedTaskInputCost.pricedTasks = completedRuns.filter(run => run.modelCost.inputCostUsd !== null).length;
112
+ if (completedTaskInputCost.pricedTasks < completedTaskInputCost.tasks) completedTaskInputCost.inputCostUsd = null;
73
113
  return { runs: runs.length, outcomes, completedOfFinished: rate(outcomes.completed, finished), finished,
74
114
  counts, latency, ...tokenTotals, finalTextCharacters: distribution(runs.map(r => r.finalTextCharacters)),
75
115
  cache: aggregateCache(runs, "cache"),
116
+ completedTaskInputCost,
117
+ requestsByChannel: requestCohorts(runs.flatMap(run => requestsByRun.get(run.taskRunId)), "channel"),
118
+ requestsByPurpose: requestCohorts(runs.flatMap(run => requestsByRun.get(run.taskRunId)), "purpose"),
119
+ requestsByStrategy: requestCohorts(runs.flatMap(run => requestsByRun.get(run.taskRunId)), "strategyVersion"),
76
120
  signals: Object.fromEntries([...new Set(runs.flatMap(r => r.signals))].map(key => [key, runs.filter(r => r.signals.includes(key)).length])) };
77
121
  }
78
122
 
@@ -107,7 +151,7 @@ function summarizeAgentPerformance(events, tasks = [], queues = [], options = {}
107
151
  parentTaskRunId: event.parentTaskRunId || null, traceId: event.traceId || null, status: "unknown", configuration: null,
108
152
  accepted: null, enqueued: null, started: null, ended: null, lastActivity: null, firstText: null, firstThinking: null,
109
153
  activeStart: null, pausedAt: null, activeMs: 0, waitingUserMs: 0, attempts: new Set(), tools: new Map(),
110
- usageSamples: [], modelOutcomes: 0, terminalUsage: null, finalTextCharacters: null, streamedCharacters: 0,
154
+ usageSamples: [], modelOutcomes: 0, modelRequests: new Map(), terminalUsage: null, finalTextCharacters: null, streamedCharacters: 0,
111
155
  counts: { modelCalls: 0, sdkTurns: 0, modelFailures: 0, toolCalls: 0, toolErrors: 0, toolExceptions: 0, toolRejections: 0, unresolvedTools: 0,
112
156
  repeatedToolCalls: 0, loopWarnings: 0, loopStops: 0, modelRetries: 0, contextSelections: 0, windowProjections: 0, maxEvictionLevel: 0 },
113
157
  modelDurations: [], modelStarts: new Map(), toolDurations: [], contextSelectDurations: [], fingerprints: new Map(), errorCodes: {} };
@@ -138,16 +182,44 @@ function summarizeAgentPerformance(events, tasks = [], queues = [], options = {}
138
182
  }
139
183
  if (type === "message.delta" && event.textCharacters > 0) { run.firstText ??= timestamp; run.streamedCharacters += event.textCharacters; }
140
184
  if (type === "thinking.delta" && event.textCharacters > 0) run.firstThinking ??= timestamp;
185
+ const modelLifecycle = ["model.started", "model.completed", "model.failed"].includes(type);
186
+ const auxiliary = event.purpose && event.purpose !== "foreground";
187
+ if (modelLifecycle && event.modelRequestId) {
188
+ let request = run.modelRequests.get(event.modelRequestId);
189
+ if (!request) {
190
+ request = { modelRequestId: event.modelRequestId, purpose: event.purpose || "foreground", status: "started",
191
+ model: event.model, provider: event.provider, transport: event.transport, channel: event.channel, compressionReason: event.compressionReason,
192
+ strategyVersion: event.strategyVersion || null,
193
+ startedAt: null, usage: null, inputCostUsd: null };
194
+ run.modelRequests.set(event.modelRequestId, request);
195
+ }
196
+ if (type === "model.started") {
197
+ if (request.startedAt !== null) continue;
198
+ request.startedAt = event.time;
199
+ } else {
200
+ if (request.status !== "started") continue;
201
+ request.status = type.slice(6);
202
+ request.providerRequestId = event.providerRequestId;
203
+ request.model = event.model || request.model;
204
+ request.channel = event.channel || request.channel;
205
+ request.durationMs = number(event.durationMs);
206
+ request.cache = event.cacheRequest || null;
207
+ request.strategyVersion = request.cache?.strategyVersion || request.strategyVersion;
208
+ request.usage = normalizedUsage(event.usage);
209
+ request.inputCostUsd = estimateModelInputCost(request);
210
+ }
211
+ }
141
212
  if (type === "model.started") {
142
- run.counts[event.modelScope === "sdk-turn" ? "sdkTurns" : "modelCalls"] += 1;
143
- run.provider ||= event.provider || ""; run.model ||= event.model || "";
144
- run.modelStarts.set(event.turnId || event.modelScope || "api-call", timestamp);
213
+ const counter = auxiliary ? "auxiliaryModelCalls" : event.modelScope === "sdk-turn" ? "sdkTurns" : "modelCalls";
214
+ run.counts[counter] = (run.counts[counter] || 0) + 1;
215
+ if (!auxiliary) { run.provider ||= event.provider || ""; run.model ||= event.model || ""; }
216
+ run.modelStarts.set(event.modelRequestId || event.turnId || event.modelScope || "api-call", timestamp);
145
217
  }
146
218
  if (["model.completed", "model.failed"].includes(type)) {
147
219
  run.modelOutcomes += 1;
148
- const key = event.turnId || event.modelScope || "api-call";
220
+ const key = event.modelRequestId || event.turnId || event.modelScope || "api-call";
149
221
  const duration = number(event.durationMs) ?? difference(timestamp, run.modelStarts.get(key) ?? null);
150
- if (duration !== null) run.modelDurations.push(duration);
222
+ if (duration !== null && !auxiliary) run.modelDurations.push(duration);
151
223
  run.modelStarts.delete(key);
152
224
  if (type === "model.failed") run.counts.modelFailures += 1;
153
225
  else { const usage = normalizedUsage(event.usage); if (usage) run.usageSamples.push(usage); }
@@ -190,6 +262,7 @@ function summarizeAgentPerformance(events, tasks = [], queues = [], options = {}
190
262
  if (code && (type.endsWith("failed") || type === "tool.rejected" || type === "model.retry" || event.ok === false)) run.errorCodes[code] = (run.errorCodes[code] || 0) + 1;
191
263
  }
192
264
  const rows = [];
265
+ const requestsByRun = new Map();
193
266
  for (const run of runs.values()) {
194
267
  const anchor = run.started ?? run.accepted ?? run.lastActivity;
195
268
  const config = run.configuration;
@@ -199,11 +272,15 @@ function summarizeAgentPerformance(events, tasks = [], queues = [], options = {}
199
272
  const end = run.ended ?? now;
200
273
  const paired = [...run.tools.values()];
201
274
  run.counts.unresolvedTools = paired.filter(t => !t.ended || t.outcome === "unknown").length;
202
- const modelStarts = run.counts.modelCalls + run.counts.sdkTurns;
275
+ const modelStarts = run.counts.modelCalls + run.counts.sdkTurns + (run.counts.auxiliaryModelCalls || 0);
203
276
  // Terminal native usage is an accumulator with zero defaults. Do not use
204
277
  // it to invent token counts when observed model calls omitted usage.
205
278
  const usage = run.usageSamples.length ? run.usageSamples : !modelStarts && !run.modelOutcomes && run.terminalUsage ? [run.terminalUsage] : [];
206
279
  const cache = cacheObservation(usage, config, provider);
280
+ const modelRequests = [...run.modelRequests.values()];
281
+ requestsByRun.set(run.taskRunId, modelRequests);
282
+ const modelCost = requestTotals(modelRequests);
283
+ if (modelRequests.length !== modelStarts) modelCost.inputCostUsd = null;
207
284
  const usageComplete = modelStarts ? run.usageSamples.length === modelStarts : !run.modelOutcomes && usage.length > 0;
208
285
  const sumUsage = samples => Object.fromEntries(["input", "output", "cacheRead", "cacheCreation"].map(key => {
209
286
  const values = samples.map(u => u[key]).filter(v => v !== null);
@@ -227,7 +304,7 @@ function summarizeAgentPerformance(events, tasks = [], queues = [], options = {}
227
304
  startedAt: run.started !== null ? new Date(run.started).toISOString() : null,
228
305
  endedAt: run.ended !== null ? new Date(run.ended).toISOString() : null,
229
306
  configuration: config, attempts: run.attempts.size || null, counts: run.counts, usage: sumUsage(usage),
230
- cache,
307
+ cache, modelCost, modelRequests: modelRequests.slice(-100),
231
308
  queueTimingSource: run.enqueued !== null ? "bus.sequence" : run.accepted !== null ? "request.accepted" : "unknown",
232
309
  finalTextCharacters: run.finalTextCharacters, streamedCharacters: run.streamedCharacters,
233
310
  reportCharacters: distribution(reportLengths), errorCodes: run.errorCodes, signals,
@@ -263,7 +340,7 @@ function summarizeAgentPerformance(events, tasks = [], queues = [], options = {}
263
340
  if (partialRuns) warnings.push({ code: "performance_partial_lifecycle", count: partialRuns });
264
341
  const limit = options.includeRuns === false ? 0 : Math.min(100, Math.max(1, Math.floor(Number(options.limit) || 20)));
265
342
  return { version: 1, generatedAt: new Date(now).toISOString(), window: { since: options.since || null, until: options.until || null, selection: "run-start; until exclusive" },
266
- summary: aggregate(rows), cohorts: [...groups.values()].sort((a, b) => b.runs.length - a.runs.length).slice(0, 100).map(g => ({ ...g.cohort, ...aggregate(g.runs) })),
343
+ summary: aggregate(rows, requestsByRun), cohorts: [...groups.values()].sort((a, b) => b.runs.length - a.runs.length).slice(0, 100).map(g => ({ ...g.cohort, ...aggregate(g.runs, requestsByRun) })),
267
344
  delegations: { tasks: delegated.length, accepted, rejected, reported, awaitingAcceptance: delegated.filter(t => t.status === "reported").length,
268
345
  failed: delegated.filter(t => t.status === "failed").length, deliveryUncertain: delegated.filter(t => t.status === "delivery_uncertain").length,
269
346
  acceptedOfReviewed: rate(accepted, accepted + rejected), acceptedOfReported: rate(accepted, reported),
@@ -87,6 +87,8 @@ function readAgentTrace(projectRoot, options = {}) {
87
87
  ...(event.finalTextCharacters != null ? { finalTextCharacters: event.finalTextCharacters } : {}),
88
88
  ...(result.code ? { resultCode: result.code } : {}),
89
89
  provider: event.provider, model: event.model, transport: event.transport, estimatedInputTokens: event.estimatedInputTokens,
90
+ modelRequestId: event.modelRequestId, providerRequestId: event.providerRequestId, purpose: event.purpose,
91
+ channel: event.channel, cacheRequest: event.cacheRequest, compressionReason: event.compressionReason, strategyVersion: event.strategyVersion,
90
92
  ...(["model.started", "model.completed", "model.failed"].includes(event.type) ? { modelScope: event.modelScope || "api-call" } : {}),
91
93
  summary: clip(event.error?.message || event.error || result.error?.message || result.error || event.text || result.text || event.phase?.type || event.type),
92
94
  ...(event.args ? { args: event.args } : {}), ...(event.result ? { result: event.result, ok: result.ok } : {}),
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+
3
+ // Published Standard text-token rates in USD per million tokens.
4
+ // https://developers.openai.com/api/docs/pricing
5
+ // https://platform.claude.com/docs/en/build-with-claude/prompt-caching#pricing
6
+ const OPENAI_RATES = Object.freeze({
7
+ "gpt-6.2-astra": [8, 0.4],
8
+ "gpt-6.2-sol": [2, 0.1],
9
+ "gpt-6-astra": [10, 1],
10
+ "gpt-6.1-sol": [2, 0.1],
11
+ "gpt-6.1-terra": [1, 0.05],
12
+ "gpt-6-luna": [0.1, 0.01],
13
+ });
14
+ const CLAUDE_RATES = Object.freeze({
15
+ "claude-opus-5-5": [4, 0.2],
16
+ "claude-opus-5": [5, 0.5],
17
+ "claude-opus-4-8": [5, 0.5],
18
+ "claude-opus-4-7": [5, 0.5],
19
+ "claude-opus-4-6": [5, 0.5],
20
+ "claude-opus-4-5": [5, 0.5],
21
+ "claude-sonnet-5-5": [2, 0.1],
22
+ "claude-sonnet-5": [2, 0.2],
23
+ "claude-sonnet-4-6": [3, 0.3],
24
+ "claude-haiku-5-5": [0.1, 0.01],
25
+ "claude-haiku-4-5": [1, 0.1],
26
+ });
27
+
28
+ function estimateModelInputCost({ channel, model, usage }) {
29
+ const openAI = channel === "openai-responses";
30
+ if (!usage || (!openAI && channel !== "anthropic-messages")) return null;
31
+ const modelName = String(model || "").toLowerCase().replace(/-(?:\d{4}-\d{2}-\d{2}|\d{8})$/, "");
32
+ const rates = (openAI ? OPENAI_RATES : CLAUDE_RATES)[openAI ? modelName : modelName.replace(/\./g, "-")];
33
+ if (!Array.isArray(rates)) return null;
34
+ const { input, cacheRead, cacheCreation, cacheWriteByTtl } = usage;
35
+ if ([input, cacheRead, cacheCreation].some(value => value === null)) return null;
36
+ const shortTtl = openAI ? "30m" : "5m";
37
+ const longTtl = openAI ? "12h" : "1h";
38
+ const shortWrite = cacheWriteByTtl[shortTtl];
39
+ const longWrite = cacheWriteByTtl[longTtl];
40
+ if (cacheCreation > 0 && (shortWrite === null || longWrite === null)) return null;
41
+ if ((shortWrite ?? 0) + (longWrite ?? 0) !== cacheCreation) return null;
42
+ const totalInput = openAI ? input : input + cacheRead + cacheCreation;
43
+ const uncachedInput = openAI ? input - cacheRead - cacheCreation : input;
44
+ if (uncachedInput < 0) return null;
45
+ // Input and cache prices apply this tier to the entire request.
46
+ const multiplier = openAI && totalInput > 272_000 ? 2 : modelName === "claude-haiku-5-5" && totalInput > 100_000 ? 5 : 1;
47
+ const [inputRate, cacheReadRate] = rates;
48
+ return multiplier * (uncachedInput * inputRate + cacheRead * cacheReadRate
49
+ + (shortWrite ?? 0) * inputRate * 1.25 + (longWrite ?? 0) * inputRate * (openAI ? 2.5 : 2)) / 1_000_000;
50
+ }
51
+
52
+ module.exports = { estimateModelInputCost };
@@ -13,6 +13,8 @@ const PROTOCOL = "ufoo-ui/1";
13
13
  // window.set.mode is main | side | multi, independently of pane membership.
14
14
  const MULTI_FRAMES_CAPABILITY = "multi-frames-v1";
15
15
  const WINDOW_MODES_CAPABILITY = "window-modes-v1";
16
+ const RAW_MARKDOWN_CAPABILITY = "markdown-raw-v1";
17
+ const DESKTOP_HOST_CAPABILITY = "desktop-host-v1";
16
18
 
17
19
  // Internal input uses an explicit agent_id and complete input/cursor draft.
18
20
  // multi.raw.input_revision increases per child edit; submit=true commits that
@@ -48,6 +50,7 @@ const COMMAND_NAMES = Object.freeze([
48
50
  "interaction.respond",
49
51
  "settings.set",
50
52
  "settings.open",
53
+ "settings.models",
51
54
  "ui.resync.request",
52
55
  "app.exit",
53
56
  "window.set",
@@ -56,7 +59,22 @@ const COMMAND_NAMES = Object.freeze([
56
59
  "multi.viewport",
57
60
  "multi.raw",
58
61
  "multi.scroll",
62
+ "multi.cancel",
59
63
  "multi.expand",
64
+ "project.add",
65
+ "project.archive",
66
+ "session.archive",
67
+ "side.select",
68
+ "worker.focus_view",
69
+ "worker.launch",
70
+ "worker.resume",
71
+ "worker.focus_external",
72
+ "workspace.changes",
73
+ "workspace.docs",
74
+ "workspace.context",
75
+ "handoff.to_cli",
76
+ "handoff.open_url",
77
+ "cli.install_shims",
60
78
  ]);
61
79
 
62
80
  const EVENT_NAMES = Object.freeze([
@@ -73,6 +91,7 @@ const EVENT_NAMES = Object.freeze([
73
91
  "agents.snapshot",
74
92
  "agents.patch",
75
93
  "projects.snapshot",
94
+ "projects.tree",
76
95
  "cron.snapshot",
77
96
  "loop.set",
78
97
  "completions.set",
@@ -93,6 +112,11 @@ const EVENT_NAMES = Object.freeze([
93
112
  "error",
94
113
  "window.set",
95
114
  "multi.pane.frame",
115
+ "worker.view.frame",
116
+ "workspace.changes.snapshot",
117
+ "workspace.docs.snapshot",
118
+ "workspace.context.snapshot",
119
+ "handoff.state",
96
120
  ]);
97
121
 
98
122
  function createEnvelope({
@@ -184,6 +208,8 @@ module.exports = {
184
208
  PROTOCOL,
185
209
  MULTI_FRAMES_CAPABILITY,
186
210
  WINDOW_MODES_CAPABILITY,
211
+ RAW_MARKDOWN_CAPABILITY,
212
+ DESKTOP_HOST_CAPABILITY,
187
213
  KINDS,
188
214
  COMMAND_NAMES,
189
215
  EVENT_NAMES,