u-foo 1.4.0 → 1.5.0

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.
package/src/daemon/ops.js CHANGED
@@ -37,6 +37,44 @@ function toTmuxBinary(agent = "") {
37
37
  return "";
38
38
  }
39
39
 
40
+ function normalizeLaunchScope(value, fallback = "inplace") {
41
+ const raw = String(value || "").trim().toLowerCase();
42
+ if (!raw) return fallback;
43
+ if (raw === "inplace" || raw === "same" || raw === "current" || raw === "tab" || raw === "pane") {
44
+ return "inplace";
45
+ }
46
+ if (
47
+ raw === "window"
48
+ || raw === "separate"
49
+ || raw === "new"
50
+ || raw === "new-window"
51
+ || raw === "external"
52
+ || raw === "1"
53
+ || raw === "true"
54
+ || raw === "yes"
55
+ || raw === "y"
56
+ || raw === "on"
57
+ ) {
58
+ return "window";
59
+ }
60
+ if (raw === "0" || raw === "false" || raw === "no" || raw === "n" || raw === "off") {
61
+ return "inplace";
62
+ }
63
+ return fallback;
64
+ }
65
+
66
+ function normalizeTerminalAppPreference(value = "") {
67
+ const raw = String(value || "").trim().toLowerCase();
68
+ if (!raw) return "";
69
+ if (raw === "terminal" || raw === "apple_terminal" || raw === "apple-terminal") {
70
+ return "terminal";
71
+ }
72
+ if (raw === "iterm2" || raw === "iterm" || raw === "iterm.app") {
73
+ return "iterm2";
74
+ }
75
+ return "";
76
+ }
77
+
40
78
  function resolveAgentId(projectRoot, agentId) {
41
79
  if (!agentId) return agentId;
42
80
  if (agentId.includes(":")) return agentId;
@@ -130,23 +168,40 @@ function runAppleScript(lines) {
130
168
  });
131
169
  }
132
170
 
133
- async function openTerminalWindow(runCmd) {
171
+ async function openTerminalWindow(runCmd, options = {}) {
134
172
  if (process.platform !== "darwin") {
135
173
  throw new Error("Terminal mode is only supported on macOS");
136
174
  }
137
175
 
176
+ const launchScope = normalizeLaunchScope(options.launchScope, "inplace");
177
+ const terminalApp = normalizeTerminalAppPreference(options.terminalApp);
178
+ const preferSeparateWindow = launchScope === "window";
138
179
  const escaped = escapeAppleScriptString(runCmd);
180
+ const shouldTryITerm2 = terminalApp
181
+ ? terminalApp === "iterm2"
182
+ : isITerm2();
139
183
 
140
- if (isITerm2()) {
184
+ if (shouldTryITerm2) {
141
185
  try {
142
- const script = [
143
- 'tell application "iTerm2"',
144
- " tell current window",
145
- ` create tab with default profile command "${escaped}"`,
146
- " end tell",
147
- " activate",
148
- "end tell",
149
- ];
186
+ const script = preferSeparateWindow
187
+ ? [
188
+ 'tell application "iTerm2"',
189
+ ` create window with default profile command "${escaped}"`,
190
+ " activate",
191
+ "end tell",
192
+ ]
193
+ : [
194
+ 'tell application "iTerm2"',
195
+ " if (count of windows) is 0 then",
196
+ ` create window with default profile command "${escaped}"`,
197
+ " else",
198
+ " tell current window",
199
+ ` create tab with default profile command "${escaped}"`,
200
+ " end tell",
201
+ " end if",
202
+ " activate",
203
+ "end tell",
204
+ ];
150
205
  await runAppleScript(script);
151
206
  return;
152
207
  } catch {
@@ -154,13 +209,55 @@ async function openTerminalWindow(runCmd) {
154
209
  }
155
210
  }
156
211
 
157
- const script = [
212
+ if (preferSeparateWindow) {
213
+ const script = [
214
+ 'tell application "Terminal"',
215
+ ` do script "${escaped}"`,
216
+ " activate",
217
+ "end tell",
218
+ ];
219
+ await runAppleScript(script);
220
+ return;
221
+ }
222
+
223
+ const preferredScript = [
158
224
  'tell application "Terminal"',
159
- `do script "${escaped}"`,
160
- "activate",
225
+ " activate",
226
+ " if (count of windows) is 0 then",
227
+ ` do script "${escaped}"`,
228
+ " else",
229
+ ' tell application "System Events"',
230
+ ' tell process "Terminal"',
231
+ ' keystroke "t" using command down',
232
+ " end tell",
233
+ " end tell",
234
+ " delay 0.08",
235
+ ` do script "${escaped}" in selected tab of front window`,
236
+ " end if",
237
+ " activate",
161
238
  "end tell",
162
239
  ];
163
- await runAppleScript(script);
240
+
241
+ try {
242
+ await runAppleScript(preferredScript);
243
+ return;
244
+ } catch {
245
+ // Accessibility can block System Events key events; fall back to pure Terminal AppleScript.
246
+ }
247
+
248
+ const fallbackScript = [
249
+ 'tell application "Terminal"',
250
+ " activate",
251
+ " if (count of windows) is 0 then",
252
+ ` do script "${escaped}"`,
253
+ " else",
254
+ " set newTab to (do script \"\" in front window)",
255
+ ` do script "${escaped}" in newTab`,
256
+ " end if",
257
+ " activate",
258
+ "end tell",
259
+ ];
260
+ await runAppleScript(fallbackScript);
164
261
  }
165
262
 
166
263
  async function closeTerminalWindowByTty(ttyPath, preferApp = "") {
@@ -262,7 +359,16 @@ async function tryReuseTerminal(projectRoot, subscriberId, meta, agent, sessionI
262
359
  /**
263
360
  * Spawn managed terminal agent - open a real Terminal session to run the agent
264
361
  */
265
- async function spawnManagedTerminalAgent(projectRoot, agent, nickname = "", processManager = null, extraArgs = [], extraEnv = "") {
362
+ async function spawnManagedTerminalAgent(
363
+ projectRoot,
364
+ agent,
365
+ nickname = "",
366
+ processManager = null,
367
+ extraArgs = [],
368
+ extraEnv = "",
369
+ launchScope = "window",
370
+ terminalApp = ""
371
+ ) {
266
372
  const normalizedAgent = normalizeLaunchAgent(agent);
267
373
  const binary = toTerminalBinary(normalizedAgent);
268
374
  const agentType = toBusAgentType(normalizedAgent);
@@ -283,7 +389,7 @@ async function spawnManagedTerminalAgent(projectRoot, agent, nickname = "", proc
283
389
 
284
390
  const runCmd = `cd ${shellEscape(projectRoot)} && ${prefix}${modeEnv}${nickEnv}${envPrefix}${binary}${argText}`;
285
391
 
286
- await openTerminalWindow(runCmd);
392
+ await openTerminalWindow(runCmd, { launchScope, terminalApp });
287
393
 
288
394
  const subscriberId = await waitForNewSubscriber(projectRoot, agentType, existing, 15000);
289
395
  return { child: null, subscriberId: subscriberId || null };
@@ -455,9 +561,57 @@ function spawnTmuxWindow(projectRoot, agent, nickname = "", extraArgs = [], extr
455
561
  });
456
562
  }
457
563
 
458
- async function launchAgent(projectRoot, agent, count = 1, nickname = "", processManager = null) {
564
+ function resolveTmuxPaneTarget() {
565
+ const explicit = String(process.env.UFOO_TMUX_TARGET || "").trim();
566
+ if (explicit) return explicit;
567
+ const preferredPane = String(process.env.UFOO_TMUX_PANE || "").trim();
568
+ if (preferredPane) return preferredPane;
569
+ const currentPane = String(process.env.TMUX_PANE || "").trim();
570
+ if (currentPane) return currentPane;
571
+ return "";
572
+ }
573
+
574
+ function spawnTmuxPane(projectRoot, agent, nickname = "", extraArgs = [], extraEnv = "", target = "") {
575
+ return new Promise((resolve, reject) => {
576
+ const normalizedAgent = normalizeLaunchAgent(agent);
577
+ const binary = toTmuxBinary(normalizedAgent);
578
+ if (!binary) {
579
+ reject(new Error(`unsupported agent type: ${agent}`));
580
+ return;
581
+ }
582
+ const nickEnv = nickname ? `UFOO_NICKNAME=${shellEscape(nickname)} ` : "";
583
+ const modeEnv = "UFOO_LAUNCH_MODE=tmux ";
584
+ const ttyEnv = "UFOO_TTY_OVERRIDE=$(tty) ";
585
+ const args = Array.isArray(extraArgs) ? extraArgs : [];
586
+ const envPrefix = extraEnv ? `${String(extraEnv).trim()} ` : "";
587
+ const argText = args.length > 0 ? ` ${args.map(shellEscape).join(" ")}` : "";
588
+ const setPaneEnv = `export TMUX_PANE=$(tmux display-message -p '#{pane_id}'); `;
589
+ const runCmd = `cd ${shellEscape(projectRoot)} && ${setPaneEnv}${modeEnv}${nickEnv}${ttyEnv}${envPrefix}${binary}${argText}`;
590
+
591
+ const tmuxArgs = ["split-window", "-d"];
592
+ const normalizedTarget = String(target || "").trim();
593
+ if (normalizedTarget) {
594
+ tmuxArgs.push("-t", normalizedTarget);
595
+ }
596
+ tmuxArgs.push(runCmd);
597
+
598
+ const proc = spawn("tmux", tmuxArgs);
599
+ let stderr = "";
600
+ proc.stderr.on("data", (d) => {
601
+ stderr += d.toString("utf8");
602
+ });
603
+ proc.on("close", (code) => {
604
+ if (code === 0) resolve();
605
+ else reject(new Error(stderr || "tmux split-window failed"));
606
+ });
607
+ });
608
+ }
609
+
610
+ async function launchAgent(projectRoot, agent, count = 1, nickname = "", processManager = null, options = {}) {
459
611
  const config = loadConfig(projectRoot);
460
612
  const mode = config.launchMode || "terminal";
613
+ const launchScope = normalizeLaunchScope(options.launchScope, "inplace");
614
+ const terminalApp = normalizeTerminalAppPreference(options.terminalApp);
461
615
  const normalizedAgent = normalizeLaunchAgent(agent);
462
616
  if (!normalizedAgent) {
463
617
  throw new Error(`unsupported agent type: ${agent}`);
@@ -465,7 +619,7 @@ async function launchAgent(projectRoot, agent, count = 1, nickname = "", process
465
619
 
466
620
  if (mode === "internal") {
467
621
  const result = await spawnInternalAgent(projectRoot, normalizedAgent, count, nickname, processManager);
468
- return { mode: "internal", subscriberIds: result.subscriberIds };
622
+ return { mode: "internal", launchScope, subscriberIds: result.subscriberIds };
469
623
  }
470
624
  if (mode === "tmux") {
471
625
  // Check if tmux is available
@@ -489,14 +643,27 @@ async function launchAgent(projectRoot, agent, count = 1, nickname = "", process
489
643
  process.env.UFOO_TMUX_SESSION = firstSession;
490
644
  }
491
645
  }
646
+ const paneTarget = resolveTmuxPaneTarget();
647
+ const useSeparateWindow = launchScope === "window";
492
648
  for (let i = 0; i < count; i += 1) {
493
649
  // Use "ucode" as default nickname for ufoo/ucode agents
494
650
  const defaultNick = normalizedAgent === "ufoo" ? "ucode" : normalizedAgent;
495
651
  const nick = count > 1 ? `${nickname || defaultNick}-${i + 1}` : (nickname || "");
496
- // eslint-disable-next-line no-await-in-loop
497
- await spawnTmuxWindow(projectRoot, normalizedAgent, nick);
652
+ if (useSeparateWindow) {
653
+ // eslint-disable-next-line no-await-in-loop
654
+ await spawnTmuxWindow(projectRoot, normalizedAgent, nick);
655
+ } else {
656
+ try {
657
+ // eslint-disable-next-line no-await-in-loop
658
+ await spawnTmuxPane(projectRoot, normalizedAgent, nick, [], "", paneTarget);
659
+ } catch {
660
+ // Fallback to new window when current pane target cannot be resolved.
661
+ // eslint-disable-next-line no-await-in-loop
662
+ await spawnTmuxWindow(projectRoot, normalizedAgent, nick);
663
+ }
664
+ }
498
665
  }
499
- return { mode: "tmux" };
666
+ return { mode: "tmux", launchScope, subscriberIds: [] };
500
667
  }
501
668
  // terminal mode - daemon 作为父进程,输出到终端窗口
502
669
  if (process.platform !== "darwin") {
@@ -509,11 +676,20 @@ async function launchAgent(projectRoot, agent, count = 1, nickname = "", process
509
676
  const defaultNick = normalizedAgent === "ufoo" ? "ucode" : normalizedAgent;
510
677
  const nick = count > 1 ? `${nickname || defaultNick}-${i + 1}` : (nickname || "");
511
678
  // eslint-disable-next-line no-await-in-loop
512
- const result = await spawnManagedTerminalAgent(projectRoot, normalizedAgent, nick, processManager);
679
+ const result = await spawnManagedTerminalAgent(
680
+ projectRoot,
681
+ normalizedAgent,
682
+ nick,
683
+ processManager,
684
+ [],
685
+ "",
686
+ launchScope,
687
+ terminalApp
688
+ );
513
689
  if (result.subscriberId) subscriberIds.push(result.subscriberId);
514
690
  }
515
691
 
516
- return { mode: "terminal", subscriberIds };
692
+ return { mode: "terminal", launchScope, subscriberIds };
517
693
  }
518
694
 
519
695
  function normalizeAgentType(agentType) {
@@ -135,6 +135,15 @@ function normalizeOnlineSender(from = "") {
135
135
  return text;
136
136
  }
137
137
 
138
+ function inboxFileName(nickname, route) {
139
+ // Namespace inbox by room/channel to prevent cross-room message leakage
140
+ if (route) {
141
+ const safe = String(route).replace(/[^a-zA-Z0-9_-]/g, "_");
142
+ return `${nickname}__${safe}.jsonl`;
143
+ }
144
+ return `${nickname}.jsonl`;
145
+ }
146
+
138
147
  function appendToInbox(nickname, msg) {
139
148
  const dir = inboxDir();
140
149
  fs.mkdirSync(dir, { recursive: true });
@@ -143,7 +152,8 @@ function appendToInbox(nickname, msg) {
143
152
  _source: messageSource(msg),
144
153
  _receivedAt: new Date().toISOString(),
145
154
  };
146
- fs.appendFileSync(path.join(dir, `${nickname}.jsonl`), JSON.stringify(entry) + "\n");
155
+ const route = msg.room || msg.channel || "";
156
+ fs.appendFileSync(path.join(dir, inboxFileName(nickname, route)), JSON.stringify(entry) + "\n");
147
157
  }
148
158
 
149
159
  // --- Helpers ---
@@ -14,6 +14,28 @@ function inboxFilePath(nickname) {
14
14
  return path.join(inboxDir(), `${nickname}.jsonl`);
15
15
  }
16
16
 
17
+ /**
18
+ * Find all inbox files for a given nickname (including room/channel-namespaced ones).
19
+ * Returns array of { file, route } objects.
20
+ */
21
+ function findInboxFiles(nickname) {
22
+ const dir = inboxDir();
23
+ if (!fs.existsSync(dir)) return [];
24
+ const prefix = `${nickname}__`;
25
+ const exact = `${nickname}.jsonl`;
26
+ const results = [];
27
+ for (const name of fs.readdirSync(dir)) {
28
+ if (!name.endsWith(".jsonl")) continue;
29
+ if (name === exact) {
30
+ results.push({ file: path.join(dir, name), route: "" });
31
+ } else if (name.startsWith(prefix)) {
32
+ const route = name.slice(prefix.length, -".jsonl".length);
33
+ results.push({ file: path.join(dir, name), route });
34
+ }
35
+ }
36
+ return results;
37
+ }
38
+
17
39
  function readMarkerPath(nickname) {
18
40
  return path.join(inboxDir(), `${nickname}.read`);
19
41
  }
@@ -80,6 +102,8 @@ function cleanupInbox(file) {
80
102
  function checkInbox(nickname, options = {}) {
81
103
  const clear = options.clear || false;
82
104
  const unreadOnly = options.unread || false;
105
+ const filterRoom = options.room || "";
106
+ const filterChannel = options.channel || "";
83
107
 
84
108
  if (!nickname) {
85
109
  console.error("nickname is required");
@@ -87,23 +111,24 @@ function checkInbox(nickname, options = {}) {
87
111
  return;
88
112
  }
89
113
 
90
- const file = inboxFilePath(nickname);
91
114
  const markerFile = readMarkerPath(nickname);
92
115
 
116
+ // Gather all inbox files for this nickname
117
+ const inboxFiles = findInboxFiles(nickname);
118
+
93
119
  if (clear) {
94
- if (fs.existsSync(file)) {
95
- fs.unlinkSync(file);
96
- console.log(`Inbox cleared for ${nickname}.`);
97
- } else {
98
- console.log(`No inbox file for ${nickname}.`);
120
+ let cleared = 0;
121
+ for (const { file } of inboxFiles) {
122
+ if (fs.existsSync(file)) { fs.unlinkSync(file); cleared++; }
99
123
  }
124
+ console.log(cleared > 0 ? `Inbox cleared for ${nickname} (${cleared} file(s)).` : `No inbox file for ${nickname}.`);
100
125
  return;
101
126
  }
102
127
 
103
- cleanupInbox(file);
104
-
105
128
  let messages = [];
106
- if (fs.existsSync(file)) {
129
+ for (const { file } of inboxFiles) {
130
+ cleanupInbox(file);
131
+ if (!fs.existsSync(file)) continue;
107
132
  const lines = fs.readFileSync(file, "utf-8").split("\n").filter(Boolean);
108
133
  for (const line of lines) {
109
134
  try {
@@ -114,6 +139,13 @@ function checkInbox(nickname, options = {}) {
114
139
  }
115
140
  }
116
141
 
142
+ // Filter by room/channel if specified
143
+ if (filterRoom) {
144
+ messages = messages.filter((m) => m.room === filterRoom);
145
+ } else if (filterChannel) {
146
+ messages = messages.filter((m) => m.channel === filterChannel);
147
+ }
148
+
117
149
  function displayWidth(str) {
118
150
  let w = 0;
119
151
  for (const ch of str) {
@@ -185,6 +185,14 @@ class OnlineServer extends EventEmitter {
185
185
  return;
186
186
  }
187
187
 
188
+ // DELETE /ufoo/online/rooms/:id
189
+ const roomDeleteMatch = pathname.match(/^\/ufoo\/online\/rooms\/([^/]+)$/);
190
+ if (roomDeleteMatch && req.method === "DELETE") {
191
+ if (!this.authenticateHttp(req, res)) return;
192
+ this.handleRoomDelete(req, res, decodeURIComponent(roomDeleteMatch[1]));
193
+ return;
194
+ }
195
+
188
196
  if (pathname.startsWith("/ufoo/online/rooms")) {
189
197
  // Step 4: HTTP auth
190
198
  if (!this.authenticateHttp(req, res)) return;
@@ -617,6 +625,25 @@ class OnlineServer extends EventEmitter {
617
625
  this.sendJson(res, 405, { ok: false, error: "Method not allowed" });
618
626
  }
619
627
 
628
+ handleRoomDelete(req, res, roomId) {
629
+ const room = this.rooms.get(roomId);
630
+ if (!room) {
631
+ this.sendJson(res, 404, { ok: false, error: "Room not found" });
632
+ return;
633
+ }
634
+ // Disconnect all members and observers
635
+ const kick = (client) => {
636
+ client.rooms.delete(roomId);
637
+ this.sendError(client.ws, "Room deleted", true, "ROOM_DELETED");
638
+ };
639
+ room.members.forEach(kick);
640
+ if (room.observers) room.observers.forEach(kick);
641
+ this.rooms.delete(roomId);
642
+ this.roomPasswords.delete(roomId);
643
+ this.roomMessageHistory.delete(roomId);
644
+ this.sendJson(res, 200, { ok: true, deleted: roomId });
645
+ }
646
+
620
647
  handleChannelsRequest(req, res) {
621
648
  if (req.method === "GET") {
622
649
  this.sendJson(res, 200, { ok: true, channels: this.listChannels() });
@@ -0,0 +1,29 @@
1
+ const crypto = require("crypto");
2
+ const fs = require("fs");
3
+ const path = require("path");
4
+
5
+ function trimTrailingSlashes(value) {
6
+ if (!value) return value;
7
+ return value.replace(/\/+$/, "") || "/";
8
+ }
9
+
10
+ function canonicalProjectRoot(projectRoot) {
11
+ const input = String(projectRoot || "").trim();
12
+ if (!input) {
13
+ throw new Error("projectRoot is required");
14
+ }
15
+ const resolved = path.resolve(input);
16
+ const canonical = fs.realpathSync.native ? fs.realpathSync.native(resolved) : fs.realpathSync(resolved);
17
+ return trimTrailingSlashes(canonical);
18
+ }
19
+
20
+ function buildProjectId(projectRoot) {
21
+ const canonical = canonicalProjectRoot(projectRoot);
22
+ return crypto.createHash("sha1").update(canonical).digest("hex").slice(0, 12);
23
+ }
24
+
25
+ module.exports = {
26
+ trimTrailingSlashes,
27
+ canonicalProjectRoot,
28
+ buildProjectId,
29
+ };