u-foo 4.0.3 → 4.0.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +239 -19
- package/README.zh-CN.md +3 -3
- package/bin/ucode.js +10 -2
- package/bin/ufoo.js +3 -0
- package/dist/tui/darwin-arm64/ufoo-tui +0 -0
- package/dist/tui/darwin-x64/ufoo-tui +0 -0
- package/dist/tui/linux-arm64/ufoo-tui +0 -0
- package/dist/tui/linux-x64/ufoo-tui +0 -0
- package/{OBSERVABILITY.md → docs/OBSERVABILITY.md} +3 -3
- package/docs/README.md +27 -0
- package/extensions/ufoo-browser/LICENSE +152 -0
- package/extensions/ufoo-browser/NOTICE +10 -0
- package/extensions/ufoo-browser/README.md +30 -0
- package/extensions/ufoo-browser/background.js +409 -0
- package/extensions/ufoo-browser/icons/icon-128.png +0 -0
- package/extensions/ufoo-browser/icons/icon-16.png +0 -0
- package/extensions/ufoo-browser/icons/icon-256.png +0 -0
- package/extensions/ufoo-browser/icons/icon-32.png +0 -0
- package/extensions/ufoo-browser/icons/icon-48.png +0 -0
- package/extensions/ufoo-browser/icons/logo.png +0 -0
- package/extensions/ufoo-browser/icons/toolbar-16.png +0 -0
- package/extensions/ufoo-browser/icons/toolbar-32.png +0 -0
- package/extensions/ufoo-browser/icons/toolbar-logo.png +0 -0
- package/extensions/ufoo-browser/manifest.json +30 -0
- package/extensions/ufoo-browser/popup.css +71 -0
- package/extensions/ufoo-browser/popup.html +44 -0
- package/extensions/ufoo-browser/popup.js +153 -0
- package/package.json +7 -5
- package/scripts/postinstall.js +6 -0
- package/src/agents/capabilities/browser/index.js +49 -0
- package/src/agents/capabilities/coding/backgroundHooks.js +94 -0
- package/src/agents/capabilities/coding/index.js +30 -1
- package/src/agents/capabilities/index.js +5 -2
- package/src/agents/capabilities/planning/index.js +44 -5
- package/src/agents/capabilities/turnRecall/index.js +341 -0
- package/src/agents/controller/controllerToolExecutor.js +2 -2
- package/src/agents/internal/internalRunner.js +30 -8
- package/src/agents/internal/taskControl.js +107 -0
- package/src/agents/profiles/coding.js +1 -1
- package/src/agents/profiles/main.js +1 -1
- package/src/agents/prompts/mainAgent.js +1 -0
- package/src/agents/prompts/native/toolDescriptions/bash.js +7 -1
- package/src/agents/providers/claudeSessionFiles.js +1 -1
- package/src/agents/providers/codexThreadProvider.js +6 -1
- package/src/agents/providers/credentials/agy.js +171 -0
- package/src/agents/providers/directAuthStatus.js +20 -2
- package/src/agents/providers/modelsCatalog.js +26 -5
- package/src/agents/providers/nativeTransport.js +145 -73
- package/src/agents/providers/providerId.js +17 -0
- package/src/agents/providers/runtimeConfig.js +67 -20
- package/src/agents/providers/transports/antigravityTransport.js +242 -0
- package/src/agents/providers/transports/index.js +1 -0
- package/src/agents/providers/transports/openaiChatTransport.js +3 -2
- package/src/agents/providers/transports/openaiResponsesTransport.js +2 -1
- package/src/agents/providers/transports/responsesProtocol.js +119 -18
- package/src/agents/providers/transports/transportContract.js +1 -0
- package/src/agents/providers/upstreamRuntime.js +3 -1
- package/src/agents/runtime/context/contextBudget.js +1 -19
- package/src/agents/runtime/context/contextWindow.js +5 -0
- package/src/agents/runtime/context/replayHistory.js +16 -10
- package/src/agents/runtime/context/runtimeStore.js +0 -1
- package/src/agents/runtime/context/sessionJournal.js +1 -1
- package/src/agents/runtime/context/slidingWindowManager.js +792 -0
- package/src/agents/runtime/context/topicSelector.js +338 -0
- package/src/agents/runtime/context/turnAnalyzer.js +767 -0
- package/src/agents/runtime/context/turnIndexStore.js +515 -0
- package/src/agents/runtime/core/agentLoop.js +140 -35
- package/src/agents/runtime/core/executionBudget.js +2 -1
- package/src/agents/runtime/core/toolErrorGuard.js +39 -0
- package/src/agents/runtime/createAgentRuntime.js +80 -7
- package/src/agents/runtime/index.js +5 -0
- package/src/agents/runtime/protocol/materialize.js +1 -1
- package/src/agents/runtime/tasks/hooks.js +137 -0
- package/src/app/chat/ChatController.js +8 -4
- package/src/app/chat/daemonMessageRouter.js +3 -1
- package/src/app/chat/inputSubmitHandler.js +2 -2
- package/src/app/chat/transport.js +1 -1
- package/src/app/cli/browserCommands.js +340 -0
- package/src/app/cli/busCoreCommands.js +63 -3
- package/src/app/cli/features/doctor.js +21 -0
- package/src/app/cli/metricsCommands.js +1 -1
- package/src/app/cli/run.js +81 -1
- package/src/app/cli/setupCommands.js +200 -0
- package/src/code/UcodeController.js +31 -1
- package/src/code/agent.js +76 -25
- package/src/code/busConsumer.js +13 -12
- package/src/code/commands.js +0 -1
- package/src/code/context/assembler.js +11 -88
- package/src/code/context/planGraphService.js +121 -6
- package/src/code/context/planProjection.js +10 -2
- package/src/code/context/reducers.js +172 -4
- package/src/code/context/stateCommit.js +0 -32
- package/src/code/context/transcript.js +7 -4
- package/src/code/internalThread.js +9 -1
- package/src/code/launcher/ucode.js +4 -2
- package/src/code/modelCommand.js +6 -5
- package/src/code/nativeRunner.js +232 -62
- package/src/code/repl.js +27 -1
- package/src/code/runtime/agentWakeup.js +20 -3
- package/src/code/runtime/backgroundWakeHost.js +45 -0
- package/src/code/runtime/taskFocusContext.js +7 -0
- package/src/code/runtime/taskLoop.js +24 -1
- package/src/code/sessionStore.js +14 -10
- package/src/code/taskDecomposer.js +16 -7
- package/src/code/tools/backgroundProcess.js +23 -0
- package/src/code/tools/bash.js +764 -12
- package/src/code/tools/executor.js +13 -4
- package/src/code/tools/planGraph.js +1 -0
- package/src/code/tools/specs.js +62 -4
- package/src/code/tools/taskRun.js +38 -0
- package/src/config.js +92 -6
- package/src/coordination/bus/index.js +2 -2
- package/src/coordination/bus/message.js +10 -1
- package/src/coordination/bus/nickname.js +3 -1
- package/src/coordination/bus/subscriber.js +25 -10
- package/src/coordination/bus/utils.js +4 -0
- package/src/coordination/bus/wakeEndpoint.js +198 -0
- package/src/coordination/history/agentPerformance.js +18 -18
- package/src/coordination/history/agentTrace.js +7 -3
- package/src/coordination/state/paths.js +4 -0
- package/src/coordination/state/workspaceAccess.js +3 -1
- package/src/orchestration/groups/modelConfig.js +66 -0
- package/src/orchestration/groups/validateTemplate.js +2 -0
- package/src/runtime/browser/broker.js +1027 -0
- package/src/runtime/browser/brokerClient.js +108 -0
- package/src/runtime/browser/componentInstaller.js +275 -0
- package/src/runtime/browser/installState.js +329 -0
- package/src/runtime/browser/manifest.js +145 -0
- package/src/runtime/browser/native-host-runner.js +198 -0
- package/src/runtime/browser/nativeHost.js +213 -0
- package/src/runtime/browser/nativeMessagingProtocol.js +50 -0
- package/src/runtime/browser/paths.js +134 -0
- package/src/runtime/browser/playwrightSession.js +614 -0
- package/src/runtime/daemon/agentHost.js +175 -28
- package/src/runtime/daemon/busBridge.js +2 -1
- package/src/runtime/daemon/deliveryScheduler.js +70 -2
- package/src/runtime/daemon/globalDaemon.js +20 -0
- package/src/runtime/daemon/groupOrchestrator.js +20 -1
- package/src/runtime/daemon/index.js +6 -4
- package/src/runtime/daemon/ops.js +14 -8
- package/src/tools/handlers/listAgents.js +1 -1
- package/src/tools/handlers/readBusSummary.js +1 -1
- package/src/tools/handlers/routeAgent.js +122 -5
- package/src/tools/schemaFixtures.js +1 -1
- package/src/ui/agentSurface.js +60 -6
- package/src/ui/format/index.js +34 -2
- package/src/ui/format/markdownRenderer.js +4 -2
- package/src/ui/rustChatHost.js +22 -7
- package/src/ui/rustMultiSession.js +14 -2
- package/src/ui/rustUcodeHost.js +249 -80
- package/src/ui/ucodeAgentSession.js +88 -0
- package/templates/groups/build-lane.json +57 -3
- package/templates/groups/build-ultra.json +114 -6
- package/templates/groups/design-system.json +57 -3
- package/templates/groups/product-discovery.json +57 -3
- package/templates/groups/ui-plan-review.json +57 -3
- package/templates/groups/ui-polish.json +57 -3
- package/templates/groups/verify-ship.json +57 -3
- package/src/agents/runtime/context/checkpointStore.js +0 -38
- package/src/agents/runtime/context/compaction.js +0 -151
package/src/code/tools/bash.js
CHANGED
|
@@ -1,28 +1,163 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const crypto = require("crypto");
|
|
4
|
+
const fs = require("fs");
|
|
5
|
+
const path = require("path");
|
|
1
6
|
const { spawn, spawnSync } = require("child_process");
|
|
2
7
|
const { normalizeWorkspaceRoot } = require("./common");
|
|
3
8
|
|
|
4
9
|
const MAX_TIMEOUT_MS = 600000;
|
|
5
10
|
const MAX_BUFFER_BYTES = 2 * 1024 * 1024;
|
|
11
|
+
const DEFAULT_STARTUP_WAIT_MS = 2500;
|
|
12
|
+
const MAX_STARTUP_WAIT_MS = 15000;
|
|
13
|
+
const DEFAULT_LOG_MAX_BYTES = 32768;
|
|
14
|
+
const MIN_LOG_MAX_BYTES = 256;
|
|
15
|
+
const MAX_LOG_MAX_BYTES = 200000;
|
|
16
|
+
const DEFAULT_LOG_TAIL_LINES = 80;
|
|
17
|
+
const DEFAULT_STATUS_TAIL_LINES = 20;
|
|
18
|
+
const DEFAULT_STOP_TAIL_LINES = 30;
|
|
19
|
+
const MAX_LOG_TAIL_LINES = 500;
|
|
20
|
+
const MAX_LOG_WAIT_MS = 10000;
|
|
21
|
+
const VALID_ACTIONS = new Set(["run", "logs", "status", "list", "stop"]);
|
|
22
|
+
const SAFE_BG_ID_RE = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/;
|
|
6
23
|
|
|
7
24
|
function normalizeBashInput(input = {}, options = {}) {
|
|
25
|
+
const rawAction = input.action == null ? "run" : String(input.action).trim().toLowerCase();
|
|
26
|
+
const action = rawAction || "run";
|
|
8
27
|
const command = String(input.command || "").trim();
|
|
9
28
|
const workspaceRoot = normalizeWorkspaceRoot(options.workspaceRoot, options.cwd);
|
|
10
29
|
const timeoutMs = Number.isFinite(input.timeoutMs)
|
|
11
30
|
? Math.min(MAX_TIMEOUT_MS, Math.max(100, Math.floor(input.timeoutMs)))
|
|
12
31
|
: 60000;
|
|
13
|
-
|
|
32
|
+
const background = Boolean(input.background);
|
|
33
|
+
const startupWaitMs = Number.isFinite(input.startupWaitMs)
|
|
34
|
+
? Math.min(MAX_STARTUP_WAIT_MS, Math.max(0, Math.floor(input.startupWaitMs)))
|
|
35
|
+
: DEFAULT_STARTUP_WAIT_MS;
|
|
36
|
+
const backgroundId = String(input.backgroundId || "").trim();
|
|
37
|
+
const hasOffset = Number.isFinite(input.offset) && input.offset >= 0;
|
|
38
|
+
const offset = hasOffset ? Math.floor(input.offset) : null;
|
|
39
|
+
const tailLines = Number.isFinite(input.tailLines)
|
|
40
|
+
? Math.min(MAX_LOG_TAIL_LINES, Math.max(1, Math.floor(input.tailLines)))
|
|
41
|
+
: null;
|
|
42
|
+
const maxBytes = Number.isFinite(input.maxBytes)
|
|
43
|
+
? Math.min(MAX_LOG_MAX_BYTES, Math.max(MIN_LOG_MAX_BYTES, Math.floor(input.maxBytes)))
|
|
44
|
+
: DEFAULT_LOG_MAX_BYTES;
|
|
45
|
+
const waitMs = Number.isFinite(input.waitMs)
|
|
46
|
+
? Math.min(MAX_LOG_WAIT_MS, Math.max(0, Math.floor(input.waitMs)))
|
|
47
|
+
: 0;
|
|
48
|
+
return {
|
|
49
|
+
action,
|
|
50
|
+
command,
|
|
51
|
+
workspaceRoot,
|
|
52
|
+
timeoutMs,
|
|
53
|
+
background,
|
|
54
|
+
startupWaitMs,
|
|
55
|
+
backgroundId,
|
|
56
|
+
offset,
|
|
57
|
+
tailLines,
|
|
58
|
+
maxBytes,
|
|
59
|
+
waitMs,
|
|
60
|
+
};
|
|
14
61
|
}
|
|
15
62
|
|
|
16
|
-
function
|
|
17
|
-
|
|
18
|
-
|
|
63
|
+
function getBgDir(workspaceRoot) {
|
|
64
|
+
return path.join(workspaceRoot, ".ufoo", "agent", "bg");
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function getBgRecordPath(workspaceRoot, backgroundId) {
|
|
68
|
+
return path.join(getBgDir(workspaceRoot), `${backgroundId}.json`);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function getBgLogPath(workspaceRoot, backgroundId) {
|
|
72
|
+
return path.join(getBgDir(workspaceRoot), `${backgroundId}.log`);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function getRelativeBgLogPath(backgroundId) {
|
|
76
|
+
return path.posix.join(".ufoo", "agent", "bg", `${backgroundId}.log`);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function generateBackgroundId() {
|
|
80
|
+
return `bg_${Date.now().toString(36)}_${crypto.randomBytes(3).toString("hex")}`;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function writeJsonAtomic(filePath, value) {
|
|
84
|
+
const dir = path.dirname(filePath);
|
|
85
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
86
|
+
const tmpPath = `${filePath}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.tmp`;
|
|
87
|
+
fs.writeFileSync(tmpPath, `${JSON.stringify(value, null, 2)}\n`, "utf8");
|
|
88
|
+
fs.renameSync(tmpPath, filePath);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function readBackgroundRecord(workspaceRoot, backgroundId) {
|
|
92
|
+
if (!SAFE_BG_ID_RE.test(backgroundId)) return null;
|
|
93
|
+
const filePath = getBgRecordPath(workspaceRoot, backgroundId);
|
|
94
|
+
try {
|
|
95
|
+
const raw = fs.readFileSync(filePath, "utf8");
|
|
96
|
+
const parsed = JSON.parse(raw);
|
|
97
|
+
return parsed && typeof parsed === "object" ? parsed : null;
|
|
98
|
+
} catch {
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function writeBackgroundRecord(workspaceRoot, record) {
|
|
104
|
+
if (!record || !SAFE_BG_ID_RE.test(record.backgroundId || "")) return;
|
|
105
|
+
try {
|
|
106
|
+
writeJsonAtomic(getBgRecordPath(workspaceRoot, record.backgroundId), record);
|
|
107
|
+
} catch {
|
|
108
|
+
// Workspace may have been cleaned up after a test or task finished.
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function updateBackgroundRecord(workspaceRoot, backgroundId, updater) {
|
|
113
|
+
const current = readBackgroundRecord(workspaceRoot, backgroundId);
|
|
114
|
+
if (!current) return null;
|
|
115
|
+
const next = updater(current);
|
|
116
|
+
if (!next || typeof next !== "object") return current;
|
|
117
|
+
writeBackgroundRecord(workspaceRoot, next);
|
|
118
|
+
return next;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function isPidAlive(pid) {
|
|
122
|
+
const num = Number(pid);
|
|
123
|
+
if (!Number.isInteger(num) || num <= 0) return false;
|
|
124
|
+
try {
|
|
125
|
+
process.kill(num, 0);
|
|
126
|
+
return true;
|
|
127
|
+
} catch (err) {
|
|
128
|
+
return Boolean(err && err.code === "EPERM");
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function terminatePidGroup(pid, signal = "SIGTERM") {
|
|
133
|
+
const num = Number(pid);
|
|
134
|
+
if (!Number.isInteger(num) || num <= 0) return false;
|
|
135
|
+
let signaled = false;
|
|
136
|
+
if (process.platform !== "win32") {
|
|
19
137
|
try {
|
|
20
|
-
process.kill(-
|
|
21
|
-
|
|
138
|
+
process.kill(-num, signal);
|
|
139
|
+
signaled = true;
|
|
140
|
+
} catch {
|
|
141
|
+
// Process group may already have exited; fall back to direct PID.
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
if (!signaled) {
|
|
145
|
+
try {
|
|
146
|
+
process.kill(num, signal);
|
|
147
|
+
signaled = true;
|
|
22
148
|
} catch {
|
|
23
|
-
//
|
|
149
|
+
// Process already exited.
|
|
24
150
|
}
|
|
25
151
|
}
|
|
152
|
+
return signaled;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function terminateChild(child, signal = "SIGTERM") {
|
|
156
|
+
if (!child) return;
|
|
157
|
+
if (child.pid) {
|
|
158
|
+
terminatePidGroup(child.pid, signal);
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
26
161
|
try {
|
|
27
162
|
child.kill(signal);
|
|
28
163
|
} catch {
|
|
@@ -30,9 +165,610 @@ function terminateChild(child, signal = "SIGTERM") {
|
|
|
30
165
|
}
|
|
31
166
|
}
|
|
32
167
|
|
|
168
|
+
function reconcileBackgroundRecord(workspaceRoot, backgroundId) {
|
|
169
|
+
const record = readBackgroundRecord(workspaceRoot, backgroundId);
|
|
170
|
+
if (!record) return null;
|
|
171
|
+
const alive = isPidAlive(record.pid);
|
|
172
|
+
if (record.status === "running" && !alive) {
|
|
173
|
+
const updated = {
|
|
174
|
+
...record,
|
|
175
|
+
status: "exited",
|
|
176
|
+
endedAt: record.endedAt || new Date().toISOString(),
|
|
177
|
+
};
|
|
178
|
+
writeBackgroundRecord(workspaceRoot, updated);
|
|
179
|
+
return { ...updated, running: false };
|
|
180
|
+
}
|
|
181
|
+
return {
|
|
182
|
+
...record,
|
|
183
|
+
running: record.status === "running" && alive,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function getLogSizeBytes(workspaceRoot, backgroundId) {
|
|
188
|
+
try {
|
|
189
|
+
const st = fs.statSync(getBgLogPath(workspaceRoot, backgroundId));
|
|
190
|
+
return Number.isFinite(st.size) ? st.size : 0;
|
|
191
|
+
} catch {
|
|
192
|
+
return 0;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function readBackgroundLogSlice(absLogPath, { offset = null, tailLines = DEFAULT_LOG_TAIL_LINES, maxBytes = DEFAULT_LOG_MAX_BYTES } = {}) {
|
|
197
|
+
let totalBytes = 0;
|
|
198
|
+
try {
|
|
199
|
+
const st = fs.statSync(absLogPath);
|
|
200
|
+
totalBytes = Number.isFinite(st.size) ? st.size : 0;
|
|
201
|
+
} catch {
|
|
202
|
+
return { logOutput: "", offset: 0, nextOffset: 0, totalBytes: 0, truncated: false };
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const clampedMaxBytes = Number.isFinite(maxBytes)
|
|
206
|
+
? Math.min(MAX_LOG_MAX_BYTES, Math.max(MIN_LOG_MAX_BYTES, Math.floor(maxBytes)))
|
|
207
|
+
: DEFAULT_LOG_MAX_BYTES;
|
|
208
|
+
|
|
209
|
+
if (Number.isInteger(offset) && offset >= 0) {
|
|
210
|
+
const startOffset = Math.min(totalBytes, offset);
|
|
211
|
+
const toRead = Math.min(clampedMaxBytes, totalBytes - startOffset);
|
|
212
|
+
if (toRead <= 0) {
|
|
213
|
+
return {
|
|
214
|
+
logOutput: "",
|
|
215
|
+
offset: startOffset,
|
|
216
|
+
nextOffset: startOffset,
|
|
217
|
+
totalBytes,
|
|
218
|
+
truncated: false,
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
const buf = Buffer.allocUnsafe(toRead);
|
|
222
|
+
let bytesRead = 0;
|
|
223
|
+
const fd = fs.openSync(absLogPath, "r");
|
|
224
|
+
try {
|
|
225
|
+
bytesRead = fs.readSync(fd, buf, 0, toRead, startOffset);
|
|
226
|
+
} finally {
|
|
227
|
+
try { fs.closeSync(fd); } catch {}
|
|
228
|
+
}
|
|
229
|
+
const logOutput = buf.subarray(0, bytesRead).toString("utf8");
|
|
230
|
+
const nextOffset = startOffset + bytesRead;
|
|
231
|
+
return {
|
|
232
|
+
logOutput,
|
|
233
|
+
offset: startOffset,
|
|
234
|
+
nextOffset,
|
|
235
|
+
totalBytes,
|
|
236
|
+
truncated: nextOffset < totalBytes,
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
if (totalBytes <= 0) {
|
|
241
|
+
return { logOutput: "", offset: 0, nextOffset: 0, totalBytes: 0, truncated: false };
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
const readStart = Math.max(0, totalBytes - clampedMaxBytes);
|
|
245
|
+
const toRead = totalBytes - readStart;
|
|
246
|
+
const buf = Buffer.allocUnsafe(toRead);
|
|
247
|
+
let bytesRead = 0;
|
|
248
|
+
const fd = fs.openSync(absLogPath, "r");
|
|
249
|
+
try {
|
|
250
|
+
bytesRead = fs.readSync(fd, buf, 0, toRead, readStart);
|
|
251
|
+
} finally {
|
|
252
|
+
try { fs.closeSync(fd); } catch {}
|
|
253
|
+
}
|
|
254
|
+
const rawChunk = buf.subarray(0, bytesRead).toString("utf8");
|
|
255
|
+
const linesLimit = Number.isFinite(tailLines)
|
|
256
|
+
? Math.min(MAX_LOG_TAIL_LINES, Math.max(1, Math.floor(tailLines)))
|
|
257
|
+
: DEFAULT_LOG_TAIL_LINES;
|
|
258
|
+
const hasTrailingNewline = rawChunk.endsWith("\n");
|
|
259
|
+
const body = hasTrailingNewline ? rawChunk.slice(0, -1) : rawChunk;
|
|
260
|
+
const allLines = body ? body.split("\n") : [];
|
|
261
|
+
const slicedLines = allLines.length > linesLimit ? allLines.slice(-linesLimit) : allLines;
|
|
262
|
+
const logOutput = slicedLines.length ? `${slicedLines.join("\n")}${hasTrailingNewline ? "\n" : ""}` : "";
|
|
263
|
+
const usedOffset = Math.max(0, totalBytes - Buffer.byteLength(logOutput, "utf8"));
|
|
264
|
+
return {
|
|
265
|
+
logOutput,
|
|
266
|
+
offset: usedOffset,
|
|
267
|
+
nextOffset: totalBytes,
|
|
268
|
+
totalBytes,
|
|
269
|
+
truncated: readStart > 0 || allLines.length > linesLimit,
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function buildBackgroundPayload(action, workspaceRoot, record, slice, overrides = {}) {
|
|
274
|
+
const exitCode = typeof record.exitCode === "number" ? record.exitCode : null;
|
|
275
|
+
return {
|
|
276
|
+
ok: true,
|
|
277
|
+
kind: "background_bash",
|
|
278
|
+
action,
|
|
279
|
+
workspaceRoot,
|
|
280
|
+
backgroundId: record.backgroundId,
|
|
281
|
+
pid: record.pid,
|
|
282
|
+
running: Boolean(record.running),
|
|
283
|
+
status: record.status,
|
|
284
|
+
code: exitCode,
|
|
285
|
+
exitCode,
|
|
286
|
+
signal: record.signal || "",
|
|
287
|
+
command: record.command || "",
|
|
288
|
+
startedAt: record.startedAt || null,
|
|
289
|
+
endedAt: record.endedAt || null,
|
|
290
|
+
logPath: record.logPath || getRelativeBgLogPath(record.backgroundId),
|
|
291
|
+
offset: slice.offset,
|
|
292
|
+
nextOffset: slice.nextOffset,
|
|
293
|
+
totalBytes: slice.totalBytes,
|
|
294
|
+
truncated: Boolean(slice.truncated),
|
|
295
|
+
logOutput: slice.logOutput,
|
|
296
|
+
stdout: slice.logOutput,
|
|
297
|
+
stderr: "",
|
|
298
|
+
error: "",
|
|
299
|
+
...overrides,
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function validateBackgroundIdInput(action, workspaceRoot, backgroundId) {
|
|
304
|
+
if (!backgroundId) {
|
|
305
|
+
return {
|
|
306
|
+
ok: false,
|
|
307
|
+
kind: "background_bash",
|
|
308
|
+
action,
|
|
309
|
+
workspaceRoot,
|
|
310
|
+
error: "backgroundId is required",
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
if (!SAFE_BG_ID_RE.test(backgroundId)) {
|
|
314
|
+
return {
|
|
315
|
+
ok: false,
|
|
316
|
+
kind: "background_bash",
|
|
317
|
+
action,
|
|
318
|
+
workspaceRoot,
|
|
319
|
+
backgroundId,
|
|
320
|
+
error: "invalid backgroundId",
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
return null;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
function listBackgroundProcesses(workspaceRoot) {
|
|
327
|
+
const dir = getBgDir(workspaceRoot);
|
|
328
|
+
let entries = [];
|
|
329
|
+
try {
|
|
330
|
+
entries = fs.readdirSync(dir);
|
|
331
|
+
} catch {
|
|
332
|
+
return [];
|
|
333
|
+
}
|
|
334
|
+
const records = [];
|
|
335
|
+
for (const name of entries) {
|
|
336
|
+
if (!name.endsWith(".json")) continue;
|
|
337
|
+
const backgroundId = name.slice(0, -5);
|
|
338
|
+
const reconciled = reconcileBackgroundRecord(workspaceRoot, backgroundId);
|
|
339
|
+
if (!reconciled) continue;
|
|
340
|
+
records.push({
|
|
341
|
+
backgroundId: reconciled.backgroundId,
|
|
342
|
+
pid: reconciled.pid,
|
|
343
|
+
running: Boolean(reconciled.running),
|
|
344
|
+
status: reconciled.status,
|
|
345
|
+
exitCode: typeof reconciled.exitCode === "number" ? reconciled.exitCode : null,
|
|
346
|
+
signal: reconciled.signal || "",
|
|
347
|
+
command: reconciled.command || "",
|
|
348
|
+
sessionId: reconciled.sessionId || "",
|
|
349
|
+
logPath: reconciled.logPath || getRelativeBgLogPath(reconciled.backgroundId),
|
|
350
|
+
startedAt: reconciled.startedAt || null,
|
|
351
|
+
endedAt: reconciled.endedAt || null,
|
|
352
|
+
totalBytes: getLogSizeBytes(workspaceRoot, reconciled.backgroundId),
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
records.sort((a, b) => String(b.startedAt || "").localeCompare(String(a.startedAt || "")));
|
|
356
|
+
return records;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
function countRunningBackgroundProcesses({ workspaceRoot = process.cwd() } = {}) {
|
|
360
|
+
let root;
|
|
361
|
+
try {
|
|
362
|
+
root = normalizeWorkspaceRoot(workspaceRoot);
|
|
363
|
+
} catch {
|
|
364
|
+
return 0;
|
|
365
|
+
}
|
|
366
|
+
const dir = getBgDir(root);
|
|
367
|
+
if (!fs.existsSync(dir)) return 0;
|
|
368
|
+
return listBackgroundProcesses(root).filter((item) => item.running).length;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function spawnDetachedBackgroundProcess(command, workspaceRoot, options = {}) {
|
|
372
|
+
const backgroundId = options.backgroundId || generateBackgroundId();
|
|
373
|
+
const dir = getBgDir(workspaceRoot);
|
|
374
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
375
|
+
const absLogPath = getBgLogPath(workspaceRoot, backgroundId);
|
|
376
|
+
const relLogPath = getRelativeBgLogPath(backgroundId);
|
|
377
|
+
const logFd = fs.openSync(absLogPath, "a");
|
|
378
|
+
let child;
|
|
379
|
+
try {
|
|
380
|
+
child = spawn(process.execPath, [path.join(__dirname, "backgroundProcess.js"), getBgRecordPath(workspaceRoot, backgroundId), command], {
|
|
381
|
+
cwd: workspaceRoot,
|
|
382
|
+
detached: process.platform !== "win32",
|
|
383
|
+
windowsHide: true,
|
|
384
|
+
stdio: ["ignore", logFd, logFd],
|
|
385
|
+
});
|
|
386
|
+
} finally {
|
|
387
|
+
try { fs.closeSync(logFd); } catch {}
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
const initialRecord = {
|
|
391
|
+
backgroundId,
|
|
392
|
+
pid: child.pid || null,
|
|
393
|
+
command,
|
|
394
|
+
workspaceRoot,
|
|
395
|
+
sessionId: String((options && options.sessionId) || ""),
|
|
396
|
+
logPath: relLogPath,
|
|
397
|
+
startedAt: new Date().toISOString(),
|
|
398
|
+
endedAt: null,
|
|
399
|
+
status: "running",
|
|
400
|
+
exitCode: null,
|
|
401
|
+
signal: "",
|
|
402
|
+
};
|
|
403
|
+
writeBackgroundRecord(workspaceRoot, initialRecord);
|
|
404
|
+
|
|
405
|
+
const state = {
|
|
406
|
+
exited: false,
|
|
407
|
+
spawnError: null,
|
|
408
|
+
};
|
|
409
|
+
|
|
410
|
+
child.once("error", (err) => {
|
|
411
|
+
state.exited = true;
|
|
412
|
+
state.spawnError = err;
|
|
413
|
+
updateBackgroundRecord(workspaceRoot, backgroundId, (cur) => ({
|
|
414
|
+
...cur,
|
|
415
|
+
status: "exited",
|
|
416
|
+
exitCode: -1,
|
|
417
|
+
error: err && err.message ? err.message : "bash failed",
|
|
418
|
+
endedAt: cur.endedAt || new Date().toISOString(),
|
|
419
|
+
}));
|
|
420
|
+
});
|
|
421
|
+
|
|
422
|
+
child.once("exit", (code, sig) => {
|
|
423
|
+
state.exited = true;
|
|
424
|
+
updateBackgroundRecord(workspaceRoot, backgroundId, (cur) => ({
|
|
425
|
+
...cur,
|
|
426
|
+
status: cur.status === "stopped" ? "stopped" : "exited",
|
|
427
|
+
exitCode: cur.endedAt ? cur.exitCode : (typeof code === "number" ? code : cur.exitCode),
|
|
428
|
+
signal: sig || cur.signal || "",
|
|
429
|
+
endedAt: cur.endedAt || new Date().toISOString(),
|
|
430
|
+
}));
|
|
431
|
+
});
|
|
432
|
+
|
|
433
|
+
if (typeof child.unref === "function") child.unref();
|
|
434
|
+
|
|
435
|
+
return {
|
|
436
|
+
child,
|
|
437
|
+
backgroundId,
|
|
438
|
+
absLogPath,
|
|
439
|
+
initialRecord,
|
|
440
|
+
state,
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
function finalizeBackgroundStart(workspaceRoot, launched, maxBytes) {
|
|
445
|
+
const { backgroundId, absLogPath, initialRecord, state } = launched;
|
|
446
|
+
const slice = readBackgroundLogSlice(absLogPath, { offset: 0, maxBytes });
|
|
447
|
+
const record = reconcileBackgroundRecord(workspaceRoot, backgroundId) || {
|
|
448
|
+
...initialRecord,
|
|
449
|
+
running: false,
|
|
450
|
+
};
|
|
451
|
+
if (state.spawnError) {
|
|
452
|
+
return buildBackgroundPayload("run", workspaceRoot, record, slice, {
|
|
453
|
+
ok: false,
|
|
454
|
+
running: false,
|
|
455
|
+
error: state.spawnError.message || "bash failed",
|
|
456
|
+
});
|
|
457
|
+
}
|
|
458
|
+
if (!record.running && record.exitCode !== 0) {
|
|
459
|
+
const reason = record.signal
|
|
460
|
+
? `background command killed by signal ${record.signal}`
|
|
461
|
+
: `background command exited with ${record.exitCode ?? -1}`;
|
|
462
|
+
return buildBackgroundPayload("run", workspaceRoot, record, slice, {
|
|
463
|
+
ok: false,
|
|
464
|
+
running: false,
|
|
465
|
+
error: reason,
|
|
466
|
+
});
|
|
467
|
+
}
|
|
468
|
+
return buildBackgroundPayload("run", workspaceRoot, record, slice);
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
function runBackgroundActionSync(parsed, options = {}) {
|
|
472
|
+
const { action, command, workspaceRoot, backgroundId, offset, tailLines, maxBytes } = parsed;
|
|
473
|
+
|
|
474
|
+
if (action === "run") {
|
|
475
|
+
if (!command) {
|
|
476
|
+
return { ok: false, kind: "background_bash", action: "run", workspaceRoot, error: "command is required" };
|
|
477
|
+
}
|
|
478
|
+
const launched = spawnDetachedBackgroundProcess(command, workspaceRoot, options);
|
|
479
|
+
return finalizeBackgroundStart(workspaceRoot, launched, maxBytes);
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
if (action === "list") {
|
|
483
|
+
const processes = listBackgroundProcesses(workspaceRoot);
|
|
484
|
+
return {
|
|
485
|
+
ok: true,
|
|
486
|
+
kind: "background_bash",
|
|
487
|
+
action: "list",
|
|
488
|
+
workspaceRoot,
|
|
489
|
+
count: processes.length,
|
|
490
|
+
runningCount: processes.filter((item) => item.running).length,
|
|
491
|
+
processes,
|
|
492
|
+
stdout: "",
|
|
493
|
+
stderr: "",
|
|
494
|
+
error: "",
|
|
495
|
+
};
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
const invalid = validateBackgroundIdInput(action, workspaceRoot, backgroundId);
|
|
499
|
+
if (invalid) return invalid;
|
|
500
|
+
|
|
501
|
+
const record = reconcileBackgroundRecord(workspaceRoot, backgroundId);
|
|
502
|
+
if (!record) {
|
|
503
|
+
return {
|
|
504
|
+
ok: false,
|
|
505
|
+
kind: "background_bash",
|
|
506
|
+
action,
|
|
507
|
+
workspaceRoot,
|
|
508
|
+
backgroundId,
|
|
509
|
+
error: `background process not found: ${backgroundId}`,
|
|
510
|
+
};
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
if (action === "logs" || action === "status") {
|
|
514
|
+
const absLogPath = getBgLogPath(workspaceRoot, backgroundId);
|
|
515
|
+
const defaultTail = action === "status" ? DEFAULT_STATUS_TAIL_LINES : DEFAULT_LOG_TAIL_LINES;
|
|
516
|
+
const slice = readBackgroundLogSlice(absLogPath, {
|
|
517
|
+
offset,
|
|
518
|
+
tailLines: tailLines == null ? defaultTail : tailLines,
|
|
519
|
+
maxBytes,
|
|
520
|
+
});
|
|
521
|
+
return buildBackgroundPayload(action, workspaceRoot, record, slice);
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
if (action === "stop") {
|
|
525
|
+
if (record.running) {
|
|
526
|
+
terminatePidGroup(record.pid, "SIGTERM");
|
|
527
|
+
if (isPidAlive(record.pid)) terminatePidGroup(record.pid, "SIGKILL");
|
|
528
|
+
}
|
|
529
|
+
const stoppedRecord = updateBackgroundRecord(workspaceRoot, backgroundId, (cur) => ({
|
|
530
|
+
...cur,
|
|
531
|
+
status: "stopped",
|
|
532
|
+
signal: cur.signal || "SIGTERM",
|
|
533
|
+
endedAt: cur.endedAt || new Date().toISOString(),
|
|
534
|
+
})) || { ...record, status: "stopped", endedAt: new Date().toISOString() };
|
|
535
|
+
const absLogPath = getBgLogPath(workspaceRoot, backgroundId);
|
|
536
|
+
const slice = readBackgroundLogSlice(absLogPath, {
|
|
537
|
+
offset: null,
|
|
538
|
+
tailLines: tailLines == null ? DEFAULT_STOP_TAIL_LINES : tailLines,
|
|
539
|
+
maxBytes,
|
|
540
|
+
});
|
|
541
|
+
return buildBackgroundPayload("stop", workspaceRoot, { ...stoppedRecord, running: false }, slice);
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
return {
|
|
545
|
+
ok: false,
|
|
546
|
+
kind: "background_bash",
|
|
547
|
+
action,
|
|
548
|
+
workspaceRoot,
|
|
549
|
+
error: `unsupported bash action: ${action}`,
|
|
550
|
+
};
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
function sleepAbortable(ms, signal) {
|
|
554
|
+
if (!(ms > 0)) return Promise.resolve(false);
|
|
555
|
+
if (signal && signal.aborted) return Promise.resolve(true);
|
|
556
|
+
return new Promise((resolve) => {
|
|
557
|
+
let settled = false;
|
|
558
|
+
const onAbort = () => {
|
|
559
|
+
if (settled) return;
|
|
560
|
+
settled = true;
|
|
561
|
+
clearTimeout(timer);
|
|
562
|
+
resolve(true);
|
|
563
|
+
};
|
|
564
|
+
const timer = setTimeout(() => {
|
|
565
|
+
if (settled) return;
|
|
566
|
+
settled = true;
|
|
567
|
+
if (signal && typeof signal.removeEventListener === "function") {
|
|
568
|
+
signal.removeEventListener("abort", onAbort);
|
|
569
|
+
}
|
|
570
|
+
resolve(false);
|
|
571
|
+
}, ms);
|
|
572
|
+
if (typeof timer.unref === "function") timer.unref();
|
|
573
|
+
if (signal && typeof signal.addEventListener === "function") {
|
|
574
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
575
|
+
}
|
|
576
|
+
});
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
async function runBackgroundActionAsync(parsed, options = {}) {
|
|
580
|
+
const {
|
|
581
|
+
action,
|
|
582
|
+
command,
|
|
583
|
+
workspaceRoot,
|
|
584
|
+
startupWaitMs,
|
|
585
|
+
backgroundId,
|
|
586
|
+
offset,
|
|
587
|
+
tailLines,
|
|
588
|
+
maxBytes,
|
|
589
|
+
waitMs,
|
|
590
|
+
} = parsed;
|
|
591
|
+
const signal = options && options.signal;
|
|
592
|
+
|
|
593
|
+
if (signal && signal.aborted) {
|
|
594
|
+
return {
|
|
595
|
+
ok: false,
|
|
596
|
+
cancelled: true,
|
|
597
|
+
code: "cancelled",
|
|
598
|
+
error: "CLI cancelled",
|
|
599
|
+
workspaceRoot,
|
|
600
|
+
};
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
if (action === "run") {
|
|
604
|
+
if (!command) {
|
|
605
|
+
return { ok: false, kind: "background_bash", action: "run", workspaceRoot, error: "command is required" };
|
|
606
|
+
}
|
|
607
|
+
let launched;
|
|
608
|
+
try {
|
|
609
|
+
launched = spawnDetachedBackgroundProcess(command, workspaceRoot, options);
|
|
610
|
+
} catch (err) {
|
|
611
|
+
return {
|
|
612
|
+
ok: false,
|
|
613
|
+
kind: "background_bash",
|
|
614
|
+
action: "run",
|
|
615
|
+
workspaceRoot,
|
|
616
|
+
error: err && err.message ? err.message : "bash failed",
|
|
617
|
+
};
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
if (startupWaitMs > 0 && !launched.state.exited) {
|
|
621
|
+
await new Promise((resolve) => {
|
|
622
|
+
let done = false;
|
|
623
|
+
const finish = () => {
|
|
624
|
+
if (done) return;
|
|
625
|
+
done = true;
|
|
626
|
+
clearTimeout(timer);
|
|
627
|
+
launched.child.removeListener("exit", finish);
|
|
628
|
+
launched.child.removeListener("error", finish);
|
|
629
|
+
if (signal && typeof signal.removeEventListener === "function") {
|
|
630
|
+
signal.removeEventListener("abort", finish);
|
|
631
|
+
}
|
|
632
|
+
resolve();
|
|
633
|
+
};
|
|
634
|
+
const timer = setTimeout(finish, startupWaitMs);
|
|
635
|
+
if (typeof timer.unref === "function") timer.unref();
|
|
636
|
+
launched.child.once("exit", finish);
|
|
637
|
+
launched.child.once("error", finish);
|
|
638
|
+
if (signal && typeof signal.addEventListener === "function") {
|
|
639
|
+
signal.addEventListener("abort", finish, { once: true });
|
|
640
|
+
}
|
|
641
|
+
});
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
if (signal && signal.aborted) {
|
|
645
|
+
terminatePidGroup(launched.initialRecord.pid, "SIGTERM");
|
|
646
|
+
updateBackgroundRecord(workspaceRoot, launched.backgroundId, (cur) => ({
|
|
647
|
+
...cur,
|
|
648
|
+
status: "stopped",
|
|
649
|
+
signal: "SIGTERM",
|
|
650
|
+
endedAt: cur.endedAt || new Date().toISOString(),
|
|
651
|
+
}));
|
|
652
|
+
return {
|
|
653
|
+
ok: false,
|
|
654
|
+
cancelled: true,
|
|
655
|
+
code: "cancelled",
|
|
656
|
+
error: "CLI cancelled",
|
|
657
|
+
workspaceRoot,
|
|
658
|
+
};
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
return finalizeBackgroundStart(workspaceRoot, launched, maxBytes);
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
if (action === "list") {
|
|
665
|
+
return runBackgroundActionSync(parsed, options);
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
const invalid = validateBackgroundIdInput(action, workspaceRoot, backgroundId);
|
|
669
|
+
if (invalid) return invalid;
|
|
670
|
+
|
|
671
|
+
let record = reconcileBackgroundRecord(workspaceRoot, backgroundId);
|
|
672
|
+
if (!record) {
|
|
673
|
+
return {
|
|
674
|
+
ok: false,
|
|
675
|
+
kind: "background_bash",
|
|
676
|
+
action,
|
|
677
|
+
workspaceRoot,
|
|
678
|
+
backgroundId,
|
|
679
|
+
error: `background process not found: ${backgroundId}`,
|
|
680
|
+
};
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
if (action === "logs" || action === "status") {
|
|
684
|
+
if (action === "logs" && waitMs > 0 && record.running) {
|
|
685
|
+
const baselineBytes = Number.isInteger(offset) && offset >= 0
|
|
686
|
+
? offset
|
|
687
|
+
: getLogSizeBytes(workspaceRoot, backgroundId);
|
|
688
|
+
const deadline = Date.now() + waitMs;
|
|
689
|
+
while (Date.now() < deadline) {
|
|
690
|
+
const currentBytes = getLogSizeBytes(workspaceRoot, backgroundId);
|
|
691
|
+
if (currentBytes > baselineBytes || !isPidAlive(record.pid)) break;
|
|
692
|
+
const aborted = await sleepAbortable(Math.min(100, deadline - Date.now()), signal);
|
|
693
|
+
if (aborted) {
|
|
694
|
+
return {
|
|
695
|
+
ok: false,
|
|
696
|
+
cancelled: true,
|
|
697
|
+
code: "cancelled",
|
|
698
|
+
error: "CLI cancelled",
|
|
699
|
+
workspaceRoot,
|
|
700
|
+
};
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
record = reconcileBackgroundRecord(workspaceRoot, backgroundId) || record;
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
const absLogPath = getBgLogPath(workspaceRoot, backgroundId);
|
|
707
|
+
const defaultTail = action === "status" ? DEFAULT_STATUS_TAIL_LINES : DEFAULT_LOG_TAIL_LINES;
|
|
708
|
+
const slice = readBackgroundLogSlice(absLogPath, {
|
|
709
|
+
offset,
|
|
710
|
+
tailLines: tailLines == null ? defaultTail : tailLines,
|
|
711
|
+
maxBytes,
|
|
712
|
+
});
|
|
713
|
+
return buildBackgroundPayload(action, workspaceRoot, record, slice);
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
if (action === "stop") {
|
|
717
|
+
if (record.running) {
|
|
718
|
+
terminatePidGroup(record.pid, "SIGTERM");
|
|
719
|
+
const termDeadline = Date.now() + 400;
|
|
720
|
+
while (Date.now() < termDeadline && isPidAlive(record.pid)) {
|
|
721
|
+
await sleepAbortable(50, null);
|
|
722
|
+
}
|
|
723
|
+
if (isPidAlive(record.pid)) {
|
|
724
|
+
terminatePidGroup(record.pid, "SIGKILL");
|
|
725
|
+
const killDeadline = Date.now() + 150;
|
|
726
|
+
while (Date.now() < killDeadline && isPidAlive(record.pid)) {
|
|
727
|
+
await sleepAbortable(30, null);
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
const stoppedRecord = updateBackgroundRecord(workspaceRoot, backgroundId, (cur) => ({
|
|
732
|
+
...cur,
|
|
733
|
+
status: "stopped",
|
|
734
|
+
signal: cur.signal || "SIGTERM",
|
|
735
|
+
endedAt: cur.endedAt || new Date().toISOString(),
|
|
736
|
+
})) || { ...record, status: "stopped", endedAt: new Date().toISOString() };
|
|
737
|
+
const absLogPath = getBgLogPath(workspaceRoot, backgroundId);
|
|
738
|
+
const slice = readBackgroundLogSlice(absLogPath, {
|
|
739
|
+
offset: null,
|
|
740
|
+
tailLines: tailLines == null ? DEFAULT_STOP_TAIL_LINES : tailLines,
|
|
741
|
+
maxBytes,
|
|
742
|
+
});
|
|
743
|
+
return buildBackgroundPayload("stop", workspaceRoot, { ...stoppedRecord, running: false }, slice);
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
return {
|
|
747
|
+
ok: false,
|
|
748
|
+
kind: "background_bash",
|
|
749
|
+
action,
|
|
750
|
+
workspaceRoot,
|
|
751
|
+
error: `unsupported bash action: ${action}`,
|
|
752
|
+
};
|
|
753
|
+
}
|
|
754
|
+
|
|
33
755
|
function runBashTool(input = {}, options = {}) {
|
|
34
756
|
try {
|
|
35
|
-
const
|
|
757
|
+
const parsed = normalizeBashInput(input, options);
|
|
758
|
+
if (!VALID_ACTIONS.has(parsed.action)) {
|
|
759
|
+
return {
|
|
760
|
+
ok: false,
|
|
761
|
+
kind: "background_bash",
|
|
762
|
+
action: parsed.action,
|
|
763
|
+
workspaceRoot: parsed.workspaceRoot,
|
|
764
|
+
error: `unsupported bash action: ${parsed.action}`,
|
|
765
|
+
};
|
|
766
|
+
}
|
|
767
|
+
if (parsed.action !== "run" || parsed.background) {
|
|
768
|
+
return runBackgroundActionSync(parsed, options);
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
const { command, workspaceRoot, timeoutMs } = parsed;
|
|
36
772
|
if (!command) {
|
|
37
773
|
return {
|
|
38
774
|
ok: false,
|
|
@@ -94,17 +830,31 @@ function runBashTool(input = {}, options = {}) {
|
|
|
94
830
|
* whole shell process group instead of waiting for the command's timeout.
|
|
95
831
|
*/
|
|
96
832
|
function runBashToolAsync(input = {}, options = {}) {
|
|
97
|
-
let
|
|
98
|
-
let workspaceRoot;
|
|
99
|
-
let timeoutMs;
|
|
833
|
+
let parsed;
|
|
100
834
|
try {
|
|
101
|
-
|
|
835
|
+
parsed = normalizeBashInput(input, options);
|
|
102
836
|
} catch (err) {
|
|
103
837
|
return Promise.resolve({
|
|
104
838
|
ok: false,
|
|
105
839
|
error: err && err.message ? err.message : "bash failed",
|
|
106
840
|
});
|
|
107
841
|
}
|
|
842
|
+
|
|
843
|
+
if (!VALID_ACTIONS.has(parsed.action)) {
|
|
844
|
+
return Promise.resolve({
|
|
845
|
+
ok: false,
|
|
846
|
+
kind: "background_bash",
|
|
847
|
+
action: parsed.action,
|
|
848
|
+
workspaceRoot: parsed.workspaceRoot,
|
|
849
|
+
error: `unsupported bash action: ${parsed.action}`,
|
|
850
|
+
});
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
if (parsed.action !== "run" || parsed.background) {
|
|
854
|
+
return runBackgroundActionAsync(parsed, options);
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
const { command, workspaceRoot, timeoutMs } = parsed;
|
|
108
858
|
const signal = options && options.signal;
|
|
109
859
|
if (!command) {
|
|
110
860
|
return Promise.resolve({ ok: false, error: "command is required" });
|
|
@@ -220,4 +970,6 @@ function runBashToolAsync(input = {}, options = {}) {
|
|
|
220
970
|
module.exports = {
|
|
221
971
|
runBashTool,
|
|
222
972
|
runBashToolAsync,
|
|
973
|
+
listBackgroundProcesses,
|
|
974
|
+
countRunningBackgroundProcesses,
|
|
223
975
|
};
|