u-foo 4.0.0 → 4.0.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 (158) hide show
  1. package/OBSERVABILITY.md +65 -0
  2. package/README.md +90 -30
  3. package/README.zh-CN.md +76 -26
  4. package/SKILLS/ufoo/SKILL.md +25 -1
  5. package/SKILLS/ufoo-bus/SKILL.md +25 -2
  6. package/bin/ucode.js +4 -0
  7. package/bin/ufoo.js +3 -3
  8. package/dist/tui/darwin-arm64/ufoo-tui +0 -0
  9. package/dist/tui/darwin-x64/ufoo-tui +0 -0
  10. package/dist/tui/linux-arm64/ufoo-tui +0 -0
  11. package/dist/tui/linux-x64/ufoo-tui +0 -0
  12. package/package.json +6 -6
  13. package/src/agents/activity/activityDetector.js +1 -1
  14. package/src/agents/capabilities/agentManagement/service.js +40 -13
  15. package/src/agents/capabilities/coordination/index.js +1 -1
  16. package/src/agents/capabilities/taskReports/index.js +1 -1
  17. package/src/agents/controller/controllerToolExecutor.js +36 -20
  18. package/src/agents/controller/index.js +1 -6
  19. package/src/agents/internal/internalRunner.js +90 -56
  20. package/src/agents/launch/index.js +0 -1
  21. package/src/agents/launch/launcher.js +38 -29
  22. package/src/agents/launch/launcherReadiness.js +35 -0
  23. package/src/agents/launch/notifier.js +2 -2
  24. package/src/agents/launch/ptyWrapper.js +5 -2
  25. package/src/agents/launch/readyDetector.js +2 -2
  26. package/src/agents/profiles/main.js +1 -1
  27. package/src/agents/prompts/cooperation.js +14 -0
  28. package/src/agents/prompts/defaultBootstrap.js +1 -1
  29. package/src/agents/prompts/groupBootstrap.js +23 -7
  30. package/src/agents/prompts/mainAgent.js +11 -2
  31. package/src/agents/prompts/native/system.js +4 -1
  32. package/src/agents/prompts/native/ufoo.js +11 -3
  33. package/src/agents/prompts/promptProfiles.js +2 -0
  34. package/src/agents/prompts/reporting.js +16 -0
  35. package/src/agents/providers/claudeEventTranslator.js +3 -0
  36. package/src/agents/providers/claudeThreadProvider.js +3 -2
  37. package/src/agents/providers/clientIdentity.js +75 -0
  38. package/src/agents/providers/codexEventTranslator.js +23 -2
  39. package/src/agents/providers/codexThreadProvider.js +15 -6
  40. package/src/agents/providers/credentials/index.js +2 -0
  41. package/src/agents/providers/directAuthStatus.js +1 -1
  42. package/src/agents/providers/index.js +1 -1
  43. package/src/agents/providers/modelSettings.js +34 -0
  44. package/src/agents/providers/modelsCatalog.js +379 -0
  45. package/src/agents/providers/nativeTransport.js +58 -40
  46. package/src/agents/providers/runtimeConfig.js +10 -8
  47. package/src/agents/providers/thinkingLevels.js +10 -36
  48. package/src/agents/providers/transports/responsesProtocol.js +11 -6
  49. package/src/agents/providers/upstreamRuntime.js +135 -0
  50. package/src/agents/runtime/context/checkpointStore.js +38 -0
  51. package/src/agents/runtime/context/compaction.js +151 -0
  52. package/src/agents/runtime/context/contextBudget.js +93 -0
  53. package/src/agents/runtime/context/replayHistory.js +28 -0
  54. package/src/agents/runtime/context/runtimeStore.js +2 -1
  55. package/src/agents/runtime/core/agentLoop.js +99 -18
  56. package/src/agents/runtime/core/executionBudget.js +36 -0
  57. package/src/agents/runtime/createAgentRuntime.js +16 -4
  58. package/src/agents/runtime/prompts/responseLanguage.js +12 -0
  59. package/src/agents/runtime/protocol/runObservation.js +24 -0
  60. package/src/agents/runtime/protocol/traceContext.js +9 -0
  61. package/src/app/chat/ChatController.js +26 -53
  62. package/src/app/chat/agentDirectory.js +1 -16
  63. package/src/app/chat/bootstrap.js +1 -2
  64. package/src/app/chat/commandExecutor.js +93 -285
  65. package/src/app/chat/commands.js +32 -45
  66. package/src/app/chat/daemonMessageRouter.js +0 -45
  67. package/src/app/chat/historyStore.js +12 -48
  68. package/src/app/chat/inputSubmitHandler.js +7 -33
  69. package/src/app/chat/internalAgentLogHistory.js +19 -60
  70. package/src/app/chat/multiWindow/paneManager.js +10 -3
  71. package/src/app/chat/streamState.js +0 -4
  72. package/src/app/cli/features/init.js +5 -5
  73. package/src/app/cli/metricsCommands.js +68 -0
  74. package/src/app/cli/run.js +42 -3
  75. package/src/app/cli/traceCommands.js +36 -0
  76. package/src/code/agent.js +18 -13
  77. package/src/code/busConsumer.js +1 -3
  78. package/src/code/commands.js +1 -1
  79. package/src/code/context/assembler.js +7 -8
  80. package/src/code/context/stateCommit.js +2 -1
  81. package/src/code/internalThread.js +10 -3
  82. package/src/code/launcher/ucode.js +1 -1
  83. package/src/code/launcher/ucodeBootstrap.js +1 -1
  84. package/src/code/modelCommand.js +11 -35
  85. package/src/code/nativeRunner.js +55 -17
  86. package/src/code/providers/modelsCatalog.js +1 -317
  87. package/src/code/repl.js +4 -11
  88. package/src/code/sessionStore.js +3 -3
  89. package/src/code/taskDecomposer.js +18 -0
  90. package/src/code/toolBudget.js +1 -17
  91. package/src/config.js +22 -72
  92. package/src/coordination/bus/index.js +12 -3
  93. package/src/coordination/bus/inject.js +2 -2
  94. package/src/coordination/bus/message.js +15 -1
  95. package/src/coordination/bus/nickname.js +1 -1
  96. package/src/coordination/bus/subscriber.js +3 -2
  97. package/src/coordination/bus/utils.js +1 -1
  98. package/src/coordination/history/agentPerformance.js +279 -0
  99. package/src/coordination/history/agentTrace.js +249 -0
  100. package/src/coordination/state/workspaceAccess.js +1 -1
  101. package/src/orchestration/controller/index.js +1 -8
  102. package/src/orchestration/controller/launchRouting.js +1 -1
  103. package/src/orchestration/solo/commands.js +3 -1
  104. package/src/runtime/contracts/agentMode.js +11 -2
  105. package/src/runtime/contracts/uiProtocol.js +18 -19
  106. package/src/runtime/daemon/agentHost.js +57 -25
  107. package/src/runtime/daemon/agentRecoveryGroups.js +70 -0
  108. package/src/runtime/daemon/busBridge.js +1 -1
  109. package/src/runtime/daemon/controlPlaneService.js +1 -1
  110. package/src/runtime/daemon/groupOrchestrator.js +20 -5
  111. package/src/runtime/daemon/groupStatus.js +20 -0
  112. package/src/runtime/daemon/index.js +19 -44
  113. package/src/runtime/daemon/mcpHttpServer.js +39 -10
  114. package/src/runtime/daemon/mcpServer.js +1 -1
  115. package/src/runtime/daemon/nicknameScope.js +1 -1
  116. package/src/runtime/daemon/ops.js +46 -23
  117. package/src/runtime/daemon/projectRuntimeGateway.js +2 -0
  118. package/src/runtime/daemon/promptRequest.js +92 -589
  119. package/src/runtime/daemon/status.js +5 -6
  120. package/src/tools/controllerSchemas.js +6 -2
  121. package/src/tools/handlers/tier2.js +4 -2
  122. package/src/tools/registry.js +4 -0
  123. package/src/tools/schemaFixtures.js +26 -2
  124. package/src/tools/tier0/readAgentMetrics.js +14 -0
  125. package/src/tools/tier0/readAgentTrace.js +12 -0
  126. package/src/ui/agentSettingsController.js +107 -0
  127. package/src/ui/agentSurface.js +1 -1
  128. package/src/ui/dashboardBridge.js +1 -1
  129. package/src/ui/format/banner.js +1 -4
  130. package/src/ui/format/index.js +14 -10
  131. package/src/ui/format/loopSummary.js +50 -0
  132. package/src/ui/format/markdownRenderer.js +3 -4
  133. package/src/ui/rustChatHost.js +191 -206
  134. package/src/ui/rustMultiSession.js +77 -36
  135. package/src/ui/rustUcodeHost.js +6 -1
  136. package/src/ui/settingsBridge.js +33 -16
  137. package/src/ui/toolMergeBridge.js +0 -4
  138. package/src/ui/uiHostServer.js +5 -8
  139. package/src/agents/controller/loopObservability.js +0 -200
  140. package/src/agents/controller/loopRuntime.js +0 -336
  141. package/src/agents/controller/ufooAgent.js +0 -830
  142. package/src/agents/launch/ptyRunner.js +0 -1135
  143. package/src/agents/providers/controllerJsonTransport.js +0 -28
  144. package/src/agents/providers/upstreamTransport.js +0 -698
  145. package/src/app/chat/agentBar.js +0 -135
  146. package/src/app/chat/agentSockets.js +0 -225
  147. package/src/app/chat/dashboardView.js +0 -405
  148. package/src/app/chat/rawKeyMap.js +0 -42
  149. package/src/app/chat/settingsController.js +0 -111
  150. package/src/coordination/history/controllerSummary.js +0 -23
  151. package/src/orchestration/controller/flags.js +0 -167
  152. package/src/orchestration/controller/gateRouter.js +0 -211
  153. package/src/orchestration/controller/routerFastPath.js +0 -22
  154. package/src/orchestration/controller/routerFinalize.js +0 -222
  155. package/src/orchestration/controller/shadowGuard.js +0 -280
  156. package/src/runtime/daemon/executionPaths.js +0 -30
  157. package/src/runtime/daemon/promptLoop.js +0 -136
  158. package/src/runtime/privacy/shadowDiff.js +0 -174
@@ -1,1135 +0,0 @@
1
- const fs = require("fs");
2
- const path = require("path");
3
- const net = require("net");
4
- const { spawnSync } = require("child_process");
5
- const EventBus = require("../../coordination/bus");
6
- const { PTY_SOCKET_MESSAGE_TYPES, PTY_SOCKET_SUBSCRIBE_MODES } = require("../../runtime/contracts/ptySocketContract");
7
- const { getUfooPaths } = require("../../coordination/state/paths");
8
- const { ActivityDetector } = require("../activity/activityDetector");
9
- const { createActivityStatePublisher } = require("../activity/activityStatePublisher");
10
- const { reconcileDetectorOwnedActivity } = require("../activity/activityReconcile");
11
- const {
12
- parseStreamEnvelope,
13
- shouldAutoReplyFromPtyToPublisher,
14
- shouldForwardStreamToPublisher,
15
- } = require("./publisherRouting");
16
- const {
17
- isValueForCodexOption,
18
- resolveDefaultManualBootstrap,
19
- } = require("../prompts/defaultBootstrap");
20
- const { buildPromptInjectionText } = require("../../coordination/bus/promptEnvelope");
21
- const { DeliveryQueue } = require("../../coordination/bus/deliveryQueue");
22
-
23
- function sleep(ms) {
24
- return new Promise((resolve) => setTimeout(resolve, ms));
25
- }
26
-
27
- function parseSubscriberId() {
28
- if (process.env.UFOO_SUBSCRIBER_ID) {
29
- const parts = process.env.UFOO_SUBSCRIBER_ID.split(":");
30
- if (parts.length === 2) {
31
- return {
32
- subscriber: process.env.UFOO_SUBSCRIBER_ID,
33
- agentType: parts[0],
34
- sessionId: parts[1],
35
- };
36
- }
37
- }
38
- throw new Error("PTY runner requires UFOO_SUBSCRIBER_ID set by daemon");
39
- }
40
-
41
- function safeSubscriber(subscriber) {
42
- return subscriber.replace(/:/g, "_");
43
- }
44
-
45
- function claimQueuedEvents(queueFile) {
46
- const queue = new DeliveryQueue(queueFile);
47
- const claims = [];
48
- while (true) {
49
- const claim = queue.claimNext();
50
- if (!claim) break;
51
- claims.push({ ...claim, queue });
52
- }
53
- return claims;
54
- }
55
-
56
- function stripAnsi(text) {
57
- return text
58
- .replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)/g, "")
59
- .replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, "");
60
- }
61
-
62
- function rewriteTitleOscPrefix(text, prefix) {
63
- if (!prefix || !text) return text;
64
- return String(text).replace(/\x1b\]([012]);([^\x07\x1b]*)(\x07|\x1b\\)/g, (match, code, title, terminator) => {
65
- if (!title || title.startsWith(`${prefix}: `)) return match;
66
- return `\x1b]${code};${prefix}: ${title}${terminator}`;
67
- });
68
- }
69
-
70
- function parseInputMessage(message) {
71
- if (!message) return { raw: false, text: "" };
72
- if (parseStreamEnvelope(message)) return null;
73
- try {
74
- const parsed = JSON.parse(message);
75
- if (parsed && typeof parsed === "object") {
76
- if (parsed.raw && typeof parsed.data === "string") {
77
- return { raw: true, text: parsed.data };
78
- }
79
- if (typeof parsed.text === "string") {
80
- return { raw: false, text: parsed.text };
81
- }
82
- }
83
- } catch {
84
- // ignore json parse errors
85
- }
86
- return { raw: false, text: message };
87
- }
88
-
89
- function readAgentsMap(agentsFilePath) {
90
- try {
91
- if (!agentsFilePath || !fs.existsSync(agentsFilePath)) return {};
92
- const data = JSON.parse(fs.readFileSync(agentsFilePath, "utf8"));
93
- return data && data.agents && typeof data.agents === "object" ? data.agents : {};
94
- } catch {
95
- return {};
96
- }
97
- }
98
-
99
- function buildPtyInputFromEvent(evt = {}, subscriber = "", agents = {}) {
100
- if (!evt || !evt.data || typeof evt.data.message !== "string") return null;
101
- const input = parseInputMessage(evt.data.message);
102
- if (!input) return null;
103
- if (input.raw) return input;
104
-
105
- return {
106
- raw: false,
107
- text: buildPromptInjectionText(
108
- { ...evt, data: { ...evt.data, message: input.text } },
109
- subscriber,
110
- agents
111
- ),
112
- };
113
- }
114
-
115
- function getOuterTerminalSize() {
116
- const cols = Number.isInteger(process.stdout && process.stdout.columns) && process.stdout.columns > 0
117
- ? process.stdout.columns
118
- : 80;
119
- const rows = Number.isInteger(process.stdout && process.stdout.rows) && process.stdout.rows > 0
120
- ? process.stdout.rows
121
- : 24;
122
- return { cols, rows };
123
- }
124
-
125
- function computeInjectedSubmitDelayMs(agentType, text) {
126
- const normalizedAgent = String(agentType || "").trim().toLowerCase();
127
- const input = typeof text === "string" ? text : "";
128
- const directSubmit = normalizedAgent === "claude-code"
129
- || normalizedAgent === "agy"
130
- || normalizedAgent === "grok"
131
- || normalizedAgent === "kimi";
132
- let delayMs = directSubmit ? 350 : 200;
133
- if (input.includes("\n")) {
134
- delayMs += directSubmit ? 250 : 120;
135
- }
136
- if (input.length > 512) {
137
- delayMs += Math.min(1200, Math.ceil(input.length / 512) * 90);
138
- }
139
- return delayMs;
140
- }
141
-
142
- function isDirectSubmitAgent(agentType) {
143
- const normalizedAgent = String(agentType || "").trim().toLowerCase();
144
- return normalizedAgent === "claude-code"
145
- || normalizedAgent === "agy"
146
- || normalizedAgent === "grok"
147
- || normalizedAgent === "kimi";
148
- }
149
-
150
- function hasPromptArg(args = []) {
151
- if (!Array.isArray(args) || args.length === 0) return false;
152
- const lastIndex = args.length - 1;
153
- const lastItem = String(args[lastIndex] || "").trim();
154
- if (!lastItem || lastItem.startsWith("-")) return false;
155
- return !isValueForCodexOption(args, lastIndex);
156
- }
157
-
158
- function appendStartupBootstrapArg(agentType, extraArgs = [], env = process.env) {
159
- const normalizedAgent = String(agentType || "").trim().toLowerCase();
160
- const args = Array.isArray(extraArgs) ? extraArgs.slice() : [];
161
- if (normalizedAgent !== "codex") return args;
162
- if (hasPromptArg(args)) return args;
163
- const startupBootstrapText = String(env.UFOO_STARTUP_BOOTSTRAP_TEXT || "").trim();
164
- if (!startupBootstrapText) return args;
165
- return [...args, startupBootstrapText];
166
- }
167
-
168
- function resolvePtyBootstrapArgs(agentType, extraArgs = [], {
169
- projectRoot = process.cwd(),
170
- env = process.env,
171
- } = {}) {
172
- const normalizedAgent = String(agentType || "").trim().toLowerCase();
173
- const args = Array.isArray(extraArgs) ? extraArgs.slice() : [];
174
- if (
175
- normalizedAgent !== "codex"
176
- && normalizedAgent !== "claude"
177
- && normalizedAgent !== "claude-code"
178
- && normalizedAgent !== "grok"
179
- ) {
180
- return { args, env: {} };
181
- }
182
-
183
- const bootstrapAgentType = normalizedAgent === "codex"
184
- ? "codex"
185
- : (normalizedAgent === "grok" ? "grok" : "claude-code");
186
- const resolved = resolveDefaultManualBootstrap({
187
- projectRoot,
188
- agentType: bootstrapAgentType,
189
- args,
190
- env,
191
- });
192
- const resolvedArgs = resolved && resolved.mode !== "skip" && Array.isArray(resolved.args)
193
- ? resolved.args
194
- : args;
195
- const resolvedEnv = resolved && resolved.mode !== "skip" && resolved.env && typeof resolved.env === "object"
196
- ? resolved.env
197
- : {};
198
- return {
199
- args: appendStartupBootstrapArg(normalizedAgent, resolvedArgs, { ...env, ...resolvedEnv }),
200
- env: resolvedEnv,
201
- };
202
- }
203
-
204
- function resolveCommand(agentType, extraArgs = [], options = {}) {
205
- const normalizedAgent = String(agentType || "").trim().toLowerCase();
206
- const bootstrap = resolvePtyBootstrapArgs(normalizedAgent, extraArgs, options);
207
- const extra = bootstrap.args;
208
- const rawCmd = String(process.env.UFOO_PTY_CMD || "").trim();
209
- if (rawCmd) {
210
- const rawArgs = String(process.env.UFOO_PTY_ARGS || "").trim();
211
- const args = rawArgs ? rawArgs.split(/\s+/).filter(Boolean) : [];
212
- return { command: rawCmd, args: [...args, ...extra], env: bootstrap.env };
213
- }
214
- if (normalizedAgent === "claude" || normalizedAgent === "claude-code") {
215
- return { command: "claude", args: [...extra], env: bootstrap.env };
216
- }
217
- if (normalizedAgent === "grok") {
218
- return { command: "grok", args: ["--no-alt-screen", ...extra], env: bootstrap.env };
219
- }
220
- if (normalizedAgent === "ufoo" || normalizedAgent === "ucode" || normalizedAgent === "ufoo-code") {
221
- return { command: "ucode", args: [...extra], env: bootstrap.env };
222
- }
223
- return { command: "codex", args: ["--no-alt-screen", "--sandbox", "workspace-write", ...extra], env: bootstrap.env };
224
- }
225
-
226
- async function runPtyRunner({ projectRoot, agentType = "codex", extraArgs = [] }) {
227
- let pty;
228
- try {
229
- // eslint-disable-next-line global-require
230
- pty = require("node-pty");
231
- } catch {
232
- throw new Error("node-pty not installed");
233
- }
234
- let Terminal = null;
235
- let SerializeAddon = null;
236
- try {
237
- const xterm = await import("@xterm/headless");
238
- const serialize = await import("@xterm/addon-serialize");
239
- Terminal = xterm.Terminal
240
- || (xterm.default && xterm.default.Terminal)
241
- || (xterm["module.exports"] && xterm["module.exports"].Terminal);
242
- SerializeAddon = serialize.SerializeAddon
243
- || (serialize.default && serialize.default.SerializeAddon)
244
- || (serialize["module.exports"] && serialize["module.exports"].SerializeAddon);
245
- } catch {
246
- Terminal = null;
247
- SerializeAddon = null;
248
- }
249
- const { subscriber } = parseSubscriberId();
250
- const queueDir = path.join(getUfooPaths(projectRoot).busQueuesDir, safeSubscriber(subscriber));
251
- const queueFile = path.join(queueDir, "pending.jsonl");
252
- const runDir = getUfooPaths(projectRoot).runDir;
253
- const logFile = path.join(runDir, "pty-runner.log");
254
- const injectSockPath = path.join(queueDir, "inject.sock");
255
-
256
- const { command, args, env: commandEnv } = resolveCommand(agentType, extraArgs, {
257
- projectRoot,
258
- env: process.env,
259
- });
260
- const env = {
261
- ...process.env,
262
- ...(commandEnv && typeof commandEnv === "object" ? commandEnv : {}),
263
- UFOO_LAUNCH_MODE: "internal-pty",
264
- UFOO_INTERNAL_PTY: "1",
265
- };
266
-
267
- const idleMs = Number.parseInt(process.env.UFOO_INTERNAL_PTY_IDLE_MS || "", 10) || 30000;
268
- const eventBus = new EventBus(projectRoot);
269
- const activityDetector = new ActivityDetector(agentType, {
270
- mode: "internal-pty",
271
- quietWindowMs: idleMs,
272
- });
273
- const agentsFilePath = getUfooPaths(projectRoot).agentsFile;
274
-
275
- let running = true;
276
- let busy = false;
277
- let ptyAlive = false;
278
- let ptyReady = false;
279
- let readyTimer = null;
280
- let currentPublisher = "";
281
- let pendingOutput = [];
282
- let outputBuffer = "";
283
- let flushTimer = null;
284
- let idleTimer = null;
285
- let watchdogTimer = null;
286
- let ptyProcess = null;
287
- let restartCount = 0;
288
- let lastSpawnTime = 0;
289
- const MAX_RESTARTS = 10;
290
- const RESTART_STABLE_MS = 30000; // reset counter if process ran > 30s
291
- const RESTART_DELAY_MS = 2000;
292
- const RESTART_BACKOFF_CAP_MS = 30000;
293
- const READY_QUIET_MS = 3000; // TUI is "ready" after 3s of no output
294
- const messageQueue = [];
295
- const injectServer = setupInjectServer();
296
- initScreenBuffer(80, 24);
297
- const maxChunk = 2000;
298
- const watchdogMs = 120000;
299
- const maxQueue = 200;
300
- let sendQueue = Promise.resolve();
301
- const streamPublisherCache = new Map();
302
- const DROP_LINE_PATTERNS = [
303
- /context left/i,
304
- /esc to interrupt/i,
305
- /for shortcuts/i,
306
- /Preparing to run session start commands/i,
307
- /^[•\s]*(working|thinking|loading|reading|editing|running|checking)[•\s]*$/i,
308
- ];
309
-
310
- function shouldDropLine(line) {
311
- if (!line) return true;
312
- const trimmed = line.trim();
313
- if (!trimmed) return true;
314
- if (/^[›❯>]$/.test(trimmed)) return true;
315
- return DROP_LINE_PATTERNS.some((re) => re.test(trimmed));
316
- }
317
-
318
- function sanitizeChunk(chunk) {
319
- if (!chunk) return "";
320
- let text = String(chunk);
321
- if (text.includes("\r")) {
322
- const parts = text.split("\r");
323
- text = parts[parts.length - 1];
324
- }
325
- const lines = text.split("\n").filter((line) => !shouldDropLine(line));
326
- return lines.join("\n");
327
- }
328
-
329
- function enqueueSend(target, message) {
330
- if (!target || !message) return;
331
- sendQueue = sendQueue.then(() => eventBus.send(target, message, subscriber)).catch((err) => {
332
- logNote(`[send-error] target=${target} err=${err.message || err}`);
333
- });
334
- }
335
-
336
- function canStreamToPublisher(target) {
337
- if (!target) return false;
338
- if (streamPublisherCache.has(target)) return streamPublisherCache.get(target);
339
- const result = shouldForwardStreamToPublisher(projectRoot, target);
340
- streamPublisherCache.set(target, result);
341
- return result;
342
- }
343
-
344
- function completePublisherResponse(reason, fallbackNote = "") {
345
- if (!currentPublisher) return;
346
- if (flushTimer) {
347
- clearTimeout(flushTimer);
348
- flushTimer = null;
349
- }
350
- if (!shouldAutoReplyFromPtyToPublisher(projectRoot, currentPublisher)) {
351
- outputBuffer = "";
352
- return;
353
- }
354
- if (outputBuffer) {
355
- const remaining = outputBuffer;
356
- outputBuffer = "";
357
- deliverChunk(remaining);
358
- }
359
- if (fallbackNote) enqueueSend(currentPublisher, fallbackNote);
360
- enqueueSend(currentPublisher, JSON.stringify({ stream: true, done: true, reason }));
361
- }
362
-
363
- // TTY view subscribers (same protocol as launcher inject.sock)
364
- const outputSubscribers = new Set();
365
- let term = null;
366
- let serializeAddon = null;
367
- let termWriteQueue = Promise.resolve();
368
- const OUTPUT_RING_MAX = (() => {
369
- const env = Number.parseInt(process.env.UFOO_INTERNAL_RING_MAX || "", 10);
370
- if (Number.isFinite(env) && env > 0) return env;
371
- return 512 * 1024;
372
- })();
373
- let outputRingBuffer = "";
374
- let outerInputHandler = null;
375
- let outerResizeHandler = null;
376
- let outerRawModeEnabled = false;
377
-
378
- function initScreenBuffer(cols = 80, rows = 24) {
379
- if (!Terminal || !SerializeAddon) return null;
380
- try {
381
- const scrollbackEnv = Number.parseInt(process.env.UFOO_INTERNAL_SCROLLBACK || "", 10);
382
- const scrollback = Number.isFinite(scrollbackEnv) && scrollbackEnv >= 0
383
- ? scrollbackEnv
384
- : 20000;
385
- term = new Terminal({
386
- cols,
387
- rows,
388
- scrollback,
389
- allowProposedApi: true,
390
- convertEol: true,
391
- });
392
- serializeAddon = new SerializeAddon();
393
- term.loadAddon(serializeAddon);
394
- } catch {
395
- term = null;
396
- serializeAddon = null;
397
- }
398
- return term;
399
- }
400
-
401
- function enqueueTermWrite(data) {
402
- if (!term || !data) return;
403
- termWriteQueue = termWriteQueue.then(() => new Promise((resolve) => {
404
- term.write(data, resolve);
405
- })).catch(() => {});
406
- }
407
-
408
- function serializeBuffer(buffer, scrollback) {
409
- if (!term || !serializeAddon || !buffer) return "";
410
- try {
411
- if (typeof serializeAddon._serializeBuffer === "function") {
412
- return serializeAddon._serializeBuffer(term, buffer, scrollback);
413
- }
414
- if (buffer === term.buffer.normal && typeof serializeAddon.serialize === "function") {
415
- return serializeAddon.serialize({
416
- scrollback,
417
- excludeAltBuffer: true,
418
- excludeModes: true,
419
- });
420
- }
421
- return "";
422
- } catch {
423
- return "";
424
- }
425
- }
426
-
427
- async function serializeSnapshot(mode = "full") {
428
- if (!term || !serializeAddon) return null;
429
- try {
430
- await termWriteQueue;
431
- const active = term.buffer.active;
432
- const normal = term.buffer.normal;
433
- const scrollback = term.options && Number.isFinite(term.options.scrollback)
434
- ? term.options.scrollback
435
- : undefined;
436
-
437
- if (mode === "screen") {
438
- const screen = serializeBuffer(active, 0);
439
- return screen ? { data: screen } : null;
440
- }
441
-
442
- let data = serializeBuffer(normal, scrollback);
443
- if (active && active !== normal) {
444
- const alt = serializeBuffer(active, 0);
445
- if (alt) data += `\x1b[H${alt}`;
446
- }
447
- return data ? { data } : null;
448
- } catch {
449
- return null;
450
- }
451
- }
452
-
453
- const titlePrefix = process.env.UFOO_LAUNCH_MODE === "host"
454
- ? String(process.env.UFOO_NICKNAME || "").trim()
455
- : "";
456
- let titleOscBuffer = "";
457
-
458
- function prependTitlePrefix(data) {
459
- if (!titlePrefix) return Buffer.from(data || "").toString("utf8");
460
- const text = Buffer.from(data || "").toString("utf8");
461
- const combined = titleOscBuffer + text;
462
- titleOscBuffer = "";
463
- const trailingOscStart = combined.lastIndexOf("\x1b]");
464
- if (trailingOscStart >= 0) {
465
- const trailing = combined.slice(trailingOscStart);
466
- if (!/(?:\x07|\x1b\\)/.test(trailing)) {
467
- titleOscBuffer = trailing;
468
- return rewriteTitleOscPrefix(combined.slice(0, trailingOscStart), titlePrefix);
469
- }
470
- }
471
- return rewriteTitleOscPrefix(combined, titlePrefix);
472
- }
473
-
474
- function broadcastOutput(data) {
475
- const text = prependTitlePrefix(data);
476
- if (!text) return;
477
- if (process.stdout && process.stdout.isTTY && typeof process.stdout.write === "function") {
478
- try {
479
- process.stdout.write(text);
480
- } catch {
481
- // ignore outer terminal write failures
482
- }
483
- }
484
- enqueueTermWrite(text);
485
- outputRingBuffer += text;
486
- if (outputRingBuffer.length > OUTPUT_RING_MAX) {
487
- outputRingBuffer = outputRingBuffer.slice(-OUTPUT_RING_MAX);
488
- }
489
- if (outputSubscribers.size === 0) return;
490
- const msg = JSON.stringify({ type: PTY_SOCKET_MESSAGE_TYPES.OUTPUT, data: text, encoding: "utf8" }) + "\n";
491
- for (const sub of outputSubscribers) {
492
- try {
493
- sub.write(msg);
494
- } catch {
495
- outputSubscribers.delete(sub);
496
- }
497
- }
498
- }
499
-
500
- function setupInjectServer() {
501
- const dir = path.dirname(injectSockPath);
502
- if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
503
- if (fs.existsSync(injectSockPath)) {
504
- try { fs.unlinkSync(injectSockPath); } catch { /* ignore */ }
505
- }
506
- const server = net.createServer((client) => {
507
- let buffer = "";
508
- client.on("data", (data) => {
509
- buffer += data.toString("utf8");
510
- const lines = buffer.split("\n");
511
- buffer = lines.pop() || "";
512
- for (const line of lines) {
513
- if (!line.trim()) continue;
514
- try {
515
- const req = JSON.parse(line);
516
- if (req.type === "inject" && req.command) {
517
- if (ptyProcess && ptyAlive) {
518
- const directSubmit = isDirectSubmitAgent(agentType);
519
- const commandText = String(req.command);
520
- const submitDelayMs = computeInjectedSubmitDelayMs(agentType, commandText);
521
- ptyProcess.write(commandText);
522
- if (directSubmit) {
523
- // Ink-style CLIs: send CR directly without ESC. ESC before
524
- // CR can be interpreted as Alt+Enter or clear/reset.
525
- setTimeout(() => {
526
- if (ptyProcess && ptyAlive) {
527
- ptyProcess.write("\r");
528
- }
529
- }, submitDelayMs);
530
- } else {
531
- // Codex/others: ESC dismisses autocomplete, then CR submits.
532
- setTimeout(() => {
533
- if (!ptyProcess || !ptyAlive) return;
534
- ptyProcess.write("\x1b");
535
- setTimeout(() => {
536
- if (ptyProcess && ptyAlive) {
537
- ptyProcess.write("\r");
538
- }
539
- }, 100);
540
- }, submitDelayMs);
541
- }
542
- client.write(JSON.stringify({ ok: true }) + "\n");
543
- } else {
544
- client.write(JSON.stringify({ ok: false, error: "pty not ready" }) + "\n");
545
- }
546
- } else if (req.type === PTY_SOCKET_MESSAGE_TYPES.RAW && typeof req.data === "string") {
547
- if (ptyProcess && ptyAlive) {
548
- ptyProcess.write(req.data);
549
- client.write(JSON.stringify({ ok: true }) + "\n");
550
- } else {
551
- client.write(JSON.stringify({ ok: false, error: "pty not ready" }) + "\n");
552
- }
553
- } else if (req.type === PTY_SOCKET_MESSAGE_TYPES.RESIZE && req.cols && req.rows) {
554
- if (ptyProcess && ptyAlive && typeof ptyProcess.resize === "function") {
555
- ptyProcess.resize(req.cols, req.rows);
556
- }
557
- if (term && typeof term.resize === "function") {
558
- try { term.resize(req.cols, req.rows); } catch { /* ignore */ }
559
- }
560
- client.write(JSON.stringify({ ok: true }) + "\n");
561
- } else if (req.type === PTY_SOCKET_MESSAGE_TYPES.SUBSCRIBE) {
562
- outputSubscribers.add(client);
563
- client.write(JSON.stringify({ type: PTY_SOCKET_MESSAGE_TYPES.SUBSCRIBED, ok: true }) + "\n");
564
- const mode = req.mode === PTY_SOCKET_SUBSCRIBE_MODES.SCREEN
565
- ? PTY_SOCKET_SUBSCRIBE_MODES.SCREEN
566
- : PTY_SOCKET_SUBSCRIBE_MODES.FULL;
567
- if (mode === PTY_SOCKET_SUBSCRIBE_MODES.FULL) {
568
- if (outputRingBuffer.length > 0) {
569
- try {
570
- client.write(JSON.stringify({
571
- type: PTY_SOCKET_MESSAGE_TYPES.REPLAY,
572
- data: outputRingBuffer,
573
- encoding: "utf8",
574
- }) + "\n");
575
- } catch {
576
- // ignore replay send errors
577
- }
578
- } else {
579
- serializeSnapshot(PTY_SOCKET_SUBSCRIBE_MODES.FULL).then((snapshot) => {
580
- if (snapshot && snapshot.data) {
581
- try {
582
- client.write(JSON.stringify({
583
- type: PTY_SOCKET_MESSAGE_TYPES.SNAPSHOT,
584
- data: snapshot.data,
585
- encoding: "utf8",
586
- }) + "\n");
587
- } catch {
588
- // ignore snapshot send errors
589
- }
590
- }
591
- }).catch(() => {});
592
- }
593
- } else {
594
- serializeSnapshot(PTY_SOCKET_SUBSCRIBE_MODES.SCREEN).then((snapshot) => {
595
- if (snapshot && snapshot.data) {
596
- try {
597
- client.write(JSON.stringify({
598
- type: PTY_SOCKET_MESSAGE_TYPES.SNAPSHOT,
599
- data: snapshot.data,
600
- encoding: "utf8",
601
- }) + "\n");
602
- } catch {
603
- // ignore snapshot send errors
604
- }
605
- }
606
- }).catch(() => {});
607
- }
608
- } else {
609
- client.write(JSON.stringify({ ok: false, error: "invalid request" }) + "\n");
610
- }
611
- } catch (err) {
612
- client.write(JSON.stringify({ ok: false, error: err.message }) + "\n");
613
- }
614
- }
615
- });
616
- client.on("error", () => {
617
- outputSubscribers.delete(client);
618
- });
619
- client.on("close", () => {
620
- outputSubscribers.delete(client);
621
- });
622
- });
623
- server.listen(injectSockPath);
624
- return server;
625
- }
626
-
627
- function syncOuterTerminalSize() {
628
- const { cols, rows } = getOuterTerminalSize();
629
- if (ptyProcess && ptyAlive && typeof ptyProcess.resize === "function") {
630
- try {
631
- ptyProcess.resize(cols, rows);
632
- } catch {
633
- // ignore outer resize failures
634
- }
635
- }
636
- if (term && typeof term.resize === "function") {
637
- try {
638
- term.resize(cols, rows);
639
- } catch {
640
- // ignore local screen buffer resize failures
641
- }
642
- }
643
- }
644
-
645
- function attachOuterTerminalBridge() {
646
- if (process.stdin && typeof process.stdin.on === "function" && !outerInputHandler) {
647
- outerInputHandler = (chunk) => {
648
- if (!ptyProcess || !ptyAlive) return;
649
- const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
650
- if (!text) return;
651
- try {
652
- ptyProcess.write(text);
653
- } catch {
654
- // ignore transient PTY bridge failures
655
- }
656
- };
657
- process.stdin.on("data", outerInputHandler);
658
- if (typeof process.stdin.resume === "function") {
659
- process.stdin.resume();
660
- }
661
- }
662
-
663
- if (process.stdin && process.stdin.isTTY && typeof process.stdin.setRawMode === "function" && !outerRawModeEnabled) {
664
- try {
665
- process.stdin.setRawMode(true);
666
- outerRawModeEnabled = true;
667
- } catch {
668
- // ignore raw mode failures on unsupported hosts
669
- }
670
- }
671
-
672
- if (process.stdout && process.stdout.isTTY && typeof process.stdout.on === "function" && !outerResizeHandler) {
673
- outerResizeHandler = () => {
674
- syncOuterTerminalSize();
675
- };
676
- process.stdout.on("resize", outerResizeHandler);
677
- syncOuterTerminalSize();
678
- }
679
- }
680
-
681
- function cleanupInjectServer(server) {
682
- for (const sub of outputSubscribers) {
683
- try { sub.destroy(); } catch { /* ignore */ }
684
- }
685
- outputSubscribers.clear();
686
- try {
687
- if (server) server.close();
688
- if (fs.existsSync(injectSockPath)) fs.unlinkSync(injectSockPath);
689
- } catch {
690
- // ignore
691
- }
692
- }
693
-
694
- function flushPending() {
695
- if (!currentPublisher || pendingOutput.length === 0) return;
696
- const chunks = pendingOutput;
697
- pendingOutput = [];
698
- if (!canStreamToPublisher(currentPublisher)) return;
699
- for (const chunk of chunks) {
700
- enqueueSend(currentPublisher, chunk);
701
- }
702
- }
703
-
704
- function deliverChunk(chunk) {
705
- if (!chunk) return;
706
- const cleaned = sanitizeChunk(chunk);
707
- if (!cleaned) return;
708
- const payload = JSON.stringify({ stream: true, delta: cleaned });
709
- if (currentPublisher) {
710
- if (canStreamToPublisher(currentPublisher)) {
711
- enqueueSend(currentPublisher, payload);
712
- }
713
- } else {
714
- pendingOutput.push(payload);
715
- if (pendingOutput.length > 50) pendingOutput.shift();
716
- }
717
- }
718
-
719
- function flushOutput() {
720
- if (!outputBuffer) return;
721
- const chunk = outputBuffer.slice(0, maxChunk);
722
- outputBuffer = outputBuffer.slice(chunk.length);
723
- if (chunk) {
724
- deliverChunk(chunk);
725
- }
726
- if (outputBuffer) {
727
- scheduleFlush();
728
- }
729
- }
730
-
731
- function scheduleFlush() {
732
- if (flushTimer) return;
733
- flushTimer = setTimeout(() => {
734
- flushTimer = null;
735
- flushOutput();
736
- }, 120);
737
- }
738
-
739
- function logNote(note) {
740
- try {
741
- fs.mkdirSync(runDir, { recursive: true });
742
- fs.appendFileSync(logFile, `[${new Date().toISOString()}] ${note}\n`);
743
- } catch {
744
- // ignore
745
- }
746
- }
747
-
748
- // Unified activity state publisher (write + broadcast)
749
- const activityPublisher = createActivityStatePublisher({
750
- agentsFile: agentsFilePath,
751
- subscriber,
752
- projectRoot,
753
- });
754
-
755
- function writeActivityState() {
756
- const snap = activityDetector.getState();
757
- activityPublisher.publish(snap.state, {
758
- since: snap.since,
759
- detail: snap.detail,
760
- }, { reconcile: true, force: true });
761
- }
762
-
763
- activityDetector.onChange((newState, oldState) => {
764
- const snap = activityDetector.getState();
765
- activityPublisher.publish(newState, {
766
- since: snap.since,
767
- previous: oldState,
768
- detail: snap.detail,
769
- });
770
- // Quiet-window detector may classify IDLE sooner than stream fallback timer.
771
- if (newState === "idle" && busy) {
772
- if (idleTimer) {
773
- clearTimeout(idleTimer);
774
- idleTimer = null;
775
- }
776
- if (watchdogTimer) {
777
- clearTimeout(watchdogTimer);
778
- watchdogTimer = null;
779
- }
780
- if (currentPublisher) {
781
- completePublisherResponse("idle");
782
- }
783
- busy = false;
784
- currentPublisher = "";
785
- processQueue();
786
- }
787
- });
788
- // Ensure daemon/dashboard can read initial state immediately after runner boots,
789
- // instead of waiting for the next 30s heartbeat tick.
790
- writeActivityState();
791
-
792
- // Heal daemon inject-stamp desync (disk working, detector idle/ready).
793
- const activityReconcileTimer = setInterval(() => {
794
- try {
795
- reconcileDetectorOwnedActivity({
796
- detector: activityDetector,
797
- publisher: activityPublisher,
798
- agentsFile: agentsFilePath,
799
- subscriber,
800
- });
801
- } catch {
802
- // reconcile must never break the runner
803
- }
804
- }, 2000);
805
- if (typeof activityReconcileTimer.unref === "function") {
806
- activityReconcileTimer.unref();
807
- }
808
-
809
- function attachPty(proc) {
810
- proc.onData((data) => {
811
- const raw = String(data || "");
812
- broadcastOutput(raw);
813
- // Auto-respond to DSR (Device Status Report) cursor position query.
814
- // Ink/codex sends \x1b[6n at startup; node-pty doesn't reply automatically,
815
- // causing codex to crash with "cursor position could not be read".
816
- if (raw.includes("\x1b[6n") || raw.includes("\x1b[?6n")) {
817
- proc.write("\x1b[1;1R");
818
- }
819
- const clean = stripAnsi(raw).replace(/\r\n/g, "\n").replace(/\r/g, "\n");
820
- if (!clean) return;
821
- outputBuffer += clean;
822
- activityDetector.processOutput(clean);
823
- scheduleFlush();
824
- // Ready detection: during TUI startup, reset the quiet timer on each output.
825
- // Once output stops for READY_QUIET_MS, the TUI is considered initialized.
826
- if (!ptyReady && !busy) {
827
- if (readyTimer) clearTimeout(readyTimer);
828
- readyTimer = setTimeout(() => {
829
- readyTimer = null;
830
- if (!ptyReady) {
831
- ptyReady = true;
832
- activityDetector.markReady();
833
- // Discard TUI startup noise accumulated before ready
834
- outputBuffer = "";
835
- pendingOutput = [];
836
- logNote("[internal-pty] TUI ready (output quiet for " + READY_QUIET_MS + "ms)");
837
- processQueue();
838
- }
839
- }, READY_QUIET_MS);
840
- }
841
- if (busy) {
842
- if (idleTimer) clearTimeout(idleTimer);
843
- idleTimer = setTimeout(() => {
844
- idleTimer = null;
845
- if (currentPublisher) {
846
- completePublisherResponse("idle");
847
- }
848
- busy = false;
849
- activityDetector.markIdle();
850
- currentPublisher = "";
851
- processQueue();
852
- }, idleMs);
853
- }
854
- });
855
-
856
- proc.onExit(({ exitCode, signal }) => {
857
- // Skip if this process has been replaced (e.g., by restartPty)
858
- if (proc !== ptyProcess) return;
859
-
860
- ptyAlive = false;
861
- ptyReady = false;
862
- if (readyTimer) {
863
- clearTimeout(readyTimer);
864
- readyTimer = null;
865
- }
866
- if (outputBuffer) {
867
- flushOutput();
868
- }
869
- if (flushTimer) {
870
- clearTimeout(flushTimer);
871
- flushTimer = null;
872
- }
873
- if (idleTimer) {
874
- clearTimeout(idleTimer);
875
- idleTimer = null;
876
- }
877
- if (watchdogTimer) {
878
- clearTimeout(watchdogTimer);
879
- watchdogTimer = null;
880
- }
881
- const note = `[internal-pty] process exited code=${exitCode} signal=${signal || ""}`.trim();
882
- if (currentPublisher) completePublisherResponse("exit", note);
883
- logNote(note);
884
-
885
- // Reset busy state
886
- busy = false;
887
- activityDetector.markIdle();
888
- currentPublisher = "";
889
-
890
- // If stop() was called, let the runner exit
891
- if (!running) return;
892
-
893
- // Auto-restart with backoff
894
- const elapsed = Date.now() - lastSpawnTime;
895
- if (elapsed > RESTART_STABLE_MS) {
896
- restartCount = 0; // Process was stable long enough, reset counter
897
- }
898
- restartCount++;
899
-
900
- if (restartCount <= MAX_RESTARTS) {
901
- const delay = Math.min(restartCount * RESTART_DELAY_MS, RESTART_BACKOFF_CAP_MS);
902
- logNote(`Auto-restarting PTY in ${delay}ms (attempt ${restartCount}/${MAX_RESTARTS})`);
903
- setTimeout(() => {
904
- if (!running) return;
905
- try {
906
- ptyProcess = spawnPtyProcess();
907
- processQueue();
908
- } catch (err) {
909
- logNote(`Restart failed: ${err.message || err}`);
910
- // Keep retrying instead of falling back
911
- restartCount++;
912
- if (restartCount <= MAX_RESTARTS) {
913
- const retryDelay = Math.min(restartCount * RESTART_DELAY_MS, RESTART_BACKOFF_CAP_MS);
914
- setTimeout(() => {
915
- if (!running) return;
916
- try {
917
- ptyProcess = spawnPtyProcess();
918
- processQueue();
919
- } catch {
920
- logNote(`PTY spawn keeps failing after ${restartCount} attempts. Agent is offline.`);
921
- }
922
- }, retryDelay);
923
- } else {
924
- logNote(`PTY spawn failed after ${MAX_RESTARTS} attempts. Agent is offline. Fix the issue and re-launch.`);
925
- }
926
- }
927
- }, delay);
928
- } else {
929
- logNote(`PTY crashed ${MAX_RESTARTS} times within ${RESTART_STABLE_MS}ms. Agent is offline. Fix the issue and re-launch.`);
930
- }
931
- });
932
- }
933
-
934
- function spawnPtyProcess() {
935
- lastSpawnTime = Date.now();
936
- ptyReady = false;
937
- if (readyTimer) {
938
- clearTimeout(readyTimer);
939
- readyTimer = null;
940
- }
941
- const { cols, rows } = getOuterTerminalSize();
942
- const proc = pty.spawn(command, args, {
943
- name: "xterm-256color",
944
- cols,
945
- rows,
946
- cwd: projectRoot,
947
- env,
948
- });
949
- ptyAlive = true;
950
- attachPty(proc);
951
- return proc;
952
- }
953
-
954
- function restartPty(reason) {
955
- if (!running) return;
956
- logNote(`Restarting PTY: ${reason}`);
957
- ptyAlive = false;
958
- ptyReady = false;
959
- if (outputBuffer) {
960
- flushOutput();
961
- }
962
- // Clear reference first so the old onExit handler skips (proc !== ptyProcess)
963
- const oldPty = ptyProcess;
964
- ptyProcess = null;
965
- try {
966
- if (oldPty) oldPty.kill();
967
- } catch {
968
- // ignore
969
- }
970
- ptyProcess = spawnPtyProcess();
971
- }
972
-
973
- const stop = () => {
974
- running = false;
975
- clearInterval(activityReconcileTimer);
976
- cleanupInjectServer(injectServer);
977
- if (process.stdin && outerInputHandler) {
978
- if (typeof process.stdin.off === "function") {
979
- process.stdin.off("data", outerInputHandler);
980
- } else if (typeof process.stdin.removeListener === "function") {
981
- process.stdin.removeListener("data", outerInputHandler);
982
- }
983
- outerInputHandler = null;
984
- }
985
- if (process.stdout && outerResizeHandler) {
986
- if (typeof process.stdout.off === "function") {
987
- process.stdout.off("resize", outerResizeHandler);
988
- } else if (typeof process.stdout.removeListener === "function") {
989
- process.stdout.removeListener("resize", outerResizeHandler);
990
- }
991
- outerResizeHandler = null;
992
- }
993
- if (process.stdin && outerRawModeEnabled && typeof process.stdin.setRawMode === "function") {
994
- try {
995
- process.stdin.setRawMode(false);
996
- } catch {
997
- // ignore raw mode cleanup failures
998
- }
999
- outerRawModeEnabled = false;
1000
- }
1001
- try {
1002
- if (ptyProcess) ptyProcess.kill();
1003
- } catch {
1004
- // ignore
1005
- }
1006
- };
1007
-
1008
- process.on("SIGTERM", stop);
1009
- process.on("SIGINT", stop);
1010
- // Ignore SIGHUP so terminal closure doesn't kill the ptyRunner
1011
- // while the daemon is still alive.
1012
- process.on("SIGHUP", () => {});
1013
-
1014
- ptyProcess = spawnPtyProcess();
1015
- attachOuterTerminalBridge();
1016
-
1017
- function processQueue() {
1018
- if (busy || messageQueue.length === 0 || !running || !ptyAlive || !ptyReady) return;
1019
- const next = messageQueue.shift();
1020
- if (!next) return;
1021
- busy = true;
1022
- activityDetector.markWorking();
1023
- currentPublisher = next.publisher;
1024
- flushPending();
1025
- if (next.text) {
1026
- if (next.raw) {
1027
- ptyProcess.write(next.text);
1028
- } else {
1029
- // Write text first, then send Enter separately.
1030
- // Codex Ink TUI requires text and submit key as separate writes.
1031
- ptyProcess.write(next.text);
1032
- setTimeout(() => {
1033
- if (ptyProcess && ptyAlive) {
1034
- // Drop the local TUI input echo from any forwarded stream output.
1035
- outputBuffer = "";
1036
- const directSubmit = isDirectSubmitAgent(agentType);
1037
- if (directSubmit) {
1038
- // Ink-style CLIs: send CR directly without ESC. ESC before CR
1039
- // can be interpreted as Alt+Enter or clear/reset.
1040
- ptyProcess.write("\r");
1041
- } else {
1042
- // Codex/others: ESC dismisses autocomplete, then CR submits.
1043
- ptyProcess.write("\x1b");
1044
- setTimeout(() => {
1045
- if (ptyProcess && ptyAlive) {
1046
- ptyProcess.write("\r");
1047
- }
1048
- }, 100);
1049
- }
1050
- }
1051
- }, 200);
1052
- }
1053
- }
1054
- if (watchdogTimer) clearTimeout(watchdogTimer);
1055
- watchdogTimer = setTimeout(() => {
1056
- watchdogTimer = null;
1057
- if (!busy) return;
1058
- const timeoutNote = `[internal-pty] task timeout; restarting PTY`;
1059
- if (currentPublisher) {
1060
- completePublisherResponse("timeout", timeoutNote);
1061
- }
1062
- logNote(timeoutNote);
1063
- restartPty("task timeout");
1064
- busy = false;
1065
- activityDetector.markIdle();
1066
- currentPublisher = "";
1067
- processQueue();
1068
- }, watchdogMs);
1069
- }
1070
-
1071
- // Heartbeat to keep agent "online" in bus status
1072
- let lastHeartbeat = 0;
1073
- const HEARTBEAT_INTERVAL = 30000;
1074
- const updateHeartbeat = () => {
1075
- try {
1076
- spawnSync("ufoo", ["bus", "check", subscriber], {
1077
- cwd: projectRoot,
1078
- env: { ...process.env, UFOO_SUBSCRIBER_ID: subscriber },
1079
- stdio: "ignore",
1080
- timeout: 5000,
1081
- });
1082
- } catch {
1083
- // ignore heartbeat errors
1084
- }
1085
- writeActivityState();
1086
- };
1087
-
1088
- while (running) {
1089
- // Periodic heartbeat
1090
- const now = Date.now();
1091
- if (now - lastHeartbeat > HEARTBEAT_INTERVAL) {
1092
- updateHeartbeat();
1093
- lastHeartbeat = now;
1094
- }
1095
-
1096
- const claims = claimQueuedEvents(queueFile);
1097
- if (claims.length > 0) {
1098
- const agents = readAgentsMap(agentsFilePath);
1099
- for (const claim of claims) {
1100
- const evt = claim.event;
1101
- try {
1102
- const input = buildPtyInputFromEvent(evt, subscriber, agents);
1103
- if (!input) {
1104
- claim.queue.completeClaim(claim);
1105
- continue;
1106
- }
1107
- const { raw, text } = input;
1108
- if (messageQueue.length >= maxQueue) {
1109
- messageQueue.shift();
1110
- }
1111
- const publisher = typeof evt.publisher === "object" && evt.publisher
1112
- ? (evt.publisher.subscriber || evt.publisher.nickname || "unknown")
1113
- : (evt.publisher || "unknown");
1114
- messageQueue.push({ publisher, raw, text });
1115
- claim.queue.completeClaim(claim);
1116
- } catch {
1117
- claim.queue.restoreClaim(claim);
1118
- }
1119
- }
1120
- }
1121
- processQueue();
1122
- // eslint-disable-next-line no-await-in-loop
1123
- await sleep(200);
1124
- }
1125
- }
1126
-
1127
- module.exports = {
1128
- appendStartupBootstrapArg,
1129
- buildPtyInputFromEvent,
1130
- parseInputMessage,
1131
- rewriteTitleOscPrefix,
1132
- resolvePtyBootstrapArgs,
1133
- resolveCommand,
1134
- runPtyRunner,
1135
- };