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
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+
3
+ const crypto = require("crypto");
4
+ const os = require("os");
5
+ const path = require("path");
6
+
7
+ /**
8
+ * Resolve the user-scoped macOS runtime home directory (`~/.ufoo/mac/`).
9
+ * Respects `UFOO_MAC_HOME` for isolated test environments.
10
+ */
11
+ function macHomeDir(env = process.env) {
12
+ const override = String(env.UFOO_MAC_HOME || "").trim();
13
+ if (override) return path.resolve(override);
14
+ return path.join(os.homedir(), ".ufoo", "mac");
15
+ }
16
+
17
+ function macBinDir(env = process.env) {
18
+ return path.join(macHomeDir(env), "bin");
19
+ }
20
+
21
+ function macPrivateDir(env = process.env) {
22
+ return path.join(macHomeDir(env), "private");
23
+ }
24
+
25
+ function macCompileLockPath(env = process.env) {
26
+ return path.join(macPrivateDir(env), "compile.lock");
27
+ }
28
+
29
+ function macDaemonLockPath(env = process.env) {
30
+ return path.join(macPrivateDir(env), "daemon.lock");
31
+ }
32
+
33
+ function macDaemonInfoPath(env = process.env) {
34
+ return path.join(macPrivateDir(env), "daemon.json");
35
+ }
36
+
37
+ function macInputLockPath(env = process.env) {
38
+ return path.join(macPrivateDir(env), "input.lock");
39
+ }
40
+
41
+ function macHelperSocketPath(env = process.env) {
42
+ const candidate = path.join(macPrivateDir(env), "helper.sock");
43
+ if (Buffer.byteLength(candidate) <= 96) return candidate;
44
+ const uid = typeof process.getuid === "function" ? process.getuid() : os.userInfo().username;
45
+ const tag = crypto.createHash("sha256").update(macPrivateDir(env)).digest("hex").slice(0, 12);
46
+ return path.join("/tmp", `ufoo-mc-${uid}-${tag}`, "h.sock");
47
+ }
48
+
49
+ function swiftHelperSourcePath() {
50
+ return path.join(__dirname, "native", "ufoo_mac_helper.swift");
51
+ }
52
+
53
+ module.exports = {
54
+ macHomeDir,
55
+ macBinDir,
56
+ macPrivateDir,
57
+ macCompileLockPath,
58
+ macDaemonLockPath,
59
+ macDaemonInfoPath,
60
+ macInputLockPath,
61
+ macHelperSocketPath,
62
+ swiftHelperSourcePath,
63
+ };
@@ -35,9 +35,11 @@ function createAgentSettingsController({ getProjectRoot, applyPatch, publish, fo
35
35
  if (!model) return { ok: false, error: "Model ID is required" };
36
36
  if (model === "<manual>") return open("manual");
37
37
  if (thinking && !normalizeThinkingLevel(thinking)) return { ok: false, error: "Unknown thinking level" };
38
+ const root = getProjectRoot();
38
39
  let confirmation;
39
- try { confirmation = await confirmModel(getProjectRoot(), model); }
40
+ try { confirmation = await confirmModel(root, model); }
40
41
  catch (error) { return { ok: false, error: error.message }; }
42
+ if (root !== getProjectRoot()) return { ok: false, error: "The active workspace changed. Try again." };
41
43
  if (!confirmation.allowed) return { ok: false, error: confirmation.error };
42
44
  const result = await applyPatch({ agent_model: model, ...(thinking ? { agent_thinking: thinking } : {}) });
43
45
  if (result.ok) {
@@ -85,18 +87,23 @@ function createAgentSettingsController({ getProjectRoot, applyPatch, publish, fo
85
87
  return open("thinking");
86
88
  }
87
89
  async function completions(text) {
90
+ const query = text.trimStart();
91
+ const modelCommand = /^\/model(?:\s|$)/.test(query) ? "/model"
92
+ : /^\/settings\s+agent\s+model(?:\s|$)/.test(query) ? MODEL_COMMAND : "";
93
+ if (!modelCommand && !/^\/settings\s+agent\s+thinking(?:\s|$)/.test(query)) return {};
88
94
  const root = getProjectRoot();
89
95
  const config = loadConfig(root);
90
96
  const thinking = suggestThinkingLevels({ current: config.agentThinking });
91
- const lists = { [THINKING_COMMAND]: thinking, [`${MODEL_COMMAND}/thinking`]: thinking };
92
- if (text.trimStart().startsWith(`${MODEL_COMMAND} `)) {
97
+ const lists = { [THINKING_COMMAND]: thinking };
98
+ if (modelCommand) {
99
+ lists[`${modelCommand}/thinking`] = thinking;
93
100
  const listed = await listModels(root).catch((error) => ({ ok: false, error: error.message }));
94
101
  const ids = listed.ok ? listed.models.slice() : [];
95
102
  if (config.agentModel && (!listed.ok || listed.allowUnlistedModels) && !ids.includes(config.agentModel)) {
96
103
  ids.unshift(config.agentModel);
97
104
  }
98
- lists[MODEL_COMMAND] = ids.map((id) => ({ id, hasChildren: true, desc: id === config.agentModel ? "current · choose thinking" : "choose thinking" }));
99
- lists[MODEL_COMMAND].push({ id: "<manual>", label: "Enter model ID", hasChildren: false,
105
+ lists[modelCommand] = ids.map((id) => ({ id, hasChildren: true, desc: id === config.agentModel ? "current · choose thinking" : "choose thinking" }));
106
+ lists[modelCommand].push({ id: "<manual>", label: "Enter model ID", hasChildren: false,
100
107
  desc: listed.ok ? "Configure a model by ID" : "Catalog unavailable · enter model ID" });
101
108
  }
102
109
  return lists;
@@ -0,0 +1,484 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * CLI <-> Desktop App bidirectional handoff, URL scheme (`ufoo://`),
5
+ * local wakeup socket (`~/.ufoo/run/desktop-handoff.sock`), macOS terminal
6
+ * launcher (`Continue in CLI`), and bundled CLI PATH shim installer.
7
+ */
8
+
9
+ const fs = require("fs");
10
+ const os = require("os");
11
+ const net = require("net");
12
+ const path = require("path");
13
+ const { spawn, spawnSync } = require("child_process");
14
+ const AgentActivator = require("../coordination/bus/activate");
15
+ const { canonicalProjectRoot } = require("../runtime/projects/projectId");
16
+ const { resolveNodeExecutable } = require("../runtime/process/nodeExecutable");
17
+ const { requestActivate } = require("../runtime/terminal/adapters/hostAdapter");
18
+
19
+ const CLI_BINARIES = Object.freeze([
20
+ "ufoo",
21
+ "ucode",
22
+ "uclaude",
23
+ "ucodex",
24
+ "uagy",
25
+ "ugrok",
26
+ "ukimi",
27
+ ]);
28
+
29
+ function getDesktopRunDir(homedir = os.homedir()) {
30
+ return path.join(homedir, ".ufoo", "run");
31
+ }
32
+
33
+ function getDesktopHandoffSocketPath(homedir = os.homedir()) {
34
+ return path.join(getDesktopRunDir(homedir), "desktop-handoff.sock");
35
+ }
36
+
37
+ function getCliBinDir(homedir = os.homedir()) {
38
+ return path.join(homedir, ".ufoo", "bin");
39
+ }
40
+
41
+ function buildHandoffUrl({
42
+ projectRoot = "",
43
+ target = "main",
44
+ windowMode = "",
45
+ docPath = "",
46
+ } = {}) {
47
+ const params = new URLSearchParams();
48
+ if (projectRoot) {
49
+ try {
50
+ params.set("project", canonicalProjectRoot(projectRoot));
51
+ } catch {
52
+ params.set("project", path.resolve(projectRoot));
53
+ }
54
+ }
55
+ if (target) params.set("target", String(target).trim());
56
+ if (windowMode && ["main", "side", "multi"].includes(String(windowMode))) {
57
+ params.set("window", String(windowMode));
58
+ }
59
+ if (docPath) params.set("doc", String(docPath).trim());
60
+ const qs = params.toString();
61
+ return `ufoo://open${qs ? `?${qs}` : ""}`;
62
+ }
63
+
64
+ function parseHandoffUrl(rawUrl = "") {
65
+ const text = String(rawUrl || "").trim();
66
+ if (!text.startsWith("ufoo://")) return null;
67
+ try {
68
+ const parsed = new URL(text);
69
+ const projectRaw = parsed.searchParams.get("project") || "";
70
+ let projectRoot = "";
71
+ if (projectRaw) {
72
+ try {
73
+ projectRoot = canonicalProjectRoot(projectRaw);
74
+ } catch {
75
+ projectRoot = path.resolve(projectRaw);
76
+ }
77
+ }
78
+ const target = parsed.searchParams.get("target") || "main";
79
+ const windowRaw = parsed.searchParams.get("window") || "";
80
+ const windowMode = ["main", "side", "multi"].includes(windowRaw) ? windowRaw : "";
81
+ const docPath = parsed.searchParams.get("doc") || "";
82
+ return {
83
+ action: parsed.hostname || parsed.pathname.replace(/^\/+/, "") || "open",
84
+ projectRoot,
85
+ target,
86
+ windowMode,
87
+ docPath,
88
+ raw: text,
89
+ };
90
+ } catch {
91
+ return null;
92
+ }
93
+ }
94
+
95
+ function createDesktopHandoffServer({
96
+ socketPath = getDesktopHandoffSocketPath(),
97
+ onHandoff = () => {},
98
+ } = {}) {
99
+ fs.mkdirSync(path.dirname(socketPath), { recursive: true });
100
+ try {
101
+ fs.unlinkSync(socketPath);
102
+ } catch {
103
+ // ignore stale socket removal errors
104
+ }
105
+
106
+ const server = net.createServer((socket) => {
107
+ let buffer = "";
108
+ socket.on("data", (chunk) => {
109
+ buffer += chunk.toString("utf8");
110
+ const newline = buffer.indexOf("\n");
111
+ if (newline < 0) return;
112
+ const line = buffer.slice(0, newline).trim();
113
+ buffer = buffer.slice(newline + 1);
114
+ try {
115
+ const msg = JSON.parse(line);
116
+ const parsed = msg.url ? parseHandoffUrl(msg.url) : msg;
117
+ if (parsed) onHandoff(parsed);
118
+ socket.end(`${JSON.stringify({ ok: true })}\n`);
119
+ } catch (err) {
120
+ socket.end(`${JSON.stringify({ ok: false, error: err.message })}\n`);
121
+ }
122
+ });
123
+ });
124
+
125
+ return {
126
+ socketPath,
127
+ listen() {
128
+ return new Promise((resolve, reject) => {
129
+ server.once("error", reject);
130
+ server.listen(socketPath, () => {
131
+ try {
132
+ fs.chmodSync(socketPath, 0o600);
133
+ } catch {
134
+ // ignore chmod issues on unsupported platforms
135
+ }
136
+ resolve(socketPath);
137
+ });
138
+ });
139
+ },
140
+ close() {
141
+ return new Promise((resolve) => {
142
+ server.close(() => {
143
+ try {
144
+ fs.unlinkSync(socketPath);
145
+ } catch {
146
+ // ignore
147
+ }
148
+ resolve();
149
+ });
150
+ });
151
+ },
152
+ };
153
+ }
154
+
155
+ function sendHandoffToRunningDesktop(handoffPayload, {
156
+ socketPath = getDesktopHandoffSocketPath(),
157
+ timeoutMs = 1200,
158
+ } = {}) {
159
+ return new Promise((resolve) => {
160
+ if (!fs.existsSync(socketPath)) {
161
+ resolve({ ok: false, reason: "no_socket" });
162
+ return;
163
+ }
164
+ let settled = false;
165
+ const finish = (res) => {
166
+ if (settled) return;
167
+ settled = true;
168
+ clearTimeout(timer);
169
+ resolve(res);
170
+ };
171
+ const client = net.createConnection(socketPath, () => {
172
+ client.write(`${JSON.stringify(handoffPayload)}\n`);
173
+ });
174
+ let buf = "";
175
+ const timer = setTimeout(() => {
176
+ try { client.destroy(); } catch {}
177
+ finish({ ok: false, reason: "timeout" });
178
+ }, timeoutMs);
179
+ if (typeof timer.unref === "function") timer.unref();
180
+
181
+ client.on("data", (chunk) => {
182
+ buf += chunk.toString("utf8");
183
+ if (buf.includes("\n")) {
184
+ try {
185
+ const parsed = JSON.parse(buf.trim().split("\n")[0]);
186
+ finish({ ok: Boolean(parsed && parsed.ok), delivered: "socket" });
187
+ } catch {
188
+ finish({ ok: true, delivered: "socket" });
189
+ }
190
+ try { client.end(); } catch {}
191
+ }
192
+ });
193
+ client.on("error", () => finish({ ok: false, reason: "connect_failed" }));
194
+ });
195
+ }
196
+
197
+ function findInstalledMacAppCandidates(repoRoot = path.resolve(__dirname, "..", "..")) {
198
+ const home = os.homedir();
199
+ return [
200
+ process.env.UFOO_DESKTOP_APP_PATH || "",
201
+ "/Applications/Ufoo.app",
202
+ path.join(home, "Applications", "Ufoo.app"),
203
+ path.join(repoRoot, "target", "release", "bundle", "macos", "Ufoo.app"),
204
+ path.join(repoRoot, "crates", "ufoo-desktop", "target", "release", "bundle", "macos", "Ufoo.app"),
205
+ ].filter(Boolean);
206
+ }
207
+
208
+ async function openInDesktopApp(options = {}) {
209
+ const url = buildHandoffUrl(options);
210
+ const parsed = parseHandoffUrl(url);
211
+ const direct = await sendHandoffToRunningDesktop({ url, ...parsed }, options);
212
+ if (direct.ok) {
213
+ if (process.platform === "darwin" && options.skipOsActivate !== true) {
214
+ for (const appPath of findInstalledMacAppCandidates()) {
215
+ if (fs.existsSync(appPath)) {
216
+ spawnSync("open", ["-a", appPath], { stdio: "ignore" });
217
+ break;
218
+ }
219
+ }
220
+ }
221
+ return { ok: true, method: "socket", url };
222
+ }
223
+
224
+ if (process.platform === "darwin" && options.skipOsOpen !== true) {
225
+ for (const appPath of findInstalledMacAppCandidates()) {
226
+ if (fs.existsSync(appPath)) {
227
+ const res = spawnSync("open", ["-a", appPath, url], { encoding: "utf8" });
228
+ if (res.status === 0) return { ok: true, method: "app_bundle", appPath, url };
229
+ }
230
+ }
231
+ const schemeRes = spawnSync("open", [url], { encoding: "utf8" });
232
+ if (schemeRes.status === 0) {
233
+ return { ok: true, method: "url_scheme", url };
234
+ }
235
+ }
236
+
237
+ return {
238
+ ok: false,
239
+ url,
240
+ error: "Ufoo.app is not running or installed in /Applications yet.",
241
+ };
242
+ }
243
+
244
+ function shellQuote(value = "") {
245
+ return `'${String(value).replace(/'/g, "'\\''")}'`;
246
+ }
247
+
248
+ function escapeAppleScriptString(value = "") {
249
+ return String(value)
250
+ .replace(/\\/g, "\\\\")
251
+ .replace(/"/g, '\\"');
252
+ }
253
+
254
+ function buildCliCommandString({
255
+ projectRoot,
256
+ windowMode = "",
257
+ agentId = "",
258
+ repoRoot = path.resolve(__dirname, "..", ".."),
259
+ ufooBin = "",
260
+ } = {}) {
261
+ const root = canonicalProjectRoot(projectRoot || process.cwd());
262
+ const binDir = getCliBinDir();
263
+ const shimmedUfoo = path.join(binDir, "ufoo");
264
+ let invocation = "";
265
+ if (ufooBin) {
266
+ invocation = shellQuote(ufooBin);
267
+ } else if (fs.existsSync(shimmedUfoo)) {
268
+ invocation = shellQuote(shimmedUfoo);
269
+ } else {
270
+ const nodeBin = resolveNodeExecutable();
271
+ const scriptPath = path.join(repoRoot, "bin", "ufoo.js");
272
+ invocation = `${shellQuote(nodeBin)} ${shellQuote(scriptPath)}`;
273
+ }
274
+
275
+ const args = ["chat", "--project", shellQuote(root)];
276
+ if (agentId) {
277
+ args.push("--agent", shellQuote(agentId));
278
+ } else if (windowMode && ["main", "side", "multi"].includes(windowMode) && windowMode !== "main") {
279
+ args.push("--window", shellQuote(windowMode));
280
+ }
281
+ return `cd ${shellQuote(root)} && ${invocation} ${args.join(" ")}`;
282
+ }
283
+
284
+ function detectPreferredMacTerminal(preferred = "") {
285
+ const explicit = String(preferred || process.env.UFOO_TERMINAL || "").trim().toLowerCase();
286
+ if (explicit) return explicit;
287
+ const candidates = [
288
+ { id: "iterm2", app: "/Applications/iTerm.app" },
289
+ { id: "ghostty", app: "/Applications/Ghostty.app" },
290
+ { id: "warp", app: "/Applications/Warp.app" },
291
+ { id: "apple-terminal", app: "/System/Applications/Utilities/Terminal.app" },
292
+ ];
293
+ for (const item of candidates) {
294
+ if (fs.existsSync(item.app)) return item.id;
295
+ }
296
+ return "apple-terminal";
297
+ }
298
+
299
+ function externalHostApp(meta) {
300
+ const aliases = [
301
+ [/^(iterm2?|iterm\.app)$/i, "iTerm"],
302
+ [/^(terminal|apple_terminal|terminal\.app)$/i, "Terminal"],
303
+ [/^cursor$/i, "Cursor"],
304
+ [/^(code|vscode|visual studio code)$/i, "Visual Studio Code"],
305
+ [/^ghostty$/i, "Ghostty"],
306
+ [/^warp(terminal)?$/i, "Warp"],
307
+ [/^(codex( app)?|chatgpt( desktop)?|com\.openai\.codex)$/i, "Codex"],
308
+ [/^(agy|antigravity( app)?|google antigravity|com\.google\.antigravity)$/i, "Antigravity"],
309
+ ];
310
+ for (const hint of [meta.host_name, meta.hostName, meta.mcp_metadata?.host_name, meta.terminal_app, meta.terminal]) {
311
+ const match = aliases.find(([pattern]) => pattern.test(String(hint || "").trim()));
312
+ if (match) return match[1];
313
+ }
314
+ return "";
315
+ }
316
+
317
+ async function focusExternalAgentHost(projectRoot, meta = {}) {
318
+ if (process.platform !== "darwin") {
319
+ return { ok: false, error: "External terminal focus is currently supported on macOS" };
320
+ }
321
+ if (meta.launch_mode === "host" && !meta.mcp_bridge && meta.host_inject_sock) {
322
+ try {
323
+ await requestActivate(meta.host_inject_sock);
324
+ return { ok: true, method: "session" };
325
+ } catch {
326
+ // Try a local window or application if the host session is unavailable.
327
+ }
328
+ }
329
+
330
+ const appName = externalHostApp(meta);
331
+ const tty = typeof meta.tty === "string" && /^\/dev\/tty[a-z\d]+$/i.test(meta.tty) ? meta.tty : "";
332
+ const terminalApps = ["Terminal", "iTerm"].filter((name) => !appName || name === appName);
333
+ if (tty && terminalApps.length) {
334
+ const activator = new AgentActivator(projectRoot);
335
+ for (const terminalApp of terminalApps) {
336
+ try {
337
+ activator.activateTerminalByTty(tty, terminalApp);
338
+ return { ok: true, appName: terminalApp, method: "session" };
339
+ } catch {
340
+ // The tab might have closed or macOS might have denied Automation.
341
+ }
342
+ }
343
+ }
344
+
345
+ if (!appName) {
346
+ return { ok: false, error: "No matching window or registered host for this worker." };
347
+ }
348
+
349
+ const threadId = meta.mcp_metadata?.provider_session_id || meta.provider_session_id;
350
+ if (appName === "Codex" && typeof threadId === "string" && /^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/i.test(threadId)) {
351
+ const res = spawnSync("open", [`codex://threads/${threadId}`], { encoding: "utf8" });
352
+ if (res.status === 0) return { ok: true, appName, method: "deep_link" };
353
+ }
354
+
355
+ const args = appName === "Codex" ? ["-b", "com.openai.codex"] : ["-a", appName];
356
+ const res = spawnSync("open", args, { encoding: "utf8" });
357
+ if (res.status === 0) return { ok: true, appName, method: "app" };
358
+ return { ok: false, error: res.stderr?.trim() || `Could not activate ${appName}` };
359
+ }
360
+
361
+ function launchCliHandoff(options = {}) {
362
+ const command = buildCliCommandString(options);
363
+ if (options.dryRun === true) {
364
+ return { ok: true, command, terminal: detectPreferredMacTerminal(options.preferredTerminal) };
365
+ }
366
+ if (process.platform !== "darwin") {
367
+ return { ok: false, command, error: "GUI->CLI terminal launch currently supports macOS" };
368
+ }
369
+
370
+ const terminal = detectPreferredMacTerminal(options.preferredTerminal);
371
+ const escapedCmd = escapeAppleScriptString(command);
372
+
373
+ if (terminal === "iterm2" && fs.existsSync("/Applications/iTerm.app")) {
374
+ const script = [
375
+ 'tell application "iTerm"',
376
+ " activate",
377
+ " if (count of windows) = 0 then",
378
+ " create window with default profile",
379
+ " tell current session of current window",
380
+ ` write text "${escapedCmd}"`,
381
+ " end tell",
382
+ " else",
383
+ " tell current window",
384
+ " create tab with default profile",
385
+ " tell current session",
386
+ ` write text "${escapedCmd}"`,
387
+ " end tell",
388
+ " end tell",
389
+ " end if",
390
+ "end tell",
391
+ ].join("\n");
392
+ const res = spawnSync("osascript", ["-e", script], { encoding: "utf8" });
393
+ if (res.status === 0) return { ok: true, terminal: "iterm2", command };
394
+ }
395
+
396
+ if (terminal === "ghostty" && fs.existsSync("/Applications/Ghostty.app")) {
397
+ const child = spawn("open", ["-na", "Ghostty.app", "--args", "-e", "/bin/zsh", "-lic", command], {
398
+ detached: true,
399
+ stdio: "ignore",
400
+ });
401
+ child.unref();
402
+ return { ok: true, terminal: "ghostty", command };
403
+ }
404
+
405
+ const appleTerminalScript = [
406
+ 'tell application "Terminal"',
407
+ " activate",
408
+ ` do script "${escapedCmd}"`,
409
+ "end tell",
410
+ ].join("\n");
411
+ const res = spawnSync("osascript", ["-e", appleTerminalScript], { encoding: "utf8" });
412
+ if (res.status === 0) {
413
+ return { ok: true, terminal: "apple-terminal", command };
414
+ }
415
+ return {
416
+ ok: false,
417
+ terminal,
418
+ command,
419
+ error: String(res.stderr || "Failed to launch macOS Terminal"),
420
+ };
421
+ }
422
+
423
+ function installCliShims({
424
+ coreRoot = path.resolve(__dirname, "..", ".."),
425
+ nodeExecutable = resolveNodeExecutable(),
426
+ tuiBinary = "",
427
+ targetDir = getCliBinDir(),
428
+ updateZshrc = false,
429
+ } = {}) {
430
+ fs.mkdirSync(targetDir, { recursive: true });
431
+ const installed = [];
432
+ for (const binName of CLI_BINARIES) {
433
+ const scriptFile = path.join(coreRoot, "bin", `${binName}.js`);
434
+ if (!fs.existsSync(scriptFile)) continue;
435
+ const shimPath = path.join(targetDir, binName);
436
+ const lines = [
437
+ "#!/bin/sh",
438
+ "# Managed by Ufoo Desktop App — shares bundled Node & GlobalDaemon core",
439
+ `export UFOO_NODE_EXECUTABLE=${shellQuote(nodeExecutable)}`,
440
+ ];
441
+ if (tuiBinary && fs.existsSync(tuiBinary)) {
442
+ lines.push(`export UFOO_TUI_BIN=${shellQuote(tuiBinary)}`);
443
+ }
444
+ lines.push(`exec ${shellQuote(nodeExecutable)} ${shellQuote(scriptFile)} "$@"`);
445
+ fs.writeFileSync(shimPath, `${lines.join("\n")}\n`, { mode: 0o755 });
446
+ fs.chmodSync(shimPath, 0o755);
447
+ installed.push(shimPath);
448
+ }
449
+
450
+ let profileUpdated = false;
451
+ if (updateZshrc) {
452
+ const zshrc = path.join(os.homedir(), ".zshrc");
453
+ const exportLine = `export PATH="${targetDir}:$PATH"`;
454
+ const current = fs.existsSync(zshrc) ? fs.readFileSync(zshrc, "utf8") : "";
455
+ if (!current.includes(targetDir)) {
456
+ fs.appendFileSync(zshrc, `\n# Ufoo CLI\n${exportLine}\n`, "utf8");
457
+ profileUpdated = true;
458
+ }
459
+ }
460
+
461
+ const pathEntries = String(process.env.PATH || "").split(path.delimiter);
462
+ return {
463
+ ok: true,
464
+ targetDir,
465
+ installed,
466
+ inPath: pathEntries.includes(targetDir),
467
+ profileUpdated,
468
+ };
469
+ }
470
+
471
+ module.exports = {
472
+ CLI_BINARIES,
473
+ getDesktopHandoffSocketPath,
474
+ getCliBinDir,
475
+ buildHandoffUrl,
476
+ parseHandoffUrl,
477
+ createDesktopHandoffServer,
478
+ sendHandoffToRunningDesktop,
479
+ openInDesktopApp,
480
+ buildCliCommandString,
481
+ launchCliHandoff,
482
+ focusExternalAgentHost,
483
+ installCliShims,
484
+ };
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const { writeFileAtomic } = require("../coordination/bus/utils");
6
+ const { withFileLock } = require("../coordination/state/fileLock");
7
+
8
+ function createDesktopArchive(controllerRoot) {
9
+ const file = path.join(controllerRoot, ".ufoo", "ui", "desktop-archive.json");
10
+
11
+ function read() {
12
+ try {
13
+ return JSON.parse(fs.readFileSync(file, "utf8"));
14
+ } catch (error) {
15
+ if (error.code !== "ENOENT") throw error;
16
+ return { projects: [], sessions: [] };
17
+ }
18
+ }
19
+
20
+ function update(entry, archived) {
21
+ withFileLock(file, () => {
22
+ const state = read();
23
+ const key = entry.id ? "sessions" : "projects";
24
+ const items = state[key];
25
+ const index = items.findIndex((item) => item.root === entry.root && item.id === entry.id);
26
+ if (archived === (index >= 0)) return;
27
+ if (archived) items.push(entry);
28
+ else items.splice(index, 1);
29
+ writeFileAtomic(file, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 });
30
+ });
31
+ }
32
+
33
+ return {
34
+ read,
35
+ archiveProject: (root) => update({ root }, true),
36
+ restoreProject: (root) => update({ root }, false),
37
+ archiveSession: (root, id) => update({ root, id }, true),
38
+ };
39
+ }
40
+
41
+ module.exports = { createDesktopArchive };