@openacp/cli 0.6.3 → 0.6.5
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/dist/adapter-YSEIZJBA.js +798 -0
- package/dist/adapter-YSEIZJBA.js.map +1 -0
- package/dist/{admin-3ZHEO5VP.js → admin-SCP25TN2.js} +3 -3
- package/dist/agent-catalog-SBZQRYOD.js +10 -0
- package/dist/agent-store-CGE4G6PA.js +8 -0
- package/dist/{agents-SXIY4IEF.js → agents-QJPHNWK2.js} +3 -3
- package/dist/{autostart-A7JRU4WJ.js → autostart-6M3FZAKW.js} +3 -3
- package/dist/{chunk-PMGNLNSH.js → chunk-2CJ46J3C.js} +2 -2
- package/dist/{chunk-5HGXUCMX.js → chunk-34M4OS5P.js} +2 -2
- package/dist/{chunk-AVCHZESZ.js → chunk-3IRAWHMC.js} +49 -20
- package/dist/chunk-3IRAWHMC.js.map +1 -0
- package/dist/{chunk-EWYNCHUH.js → chunk-3ZO3MHZN.js} +22 -3
- package/dist/chunk-3ZO3MHZN.js.map +1 -0
- package/dist/{chunk-TTDSLV35.js → chunk-4CTX774K.js} +3 -3
- package/dist/chunk-4GQ3I65A.js +23 -0
- package/dist/chunk-4GQ3I65A.js.map +1 -0
- package/dist/{chunk-NXEQXRQR.js → chunk-774Y4RAK.js} +2 -2
- package/dist/{chunk-6LSFRNHE.js → chunk-7KZI2236.js} +3 -3
- package/dist/{chunk-SM3G6UAX.js → chunk-BNLGTZ34.js} +2 -2
- package/dist/{chunk-FMWSVLRM.js → chunk-FCLGYYTY.js} +1 -21
- package/dist/chunk-FCLGYYTY.js.map +1 -0
- package/dist/chunk-FEWSQT3U.js +3949 -0
- package/dist/chunk-FEWSQT3U.js.map +1 -0
- package/dist/{chunk-HP2IJYCA.js → chunk-FW6HM4VU.js} +91 -4030
- package/dist/chunk-FW6HM4VU.js.map +1 -0
- package/dist/{chunk-ESOPMQAY.js → chunk-GAK6PIBW.js} +25 -2
- package/dist/chunk-GAK6PIBW.js.map +1 -0
- package/dist/{chunk-3KGRVAEV.js → chunk-J4SJTKIK.js} +2 -2
- package/dist/{chunk-FZ5BIWG5.js → chunk-JV6XQRAE.js} +4 -4
- package/dist/{chunk-OHR6SBMC.js → chunk-PJVKOZTR.js} +3 -3
- package/dist/{chunk-EVFJW45N.js → chunk-S64CB6J3.js} +13 -13
- package/dist/{chunk-EVFJW45N.js.map → chunk-S64CB6J3.js.map} +1 -1
- package/dist/{chunk-CKOK7JW6.js → chunk-UKT3G5IA.js} +3 -3
- package/dist/{chunk-PWFPTG5X.js → chunk-V5GZQEIY.js} +2 -2
- package/dist/{chunk-KO5RL7MZ.js → chunk-WVMSP4AF.js} +2 -2
- package/dist/{chunk-TMCQZAXN.js → chunk-XVL6AGMG.js} +3 -3
- package/dist/{chunk-IER5UCY7.js → chunk-YQRF3IOR.js} +2 -2
- package/dist/{chunk-G3OHCXZG.js → chunk-ZKTIZME6.js} +194 -133
- package/dist/chunk-ZKTIZME6.js.map +1 -0
- package/dist/cli.js +54 -44
- package/dist/cli.js.map +1 -1
- package/dist/{config-4YSJ4NCI.js → config-B26J3XXN.js} +3 -3
- package/dist/config-editor-QTGUK3CD.js +12 -0
- package/dist/{daemon-I6XMRQ6P.js → daemon-5DS5BQXJ.js} +4 -4
- package/dist/{discord-VHCBN3JJ.js → discord-QKT3JMRW.js} +28 -26
- package/dist/{discord-VHCBN3JJ.js.map → discord-QKT3JMRW.js.map} +1 -1
- package/dist/doctor-6SUCVUZB.js +9 -0
- package/dist/doctor-QQ3YZEYV.js +14 -0
- package/dist/index.d.ts +166 -11
- package/dist/index.js +17 -14
- package/dist/{install-cloudflared-G2GUKCHA.js → install-cloudflared-FSILDS5J.js} +3 -3
- package/dist/{install-jq-7QTU7XYY.js → install-jq-P6RUBKPV.js} +3 -3
- package/dist/{log-SPS2S6FO.js → log-RCVBXLTN.js} +8 -4
- package/dist/{main-P4X6SAPZ.js → main-TSZR4HPP.js} +57 -29
- package/dist/main-TSZR4HPP.js.map +1 -0
- package/dist/{new-session-PUNUHGYP.js → new-session-K6UCWYOP.js} +5 -5
- package/dist/{post-upgrade-6N4JCV5S.js → post-upgrade-62LUHDJO.js} +5 -5
- package/dist/{session-ZMAM67AA.js → session-O6ZPLJIZ.js} +4 -4
- package/dist/{settings-OEQEZS5Y.js → settings-RRF77IC4.js} +3 -3
- package/dist/{setup-7YBFKRG7.js → setup-5ZKSUR26.js} +4 -4
- package/dist/{tunnel-service-BMIBHUBK.js → tunnel-service-NJJH4I26.js} +3 -3
- package/dist/{version-ALWGGVKM.js → version-AXXV6IV2.js} +2 -2
- package/package.json +6 -1
- package/dist/agent-catalog-IVU2KANH.js +0 -10
- package/dist/agent-store-ZBXGOFPH.js +0 -8
- package/dist/chunk-AVCHZESZ.js.map +0 -1
- package/dist/chunk-ESOPMQAY.js.map +0 -1
- package/dist/chunk-EWYNCHUH.js.map +0 -1
- package/dist/chunk-FMWSVLRM.js.map +0 -1
- package/dist/chunk-G3OHCXZG.js.map +0 -1
- package/dist/chunk-HP2IJYCA.js.map +0 -1
- package/dist/config-editor-F25HEMGL.js +0 -12
- package/dist/doctor-GPW5ECK6.js +0 -14
- package/dist/doctor-Y3SCSVPI.js +0 -9
- package/dist/main-P4X6SAPZ.js.map +0 -1
- /package/dist/{admin-3ZHEO5VP.js.map → admin-SCP25TN2.js.map} +0 -0
- /package/dist/{agent-catalog-IVU2KANH.js.map → agent-catalog-SBZQRYOD.js.map} +0 -0
- /package/dist/{agent-store-ZBXGOFPH.js.map → agent-store-CGE4G6PA.js.map} +0 -0
- /package/dist/{agents-SXIY4IEF.js.map → agents-QJPHNWK2.js.map} +0 -0
- /package/dist/{autostart-A7JRU4WJ.js.map → autostart-6M3FZAKW.js.map} +0 -0
- /package/dist/{chunk-PMGNLNSH.js.map → chunk-2CJ46J3C.js.map} +0 -0
- /package/dist/{chunk-5HGXUCMX.js.map → chunk-34M4OS5P.js.map} +0 -0
- /package/dist/{chunk-TTDSLV35.js.map → chunk-4CTX774K.js.map} +0 -0
- /package/dist/{chunk-NXEQXRQR.js.map → chunk-774Y4RAK.js.map} +0 -0
- /package/dist/{chunk-6LSFRNHE.js.map → chunk-7KZI2236.js.map} +0 -0
- /package/dist/{chunk-SM3G6UAX.js.map → chunk-BNLGTZ34.js.map} +0 -0
- /package/dist/{chunk-3KGRVAEV.js.map → chunk-J4SJTKIK.js.map} +0 -0
- /package/dist/{chunk-FZ5BIWG5.js.map → chunk-JV6XQRAE.js.map} +0 -0
- /package/dist/{chunk-OHR6SBMC.js.map → chunk-PJVKOZTR.js.map} +0 -0
- /package/dist/{chunk-CKOK7JW6.js.map → chunk-UKT3G5IA.js.map} +0 -0
- /package/dist/{chunk-PWFPTG5X.js.map → chunk-V5GZQEIY.js.map} +0 -0
- /package/dist/{chunk-KO5RL7MZ.js.map → chunk-WVMSP4AF.js.map} +0 -0
- /package/dist/{chunk-TMCQZAXN.js.map → chunk-XVL6AGMG.js.map} +0 -0
- /package/dist/{chunk-IER5UCY7.js.map → chunk-YQRF3IOR.js.map} +0 -0
- /package/dist/{config-4YSJ4NCI.js.map → config-B26J3XXN.js.map} +0 -0
- /package/dist/{config-editor-F25HEMGL.js.map → config-editor-QTGUK3CD.js.map} +0 -0
- /package/dist/{daemon-I6XMRQ6P.js.map → daemon-5DS5BQXJ.js.map} +0 -0
- /package/dist/{doctor-GPW5ECK6.js.map → doctor-6SUCVUZB.js.map} +0 -0
- /package/dist/{doctor-Y3SCSVPI.js.map → doctor-QQ3YZEYV.js.map} +0 -0
- /package/dist/{install-cloudflared-G2GUKCHA.js.map → install-cloudflared-FSILDS5J.js.map} +0 -0
- /package/dist/{install-jq-7QTU7XYY.js.map → install-jq-P6RUBKPV.js.map} +0 -0
- /package/dist/{log-SPS2S6FO.js.map → log-RCVBXLTN.js.map} +0 -0
- /package/dist/{new-session-PUNUHGYP.js.map → new-session-K6UCWYOP.js.map} +0 -0
- /package/dist/{post-upgrade-6N4JCV5S.js.map → post-upgrade-62LUHDJO.js.map} +0 -0
- /package/dist/{session-ZMAM67AA.js.map → session-O6ZPLJIZ.js.map} +0 -0
- /package/dist/{settings-OEQEZS5Y.js.map → settings-RRF77IC4.js.map} +0 -0
- /package/dist/{setup-7YBFKRG7.js.map → setup-5ZKSUR26.js.map} +0 -0
- /package/dist/{tunnel-service-BMIBHUBK.js.map → tunnel-service-NJJH4I26.js.map} +0 -0
- /package/dist/{version-ALWGGVKM.js.map → version-AXXV6IV2.js.map} +0 -0
|
@@ -0,0 +1,3949 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AgentCatalog
|
|
3
|
+
} from "./chunk-UKT3G5IA.js";
|
|
4
|
+
import {
|
|
5
|
+
getAgentCapabilities
|
|
6
|
+
} from "./chunk-JKBFUAJK.js";
|
|
7
|
+
import {
|
|
8
|
+
createChildLogger,
|
|
9
|
+
createSessionLogger
|
|
10
|
+
} from "./chunk-GAK6PIBW.js";
|
|
11
|
+
|
|
12
|
+
// src/core/streams.ts
|
|
13
|
+
function nodeToWebWritable(nodeStream) {
|
|
14
|
+
return new WritableStream({
|
|
15
|
+
write(chunk) {
|
|
16
|
+
return new Promise((resolve3, reject) => {
|
|
17
|
+
nodeStream.write(Buffer.from(chunk), (err) => {
|
|
18
|
+
if (err) reject(err);
|
|
19
|
+
else resolve3();
|
|
20
|
+
});
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
function nodeToWebReadable(nodeStream) {
|
|
26
|
+
return new ReadableStream({
|
|
27
|
+
start(controller) {
|
|
28
|
+
nodeStream.on("data", (chunk) => {
|
|
29
|
+
controller.enqueue(new Uint8Array(chunk));
|
|
30
|
+
});
|
|
31
|
+
nodeStream.on("end", () => controller.close());
|
|
32
|
+
nodeStream.on("error", (err) => controller.error(err));
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// src/core/stderr-capture.ts
|
|
38
|
+
var StderrCapture = class {
|
|
39
|
+
constructor(maxLines = 50) {
|
|
40
|
+
this.maxLines = maxLines;
|
|
41
|
+
}
|
|
42
|
+
lines = [];
|
|
43
|
+
append(chunk) {
|
|
44
|
+
this.lines.push(...chunk.split("\n").filter(Boolean));
|
|
45
|
+
if (this.lines.length > this.maxLines) {
|
|
46
|
+
this.lines = this.lines.slice(-this.maxLines);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
getLastLines() {
|
|
50
|
+
return this.lines.join("\n");
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
// src/core/typed-emitter.ts
|
|
55
|
+
var TypedEmitter = class {
|
|
56
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
57
|
+
listeners = /* @__PURE__ */ new Map();
|
|
58
|
+
paused = false;
|
|
59
|
+
buffer = [];
|
|
60
|
+
on(event, listener) {
|
|
61
|
+
let set = this.listeners.get(event);
|
|
62
|
+
if (!set) {
|
|
63
|
+
set = /* @__PURE__ */ new Set();
|
|
64
|
+
this.listeners.set(event, set);
|
|
65
|
+
}
|
|
66
|
+
set.add(listener);
|
|
67
|
+
return this;
|
|
68
|
+
}
|
|
69
|
+
off(event, listener) {
|
|
70
|
+
this.listeners.get(event)?.delete(listener);
|
|
71
|
+
return this;
|
|
72
|
+
}
|
|
73
|
+
emit(event, ...args) {
|
|
74
|
+
if (this.paused) {
|
|
75
|
+
if (this.passthroughFn?.(event, args)) {
|
|
76
|
+
this.deliver(event, args);
|
|
77
|
+
} else {
|
|
78
|
+
this.buffer.push({ event, args });
|
|
79
|
+
}
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
this.deliver(event, args);
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Pause event delivery. Events emitted while paused are buffered.
|
|
86
|
+
* Optionally pass a filter to allow specific events through even while paused.
|
|
87
|
+
*/
|
|
88
|
+
pause(passthrough) {
|
|
89
|
+
this.paused = true;
|
|
90
|
+
this.passthroughFn = passthrough;
|
|
91
|
+
}
|
|
92
|
+
passthroughFn;
|
|
93
|
+
/** Resume event delivery and replay buffered events in order. */
|
|
94
|
+
resume() {
|
|
95
|
+
this.paused = false;
|
|
96
|
+
this.passthroughFn = void 0;
|
|
97
|
+
const buffered = this.buffer.splice(0);
|
|
98
|
+
for (const { event, args } of buffered) {
|
|
99
|
+
this.deliver(event, args);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
/** Discard all buffered events without delivering them. */
|
|
103
|
+
clearBuffer() {
|
|
104
|
+
this.buffer.length = 0;
|
|
105
|
+
}
|
|
106
|
+
get isPaused() {
|
|
107
|
+
return this.paused;
|
|
108
|
+
}
|
|
109
|
+
get bufferSize() {
|
|
110
|
+
return this.buffer.length;
|
|
111
|
+
}
|
|
112
|
+
removeAllListeners(event) {
|
|
113
|
+
if (event) {
|
|
114
|
+
this.listeners.delete(event);
|
|
115
|
+
} else {
|
|
116
|
+
this.listeners.clear();
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
deliver(event, args) {
|
|
120
|
+
const set = this.listeners.get(event);
|
|
121
|
+
if (!set) return;
|
|
122
|
+
for (const listener of set) {
|
|
123
|
+
listener(...args);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
// src/core/agent-instance.ts
|
|
129
|
+
import { spawn, execFileSync } from "child_process";
|
|
130
|
+
import { Transform } from "stream";
|
|
131
|
+
import fs from "fs";
|
|
132
|
+
import path from "path";
|
|
133
|
+
import { randomUUID } from "crypto";
|
|
134
|
+
import { ClientSideConnection, ndJsonStream } from "@agentclientprotocol/sdk";
|
|
135
|
+
var log = createChildLogger({ module: "agent-instance" });
|
|
136
|
+
function findPackageRoot(startDir) {
|
|
137
|
+
let dir = startDir;
|
|
138
|
+
while (dir !== path.dirname(dir)) {
|
|
139
|
+
if (fs.existsSync(path.join(dir, "package.json"))) {
|
|
140
|
+
return dir;
|
|
141
|
+
}
|
|
142
|
+
dir = path.dirname(dir);
|
|
143
|
+
}
|
|
144
|
+
return startDir;
|
|
145
|
+
}
|
|
146
|
+
function resolveAgentCommand(cmd) {
|
|
147
|
+
const searchRoots = [process.cwd()];
|
|
148
|
+
const ownDir = findPackageRoot(import.meta.dirname);
|
|
149
|
+
if (ownDir !== process.cwd()) {
|
|
150
|
+
searchRoots.push(ownDir);
|
|
151
|
+
}
|
|
152
|
+
for (const root of searchRoots) {
|
|
153
|
+
const packageDirs = [
|
|
154
|
+
path.resolve(root, "node_modules", "@zed-industries", cmd, "dist", "index.js"),
|
|
155
|
+
path.resolve(root, "node_modules", cmd, "dist", "index.js")
|
|
156
|
+
];
|
|
157
|
+
for (const jsPath of packageDirs) {
|
|
158
|
+
if (fs.existsSync(jsPath)) {
|
|
159
|
+
return { command: process.execPath, args: [jsPath] };
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
for (const root of searchRoots) {
|
|
164
|
+
const localBin = path.resolve(root, "node_modules", ".bin", cmd);
|
|
165
|
+
if (fs.existsSync(localBin)) {
|
|
166
|
+
const content = fs.readFileSync(localBin, "utf-8");
|
|
167
|
+
if (content.startsWith("#!/usr/bin/env node")) {
|
|
168
|
+
return { command: process.execPath, args: [localBin] };
|
|
169
|
+
}
|
|
170
|
+
const match = content.match(/"([^"]+\.js)"/);
|
|
171
|
+
if (match) {
|
|
172
|
+
const target = path.resolve(path.dirname(localBin), match[1]);
|
|
173
|
+
if (fs.existsSync(target)) {
|
|
174
|
+
return { command: process.execPath, args: [target] };
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
try {
|
|
180
|
+
const fullPath = execFileSync("which", [cmd], { encoding: "utf-8" }).trim();
|
|
181
|
+
if (fullPath) {
|
|
182
|
+
const content = fs.readFileSync(fullPath, "utf-8");
|
|
183
|
+
if (content.startsWith("#!/usr/bin/env node")) {
|
|
184
|
+
return { command: process.execPath, args: [fullPath] };
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
} catch {
|
|
188
|
+
}
|
|
189
|
+
return { command: cmd, args: [] };
|
|
190
|
+
}
|
|
191
|
+
var AgentInstance = class _AgentInstance extends TypedEmitter {
|
|
192
|
+
connection;
|
|
193
|
+
child;
|
|
194
|
+
stderrCapture;
|
|
195
|
+
terminals = /* @__PURE__ */ new Map();
|
|
196
|
+
sessionId;
|
|
197
|
+
agentName;
|
|
198
|
+
promptCapabilities;
|
|
199
|
+
// Callback — set by core when wiring events
|
|
200
|
+
onPermissionRequest = async () => "";
|
|
201
|
+
constructor(agentName) {
|
|
202
|
+
super();
|
|
203
|
+
this.agentName = agentName;
|
|
204
|
+
}
|
|
205
|
+
static async spawnSubprocess(agentDef, workingDirectory) {
|
|
206
|
+
const instance = new _AgentInstance(agentDef.name);
|
|
207
|
+
const resolved = resolveAgentCommand(agentDef.command);
|
|
208
|
+
log.debug(
|
|
209
|
+
{
|
|
210
|
+
agentName: agentDef.name,
|
|
211
|
+
command: resolved.command,
|
|
212
|
+
args: resolved.args
|
|
213
|
+
},
|
|
214
|
+
"Resolved agent command"
|
|
215
|
+
);
|
|
216
|
+
instance.child = spawn(
|
|
217
|
+
resolved.command,
|
|
218
|
+
[...resolved.args, ...agentDef.args],
|
|
219
|
+
{
|
|
220
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
221
|
+
cwd: workingDirectory,
|
|
222
|
+
env: { ...process.env, ...agentDef.env }
|
|
223
|
+
}
|
|
224
|
+
);
|
|
225
|
+
await new Promise((resolve3, reject) => {
|
|
226
|
+
instance.child.on("error", (err) => {
|
|
227
|
+
reject(
|
|
228
|
+
new Error(
|
|
229
|
+
`Failed to spawn agent "${agentDef.name}": ${err.message}. Is "${agentDef.command}" installed?`
|
|
230
|
+
)
|
|
231
|
+
);
|
|
232
|
+
});
|
|
233
|
+
instance.child.on("spawn", () => resolve3());
|
|
234
|
+
});
|
|
235
|
+
instance.stderrCapture = new StderrCapture(50);
|
|
236
|
+
instance.child.stderr.on("data", (chunk) => {
|
|
237
|
+
instance.stderrCapture.append(chunk.toString());
|
|
238
|
+
});
|
|
239
|
+
const stdinLogger = new Transform({
|
|
240
|
+
transform(chunk, _enc, cb) {
|
|
241
|
+
log.debug(
|
|
242
|
+
{ direction: "send", raw: chunk.toString().trimEnd() },
|
|
243
|
+
"ACP raw"
|
|
244
|
+
);
|
|
245
|
+
cb(null, chunk);
|
|
246
|
+
}
|
|
247
|
+
});
|
|
248
|
+
stdinLogger.pipe(instance.child.stdin);
|
|
249
|
+
const stdoutLogger = new Transform({
|
|
250
|
+
transform(chunk, _enc, cb) {
|
|
251
|
+
log.debug(
|
|
252
|
+
{ direction: "recv", raw: chunk.toString().trimEnd() },
|
|
253
|
+
"ACP raw"
|
|
254
|
+
);
|
|
255
|
+
cb(null, chunk);
|
|
256
|
+
}
|
|
257
|
+
});
|
|
258
|
+
instance.child.stdout.pipe(stdoutLogger);
|
|
259
|
+
const toAgent = nodeToWebWritable(stdinLogger);
|
|
260
|
+
const fromAgent = nodeToWebReadable(stdoutLogger);
|
|
261
|
+
const stream = ndJsonStream(toAgent, fromAgent);
|
|
262
|
+
instance.connection = new ClientSideConnection(
|
|
263
|
+
(_agent) => instance.createClient(_agent),
|
|
264
|
+
stream
|
|
265
|
+
);
|
|
266
|
+
const initResponse = await instance.connection.initialize({
|
|
267
|
+
protocolVersion: 1,
|
|
268
|
+
clientCapabilities: {
|
|
269
|
+
fs: { readTextFile: true, writeTextFile: true },
|
|
270
|
+
terminal: true
|
|
271
|
+
}
|
|
272
|
+
});
|
|
273
|
+
instance.promptCapabilities = initResponse.agentCapabilities?.promptCapabilities;
|
|
274
|
+
log.info(
|
|
275
|
+
{ promptCapabilities: instance.promptCapabilities ?? {} },
|
|
276
|
+
"Agent prompt capabilities"
|
|
277
|
+
);
|
|
278
|
+
return instance;
|
|
279
|
+
}
|
|
280
|
+
setupCrashDetection() {
|
|
281
|
+
this.child.on("exit", (code, signal) => {
|
|
282
|
+
log.info(
|
|
283
|
+
{ sessionId: this.sessionId, exitCode: code, signal },
|
|
284
|
+
"Agent process exited"
|
|
285
|
+
);
|
|
286
|
+
if (code !== 0 && code !== null) {
|
|
287
|
+
const stderr = this.stderrCapture.getLastLines();
|
|
288
|
+
this.emit("agent_event", {
|
|
289
|
+
type: "error",
|
|
290
|
+
message: `Agent crashed (exit code ${code})
|
|
291
|
+
${stderr}`
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
});
|
|
295
|
+
this.connection.closed.then(() => {
|
|
296
|
+
log.debug({ sessionId: this.sessionId }, "ACP connection closed");
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
static async spawn(agentDef, workingDirectory) {
|
|
300
|
+
log.debug(
|
|
301
|
+
{ agentName: agentDef.name, command: agentDef.command },
|
|
302
|
+
"Spawning agent"
|
|
303
|
+
);
|
|
304
|
+
const spawnStart = Date.now();
|
|
305
|
+
const instance = await _AgentInstance.spawnSubprocess(
|
|
306
|
+
agentDef,
|
|
307
|
+
workingDirectory
|
|
308
|
+
);
|
|
309
|
+
const response = await instance.connection.newSession({
|
|
310
|
+
cwd: workingDirectory,
|
|
311
|
+
mcpServers: []
|
|
312
|
+
});
|
|
313
|
+
instance.sessionId = response.sessionId;
|
|
314
|
+
instance.setupCrashDetection();
|
|
315
|
+
log.info(
|
|
316
|
+
{ sessionId: response.sessionId, durationMs: Date.now() - spawnStart },
|
|
317
|
+
"Agent spawn complete"
|
|
318
|
+
);
|
|
319
|
+
return instance;
|
|
320
|
+
}
|
|
321
|
+
static async resume(agentDef, workingDirectory, agentSessionId) {
|
|
322
|
+
log.debug({ agentName: agentDef.name, agentSessionId }, "Resuming agent");
|
|
323
|
+
const spawnStart = Date.now();
|
|
324
|
+
const instance = await _AgentInstance.spawnSubprocess(
|
|
325
|
+
agentDef,
|
|
326
|
+
workingDirectory
|
|
327
|
+
);
|
|
328
|
+
try {
|
|
329
|
+
const response = await instance.connection.unstable_resumeSession({
|
|
330
|
+
sessionId: agentSessionId,
|
|
331
|
+
cwd: workingDirectory
|
|
332
|
+
});
|
|
333
|
+
instance.sessionId = response.sessionId;
|
|
334
|
+
log.info(
|
|
335
|
+
{ sessionId: response.sessionId, durationMs: Date.now() - spawnStart },
|
|
336
|
+
"Agent resume complete"
|
|
337
|
+
);
|
|
338
|
+
} catch (err) {
|
|
339
|
+
log.warn(
|
|
340
|
+
{ err, agentSessionId },
|
|
341
|
+
"Resume failed, falling back to new session"
|
|
342
|
+
);
|
|
343
|
+
const response = await instance.connection.newSession({
|
|
344
|
+
cwd: workingDirectory,
|
|
345
|
+
mcpServers: []
|
|
346
|
+
});
|
|
347
|
+
instance.sessionId = response.sessionId;
|
|
348
|
+
log.info(
|
|
349
|
+
{ sessionId: response.sessionId, durationMs: Date.now() - spawnStart },
|
|
350
|
+
"Agent fallback spawn complete"
|
|
351
|
+
);
|
|
352
|
+
}
|
|
353
|
+
instance.setupCrashDetection();
|
|
354
|
+
return instance;
|
|
355
|
+
}
|
|
356
|
+
// createClient — implemented in Task 6b
|
|
357
|
+
createClient(_agent) {
|
|
358
|
+
const self = this;
|
|
359
|
+
const MAX_OUTPUT_BYTES = 1024 * 1024;
|
|
360
|
+
return {
|
|
361
|
+
// ── Session updates ──────────────────────────────────────────────────
|
|
362
|
+
async sessionUpdate(params) {
|
|
363
|
+
const update = params.update;
|
|
364
|
+
let event = null;
|
|
365
|
+
switch (update.sessionUpdate) {
|
|
366
|
+
case "agent_message_chunk":
|
|
367
|
+
if (update.content.type === "text") {
|
|
368
|
+
event = { type: "text", content: update.content.text };
|
|
369
|
+
} else if (update.content.type === "image") {
|
|
370
|
+
const c = update.content;
|
|
371
|
+
event = { type: "image_content", data: c.data, mimeType: c.mimeType };
|
|
372
|
+
} else if (update.content.type === "audio") {
|
|
373
|
+
const c = update.content;
|
|
374
|
+
event = { type: "audio_content", data: c.data, mimeType: c.mimeType };
|
|
375
|
+
}
|
|
376
|
+
break;
|
|
377
|
+
case "agent_thought_chunk":
|
|
378
|
+
if (update.content.type === "text") {
|
|
379
|
+
event = { type: "thought", content: update.content.text };
|
|
380
|
+
}
|
|
381
|
+
break;
|
|
382
|
+
case "tool_call":
|
|
383
|
+
event = {
|
|
384
|
+
type: "tool_call",
|
|
385
|
+
id: update.toolCallId,
|
|
386
|
+
name: update.title,
|
|
387
|
+
kind: update.kind ?? void 0,
|
|
388
|
+
status: update.status ?? "pending",
|
|
389
|
+
content: update.content ?? void 0,
|
|
390
|
+
rawInput: update.rawInput ?? void 0,
|
|
391
|
+
meta: update._meta ?? void 0
|
|
392
|
+
};
|
|
393
|
+
break;
|
|
394
|
+
case "tool_call_update":
|
|
395
|
+
event = {
|
|
396
|
+
type: "tool_update",
|
|
397
|
+
id: update.toolCallId,
|
|
398
|
+
name: update.title ?? void 0,
|
|
399
|
+
kind: update.kind ?? void 0,
|
|
400
|
+
status: update.status ?? "pending",
|
|
401
|
+
content: update.content ?? void 0,
|
|
402
|
+
rawInput: update.rawInput ?? void 0,
|
|
403
|
+
meta: update._meta ?? void 0
|
|
404
|
+
};
|
|
405
|
+
break;
|
|
406
|
+
case "plan":
|
|
407
|
+
event = { type: "plan", entries: update.entries };
|
|
408
|
+
break;
|
|
409
|
+
case "usage_update":
|
|
410
|
+
event = {
|
|
411
|
+
type: "usage",
|
|
412
|
+
tokensUsed: update.used,
|
|
413
|
+
contextSize: update.size,
|
|
414
|
+
cost: update.cost ?? void 0
|
|
415
|
+
};
|
|
416
|
+
break;
|
|
417
|
+
case "available_commands_update":
|
|
418
|
+
event = {
|
|
419
|
+
type: "commands_update",
|
|
420
|
+
commands: update.availableCommands
|
|
421
|
+
};
|
|
422
|
+
break;
|
|
423
|
+
default:
|
|
424
|
+
return;
|
|
425
|
+
}
|
|
426
|
+
if (event !== null) {
|
|
427
|
+
self.emit("agent_event", event);
|
|
428
|
+
}
|
|
429
|
+
},
|
|
430
|
+
// ── Permission requests ──────────────────────────────────────────────
|
|
431
|
+
async requestPermission(params) {
|
|
432
|
+
const permissionRequest = {
|
|
433
|
+
id: params.toolCall.toolCallId,
|
|
434
|
+
description: params.toolCall.title ?? params.toolCall.toolCallId,
|
|
435
|
+
options: params.options.map((opt) => ({
|
|
436
|
+
id: opt.optionId,
|
|
437
|
+
label: opt.name,
|
|
438
|
+
isAllow: opt.kind === "allow_once" || opt.kind === "allow_always"
|
|
439
|
+
}))
|
|
440
|
+
};
|
|
441
|
+
const selectedOptionId = await self.onPermissionRequest(permissionRequest);
|
|
442
|
+
return {
|
|
443
|
+
outcome: { outcome: "selected", optionId: selectedOptionId }
|
|
444
|
+
};
|
|
445
|
+
},
|
|
446
|
+
// ── File operations ──────────────────────────────────────────────────
|
|
447
|
+
async readTextFile(params) {
|
|
448
|
+
const content = await fs.promises.readFile(params.path, "utf-8");
|
|
449
|
+
return { content };
|
|
450
|
+
},
|
|
451
|
+
async writeTextFile(params) {
|
|
452
|
+
await fs.promises.mkdir(path.dirname(params.path), { recursive: true });
|
|
453
|
+
await fs.promises.writeFile(params.path, params.content, "utf-8");
|
|
454
|
+
return {};
|
|
455
|
+
},
|
|
456
|
+
// ── Terminal operations ──────────────────────────────────────────────
|
|
457
|
+
async createTerminal(params) {
|
|
458
|
+
const terminalId = randomUUID();
|
|
459
|
+
const args = params.args ?? [];
|
|
460
|
+
const env = {};
|
|
461
|
+
for (const ev of params.env ?? []) {
|
|
462
|
+
env[ev.name] = ev.value;
|
|
463
|
+
}
|
|
464
|
+
const childProcess = spawn(params.command, args, {
|
|
465
|
+
cwd: params.cwd ?? void 0,
|
|
466
|
+
env: { ...process.env, ...env },
|
|
467
|
+
shell: false
|
|
468
|
+
});
|
|
469
|
+
const state = {
|
|
470
|
+
process: childProcess,
|
|
471
|
+
output: "",
|
|
472
|
+
exitStatus: null
|
|
473
|
+
};
|
|
474
|
+
self.terminals.set(terminalId, state);
|
|
475
|
+
const outputByteLimit = params.outputByteLimit ?? MAX_OUTPUT_BYTES;
|
|
476
|
+
const appendOutput = (chunk) => {
|
|
477
|
+
state.output += chunk;
|
|
478
|
+
const bytes = Buffer.byteLength(state.output, "utf-8");
|
|
479
|
+
if (bytes > outputByteLimit) {
|
|
480
|
+
const excess = bytes - outputByteLimit;
|
|
481
|
+
state.output = state.output.slice(excess);
|
|
482
|
+
}
|
|
483
|
+
};
|
|
484
|
+
childProcess.stdout?.on(
|
|
485
|
+
"data",
|
|
486
|
+
(chunk) => appendOutput(chunk.toString())
|
|
487
|
+
);
|
|
488
|
+
childProcess.stderr?.on(
|
|
489
|
+
"data",
|
|
490
|
+
(chunk) => appendOutput(chunk.toString())
|
|
491
|
+
);
|
|
492
|
+
childProcess.on("exit", (code, signal) => {
|
|
493
|
+
state.exitStatus = { exitCode: code, signal };
|
|
494
|
+
});
|
|
495
|
+
return { terminalId };
|
|
496
|
+
},
|
|
497
|
+
async terminalOutput(params) {
|
|
498
|
+
const state = self.terminals.get(params.terminalId);
|
|
499
|
+
if (!state) {
|
|
500
|
+
throw new Error(`Terminal not found: ${params.terminalId}`);
|
|
501
|
+
}
|
|
502
|
+
return {
|
|
503
|
+
output: state.output,
|
|
504
|
+
truncated: false,
|
|
505
|
+
exitStatus: state.exitStatus ? {
|
|
506
|
+
exitCode: state.exitStatus.exitCode,
|
|
507
|
+
signal: state.exitStatus.signal
|
|
508
|
+
} : void 0
|
|
509
|
+
};
|
|
510
|
+
},
|
|
511
|
+
async waitForTerminalExit(params) {
|
|
512
|
+
const state = self.terminals.get(params.terminalId);
|
|
513
|
+
if (!state) {
|
|
514
|
+
throw new Error(`Terminal not found: ${params.terminalId}`);
|
|
515
|
+
}
|
|
516
|
+
if (state.exitStatus !== null) {
|
|
517
|
+
return {
|
|
518
|
+
exitCode: state.exitStatus.exitCode,
|
|
519
|
+
signal: state.exitStatus.signal
|
|
520
|
+
};
|
|
521
|
+
}
|
|
522
|
+
return new Promise((resolve3) => {
|
|
523
|
+
state.process.on("exit", (code, signal) => {
|
|
524
|
+
resolve3({ exitCode: code, signal });
|
|
525
|
+
});
|
|
526
|
+
});
|
|
527
|
+
},
|
|
528
|
+
async killTerminal(params) {
|
|
529
|
+
const state = self.terminals.get(params.terminalId);
|
|
530
|
+
if (!state) {
|
|
531
|
+
throw new Error(`Terminal not found: ${params.terminalId}`);
|
|
532
|
+
}
|
|
533
|
+
state.process.kill("SIGTERM");
|
|
534
|
+
return {};
|
|
535
|
+
},
|
|
536
|
+
async releaseTerminal(params) {
|
|
537
|
+
const state = self.terminals.get(params.terminalId);
|
|
538
|
+
if (!state) {
|
|
539
|
+
return;
|
|
540
|
+
}
|
|
541
|
+
state.process.kill("SIGKILL");
|
|
542
|
+
self.terminals.delete(params.terminalId);
|
|
543
|
+
}
|
|
544
|
+
};
|
|
545
|
+
}
|
|
546
|
+
async prompt(text, attachments) {
|
|
547
|
+
const contentBlocks = [{ type: "text", text }];
|
|
548
|
+
const SUPPORTED_IMAGE_MIMES = /* @__PURE__ */ new Set(["image/jpeg", "image/png", "image/gif", "image/webp"]);
|
|
549
|
+
for (const att of attachments ?? []) {
|
|
550
|
+
const tooLarge = att.size > 10 * 1024 * 1024;
|
|
551
|
+
if (att.type === "image" && this.promptCapabilities?.image && !tooLarge && SUPPORTED_IMAGE_MIMES.has(att.mimeType)) {
|
|
552
|
+
const data = await fs.promises.readFile(att.filePath);
|
|
553
|
+
contentBlocks.push({ type: "image", data: data.toString("base64"), mimeType: att.mimeType });
|
|
554
|
+
} else if (att.type === "audio" && this.promptCapabilities?.audio && !tooLarge) {
|
|
555
|
+
const data = await fs.promises.readFile(att.filePath);
|
|
556
|
+
contentBlocks.push({ type: "audio", data: data.toString("base64"), mimeType: att.mimeType });
|
|
557
|
+
} else {
|
|
558
|
+
if ((att.type === "image" || att.type === "audio") && !tooLarge) {
|
|
559
|
+
log.debug(
|
|
560
|
+
{ type: att.type, capabilities: this.promptCapabilities ?? {} },
|
|
561
|
+
"Agent does not support %s content, falling back to file path",
|
|
562
|
+
att.type
|
|
563
|
+
);
|
|
564
|
+
}
|
|
565
|
+
contentBlocks[0].text += `
|
|
566
|
+
|
|
567
|
+
[Attached file: ${att.filePath}]`;
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
return this.connection.prompt({
|
|
571
|
+
sessionId: this.sessionId,
|
|
572
|
+
prompt: contentBlocks
|
|
573
|
+
});
|
|
574
|
+
}
|
|
575
|
+
async cancel() {
|
|
576
|
+
await this.connection.cancel({ sessionId: this.sessionId });
|
|
577
|
+
}
|
|
578
|
+
async destroy() {
|
|
579
|
+
for (const [, t] of this.terminals) {
|
|
580
|
+
t.process.kill("SIGKILL");
|
|
581
|
+
}
|
|
582
|
+
this.terminals.clear();
|
|
583
|
+
this.child.kill("SIGTERM");
|
|
584
|
+
setTimeout(() => {
|
|
585
|
+
if (!this.child.killed) this.child.kill("SIGKILL");
|
|
586
|
+
}, 1e4);
|
|
587
|
+
}
|
|
588
|
+
};
|
|
589
|
+
|
|
590
|
+
// src/core/agent-manager.ts
|
|
591
|
+
var AgentManager = class {
|
|
592
|
+
constructor(catalog) {
|
|
593
|
+
this.catalog = catalog;
|
|
594
|
+
}
|
|
595
|
+
getAvailableAgents() {
|
|
596
|
+
const installed = this.catalog.getInstalledEntries();
|
|
597
|
+
return Object.entries(installed).map(([key, agent]) => ({
|
|
598
|
+
name: key,
|
|
599
|
+
command: agent.command,
|
|
600
|
+
args: agent.args,
|
|
601
|
+
env: agent.env
|
|
602
|
+
}));
|
|
603
|
+
}
|
|
604
|
+
getAgent(name) {
|
|
605
|
+
return this.catalog.resolve(name);
|
|
606
|
+
}
|
|
607
|
+
async spawn(agentName, workingDirectory) {
|
|
608
|
+
const agentDef = this.getAgent(agentName);
|
|
609
|
+
if (!agentDef) throw new Error(`Agent "${agentName}" is not installed. Run "openacp agents install ${agentName}" to add it.`);
|
|
610
|
+
return AgentInstance.spawn(agentDef, workingDirectory);
|
|
611
|
+
}
|
|
612
|
+
async resume(agentName, workingDirectory, agentSessionId) {
|
|
613
|
+
const agentDef = this.getAgent(agentName);
|
|
614
|
+
if (!agentDef) throw new Error(`Agent "${agentName}" is not installed. Run "openacp agents install ${agentName}" to add it.`);
|
|
615
|
+
return AgentInstance.resume(agentDef, workingDirectory, agentSessionId);
|
|
616
|
+
}
|
|
617
|
+
};
|
|
618
|
+
|
|
619
|
+
// src/core/prompt-queue.ts
|
|
620
|
+
var PromptQueue = class {
|
|
621
|
+
constructor(processor, onError) {
|
|
622
|
+
this.processor = processor;
|
|
623
|
+
this.onError = onError;
|
|
624
|
+
}
|
|
625
|
+
queue = [];
|
|
626
|
+
processing = false;
|
|
627
|
+
abortController = null;
|
|
628
|
+
async enqueue(text, attachments) {
|
|
629
|
+
if (this.processing) {
|
|
630
|
+
return new Promise((resolve3) => {
|
|
631
|
+
this.queue.push({ text, attachments, resolve: resolve3 });
|
|
632
|
+
});
|
|
633
|
+
}
|
|
634
|
+
await this.process(text, attachments);
|
|
635
|
+
}
|
|
636
|
+
async process(text, attachments) {
|
|
637
|
+
this.processing = true;
|
|
638
|
+
this.abortController = new AbortController();
|
|
639
|
+
const { signal } = this.abortController;
|
|
640
|
+
try {
|
|
641
|
+
await Promise.race([
|
|
642
|
+
this.processor(text, attachments),
|
|
643
|
+
new Promise((_, reject) => {
|
|
644
|
+
signal.addEventListener("abort", () => reject(new Error("Prompt aborted")), { once: true });
|
|
645
|
+
})
|
|
646
|
+
]);
|
|
647
|
+
} catch (err) {
|
|
648
|
+
if (!(err instanceof Error && err.message === "Prompt aborted")) {
|
|
649
|
+
this.onError?.(err);
|
|
650
|
+
}
|
|
651
|
+
} finally {
|
|
652
|
+
this.abortController = null;
|
|
653
|
+
this.processing = false;
|
|
654
|
+
this.drainNext();
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
drainNext() {
|
|
658
|
+
const next = this.queue.shift();
|
|
659
|
+
if (next) {
|
|
660
|
+
this.process(next.text, next.attachments).then(next.resolve);
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
clear() {
|
|
664
|
+
if (this.abortController) {
|
|
665
|
+
this.abortController.abort();
|
|
666
|
+
}
|
|
667
|
+
for (const item of this.queue) {
|
|
668
|
+
item.resolve();
|
|
669
|
+
}
|
|
670
|
+
this.queue = [];
|
|
671
|
+
}
|
|
672
|
+
get pending() {
|
|
673
|
+
return this.queue.length;
|
|
674
|
+
}
|
|
675
|
+
get isProcessing() {
|
|
676
|
+
return this.processing;
|
|
677
|
+
}
|
|
678
|
+
};
|
|
679
|
+
|
|
680
|
+
// src/core/permission-gate.ts
|
|
681
|
+
var DEFAULT_TIMEOUT_MS = 10 * 60 * 1e3;
|
|
682
|
+
var PermissionGate = class {
|
|
683
|
+
request;
|
|
684
|
+
resolveFn;
|
|
685
|
+
rejectFn;
|
|
686
|
+
settled = false;
|
|
687
|
+
timeoutTimer;
|
|
688
|
+
timeoutMs;
|
|
689
|
+
constructor(timeoutMs) {
|
|
690
|
+
this.timeoutMs = timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
691
|
+
}
|
|
692
|
+
setPending(request) {
|
|
693
|
+
this.request = request;
|
|
694
|
+
this.settled = false;
|
|
695
|
+
this.clearTimeout();
|
|
696
|
+
return new Promise((resolve3, reject) => {
|
|
697
|
+
this.resolveFn = resolve3;
|
|
698
|
+
this.rejectFn = reject;
|
|
699
|
+
this.timeoutTimer = setTimeout(() => {
|
|
700
|
+
this.reject("Permission request timed out (no response received)");
|
|
701
|
+
}, this.timeoutMs);
|
|
702
|
+
});
|
|
703
|
+
}
|
|
704
|
+
resolve(optionId) {
|
|
705
|
+
if (this.settled || !this.resolveFn) return;
|
|
706
|
+
this.settled = true;
|
|
707
|
+
this.clearTimeout();
|
|
708
|
+
this.resolveFn(optionId);
|
|
709
|
+
this.cleanup();
|
|
710
|
+
}
|
|
711
|
+
reject(reason) {
|
|
712
|
+
if (this.settled || !this.rejectFn) return;
|
|
713
|
+
this.settled = true;
|
|
714
|
+
this.clearTimeout();
|
|
715
|
+
this.rejectFn(new Error(reason ?? "Permission rejected"));
|
|
716
|
+
this.cleanup();
|
|
717
|
+
}
|
|
718
|
+
get isPending() {
|
|
719
|
+
return !!this.request && !this.settled;
|
|
720
|
+
}
|
|
721
|
+
get currentRequest() {
|
|
722
|
+
return this.isPending ? this.request : void 0;
|
|
723
|
+
}
|
|
724
|
+
/** The request ID of the current pending request, undefined after settlement */
|
|
725
|
+
get requestId() {
|
|
726
|
+
return this.request?.id;
|
|
727
|
+
}
|
|
728
|
+
clearTimeout() {
|
|
729
|
+
if (this.timeoutTimer) {
|
|
730
|
+
clearTimeout(this.timeoutTimer);
|
|
731
|
+
this.timeoutTimer = void 0;
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
cleanup() {
|
|
735
|
+
this.request = void 0;
|
|
736
|
+
this.resolveFn = void 0;
|
|
737
|
+
this.rejectFn = void 0;
|
|
738
|
+
}
|
|
739
|
+
};
|
|
740
|
+
|
|
741
|
+
// src/core/session.ts
|
|
742
|
+
import { nanoid } from "nanoid";
|
|
743
|
+
import * as fs2 from "fs";
|
|
744
|
+
var moduleLog = createChildLogger({ module: "session" });
|
|
745
|
+
var TTS_PROMPT_INSTRUCTION = `
|
|
746
|
+
|
|
747
|
+
Additionally, include a [TTS]...[/TTS] block with a spoken-friendly summary of your response. Focus on key information, decisions the user needs to make, or actions required. The agent decides what to say and how long. Respond in the same language the user is using. This instruction applies to this message only.`;
|
|
748
|
+
var TTS_BLOCK_REGEX = /\[TTS\]([\s\S]*?)\[\/TTS\]/;
|
|
749
|
+
var TTS_MAX_LENGTH = 5e3;
|
|
750
|
+
var TTS_TIMEOUT_MS = 3e4;
|
|
751
|
+
var VALID_TRANSITIONS = {
|
|
752
|
+
initializing: /* @__PURE__ */ new Set(["active", "error"]),
|
|
753
|
+
active: /* @__PURE__ */ new Set(["error", "finished", "cancelled"]),
|
|
754
|
+
error: /* @__PURE__ */ new Set(["active"]),
|
|
755
|
+
cancelled: /* @__PURE__ */ new Set(["active"]),
|
|
756
|
+
finished: /* @__PURE__ */ new Set()
|
|
757
|
+
};
|
|
758
|
+
var Session = class extends TypedEmitter {
|
|
759
|
+
id;
|
|
760
|
+
channelId;
|
|
761
|
+
threadId = "";
|
|
762
|
+
agentName;
|
|
763
|
+
workingDirectory;
|
|
764
|
+
agentInstance;
|
|
765
|
+
agentSessionId = "";
|
|
766
|
+
_status = "initializing";
|
|
767
|
+
name;
|
|
768
|
+
createdAt = /* @__PURE__ */ new Date();
|
|
769
|
+
voiceMode = "off";
|
|
770
|
+
dangerousMode = false;
|
|
771
|
+
archiving = false;
|
|
772
|
+
log;
|
|
773
|
+
permissionGate = new PermissionGate();
|
|
774
|
+
queue;
|
|
775
|
+
speechService;
|
|
776
|
+
constructor(opts) {
|
|
777
|
+
super();
|
|
778
|
+
this.id = opts.id || nanoid(12);
|
|
779
|
+
this.channelId = opts.channelId;
|
|
780
|
+
this.agentName = opts.agentName;
|
|
781
|
+
this.workingDirectory = opts.workingDirectory;
|
|
782
|
+
this.agentInstance = opts.agentInstance;
|
|
783
|
+
this.speechService = opts.speechService;
|
|
784
|
+
this.log = createSessionLogger(this.id, moduleLog);
|
|
785
|
+
this.log.info({ agentName: this.agentName }, "Session created");
|
|
786
|
+
this.queue = new PromptQueue(
|
|
787
|
+
(text, attachments) => this.processPrompt(text, attachments),
|
|
788
|
+
(err) => {
|
|
789
|
+
this.fail("Prompt execution failed");
|
|
790
|
+
this.log.error({ err }, "Prompt execution failed");
|
|
791
|
+
}
|
|
792
|
+
);
|
|
793
|
+
}
|
|
794
|
+
// --- State Machine ---
|
|
795
|
+
get status() {
|
|
796
|
+
return this._status;
|
|
797
|
+
}
|
|
798
|
+
/** Transition to active — from initializing, error, or cancelled */
|
|
799
|
+
activate() {
|
|
800
|
+
this.transition("active");
|
|
801
|
+
}
|
|
802
|
+
/** Transition to error — from initializing or active */
|
|
803
|
+
fail(reason) {
|
|
804
|
+
this.transition("error");
|
|
805
|
+
this.emit("error", new Error(reason));
|
|
806
|
+
}
|
|
807
|
+
/** Transition to finished — from active only. Emits session_end for backward compat. */
|
|
808
|
+
finish(reason) {
|
|
809
|
+
this.transition("finished");
|
|
810
|
+
this.emit("session_end", reason ?? "completed");
|
|
811
|
+
}
|
|
812
|
+
/** Transition to cancelled — from active only (terminal session cancel) */
|
|
813
|
+
markCancelled() {
|
|
814
|
+
this.transition("cancelled");
|
|
815
|
+
}
|
|
816
|
+
transition(to) {
|
|
817
|
+
const from = this._status;
|
|
818
|
+
const allowed = VALID_TRANSITIONS[from];
|
|
819
|
+
if (!allowed?.has(to)) {
|
|
820
|
+
throw new Error(
|
|
821
|
+
`Invalid session transition: ${from} \u2192 ${to}`
|
|
822
|
+
);
|
|
823
|
+
}
|
|
824
|
+
this._status = to;
|
|
825
|
+
this.log.debug({ from, to }, "Session status transition");
|
|
826
|
+
this.emit("status_change", from, to);
|
|
827
|
+
}
|
|
828
|
+
/** Number of prompts waiting in queue */
|
|
829
|
+
get queueDepth() {
|
|
830
|
+
return this.queue.pending;
|
|
831
|
+
}
|
|
832
|
+
get promptRunning() {
|
|
833
|
+
return this.queue.isProcessing;
|
|
834
|
+
}
|
|
835
|
+
// --- Voice Mode ---
|
|
836
|
+
setVoiceMode(mode) {
|
|
837
|
+
this.voiceMode = mode;
|
|
838
|
+
this.log.info({ voiceMode: mode }, "TTS mode changed");
|
|
839
|
+
}
|
|
840
|
+
// --- Public API ---
|
|
841
|
+
async enqueuePrompt(text, attachments) {
|
|
842
|
+
await this.queue.enqueue(text, attachments);
|
|
843
|
+
}
|
|
844
|
+
async processPrompt(text, attachments) {
|
|
845
|
+
if (text === "\0__warmup__") {
|
|
846
|
+
await this.runWarmup();
|
|
847
|
+
return;
|
|
848
|
+
}
|
|
849
|
+
if (this._status === "initializing") {
|
|
850
|
+
this.activate();
|
|
851
|
+
}
|
|
852
|
+
const promptStart = Date.now();
|
|
853
|
+
this.log.debug("Prompt execution started");
|
|
854
|
+
const processed = await this.maybeTranscribeAudio(text, attachments);
|
|
855
|
+
const ttsActive = this.voiceMode !== "off" && !!this.speechService?.isTTSAvailable();
|
|
856
|
+
if (ttsActive) {
|
|
857
|
+
processed.text += TTS_PROMPT_INSTRUCTION;
|
|
858
|
+
if (this.voiceMode === "next") {
|
|
859
|
+
this.voiceMode = "off";
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
let accumulatedText = "";
|
|
863
|
+
const accumulatorListener = ttsActive ? (event) => {
|
|
864
|
+
if (event.type === "text") {
|
|
865
|
+
accumulatedText += event.content;
|
|
866
|
+
}
|
|
867
|
+
} : null;
|
|
868
|
+
if (accumulatorListener) {
|
|
869
|
+
this.on("agent_event", accumulatorListener);
|
|
870
|
+
}
|
|
871
|
+
try {
|
|
872
|
+
await this.agentInstance.prompt(processed.text, processed.attachments);
|
|
873
|
+
} finally {
|
|
874
|
+
if (accumulatorListener) {
|
|
875
|
+
this.off("agent_event", accumulatorListener);
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
this.log.info(
|
|
879
|
+
{ durationMs: Date.now() - promptStart },
|
|
880
|
+
"Prompt execution completed"
|
|
881
|
+
);
|
|
882
|
+
if (ttsActive && accumulatedText) {
|
|
883
|
+
this.processTTSResponse(accumulatedText).catch((err) => {
|
|
884
|
+
this.log.warn({ err }, "TTS post-processing failed");
|
|
885
|
+
});
|
|
886
|
+
}
|
|
887
|
+
if (!this.name) {
|
|
888
|
+
await this.autoName();
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
async maybeTranscribeAudio(text, attachments) {
|
|
892
|
+
if (!attachments?.length || !this.speechService) {
|
|
893
|
+
return { text, attachments };
|
|
894
|
+
}
|
|
895
|
+
const hasAudioCapability = this.agentInstance.promptCapabilities?.audio === true;
|
|
896
|
+
if (hasAudioCapability) {
|
|
897
|
+
return { text, attachments };
|
|
898
|
+
}
|
|
899
|
+
if (!this.speechService.isSTTAvailable()) {
|
|
900
|
+
return { text, attachments };
|
|
901
|
+
}
|
|
902
|
+
let transcribedText = text;
|
|
903
|
+
const remainingAttachments = [];
|
|
904
|
+
for (const att of attachments) {
|
|
905
|
+
if (att.type !== "audio") {
|
|
906
|
+
remainingAttachments.push(att);
|
|
907
|
+
continue;
|
|
908
|
+
}
|
|
909
|
+
try {
|
|
910
|
+
const audioPath = att.originalFilePath || att.filePath;
|
|
911
|
+
const audioMime = att.originalFilePath ? "audio/ogg" : att.mimeType;
|
|
912
|
+
const audioBuffer = await fs2.promises.readFile(audioPath);
|
|
913
|
+
const result = await this.speechService.transcribe(audioBuffer, audioMime);
|
|
914
|
+
this.log.info({ provider: "stt", duration: result.duration }, "Voice transcribed");
|
|
915
|
+
this.emit("agent_event", {
|
|
916
|
+
type: "system_message",
|
|
917
|
+
message: `\u{1F3A4} You said: ${result.text}`
|
|
918
|
+
});
|
|
919
|
+
transcribedText = transcribedText.replace(/\[Audio:\s*[^\]]*\]\s*/g, "").trim();
|
|
920
|
+
transcribedText = transcribedText ? `${transcribedText}
|
|
921
|
+
${result.text}` : result.text;
|
|
922
|
+
} catch (err) {
|
|
923
|
+
this.log.warn({ err }, "STT transcription failed, keeping audio attachment");
|
|
924
|
+
this.emit("agent_event", {
|
|
925
|
+
type: "error",
|
|
926
|
+
message: `Voice transcription failed: ${err.message}`
|
|
927
|
+
});
|
|
928
|
+
remainingAttachments.push(att);
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
return {
|
|
932
|
+
text: transcribedText,
|
|
933
|
+
attachments: remainingAttachments.length > 0 ? remainingAttachments : void 0
|
|
934
|
+
};
|
|
935
|
+
}
|
|
936
|
+
async processTTSResponse(responseText) {
|
|
937
|
+
const match = TTS_BLOCK_REGEX.exec(responseText);
|
|
938
|
+
if (!match?.[1]) {
|
|
939
|
+
this.log.debug("No [TTS] block found in response, skipping synthesis");
|
|
940
|
+
return;
|
|
941
|
+
}
|
|
942
|
+
let ttsText = match[1].trim();
|
|
943
|
+
if (!ttsText) return;
|
|
944
|
+
if (ttsText.length > TTS_MAX_LENGTH) {
|
|
945
|
+
ttsText = ttsText.slice(0, TTS_MAX_LENGTH);
|
|
946
|
+
}
|
|
947
|
+
try {
|
|
948
|
+
const timeoutPromise = new Promise(
|
|
949
|
+
(_, reject) => setTimeout(() => reject(new Error("TTS synthesis timed out")), TTS_TIMEOUT_MS)
|
|
950
|
+
);
|
|
951
|
+
const result = await Promise.race([
|
|
952
|
+
this.speechService.synthesize(ttsText),
|
|
953
|
+
timeoutPromise
|
|
954
|
+
]);
|
|
955
|
+
const base64 = result.audioBuffer.toString("base64");
|
|
956
|
+
this.emit("agent_event", {
|
|
957
|
+
type: "audio_content",
|
|
958
|
+
data: base64,
|
|
959
|
+
mimeType: result.mimeType
|
|
960
|
+
});
|
|
961
|
+
this.log.info("TTS synthesis completed");
|
|
962
|
+
} catch (err) {
|
|
963
|
+
this.log.warn({ err }, "TTS synthesis failed, skipping");
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
// NOTE: This injects a summary prompt into the agent's conversation history.
|
|
967
|
+
async autoName() {
|
|
968
|
+
let title = "";
|
|
969
|
+
const captureHandler = (event) => {
|
|
970
|
+
if (event.type === "text") title += event.content;
|
|
971
|
+
};
|
|
972
|
+
this.pause((event) => event !== "agent_event");
|
|
973
|
+
this.agentInstance.on("agent_event", captureHandler);
|
|
974
|
+
try {
|
|
975
|
+
await this.agentInstance.prompt(
|
|
976
|
+
"Summarize this conversation in max 5 words for a topic title. Reply ONLY with the title, nothing else."
|
|
977
|
+
);
|
|
978
|
+
this.name = title.trim().slice(0, 50) || `Session ${this.id.slice(0, 6)}`;
|
|
979
|
+
this.log.info({ name: this.name }, "Session auto-named");
|
|
980
|
+
this.emit("named", this.name);
|
|
981
|
+
} catch {
|
|
982
|
+
this.name = `Session ${this.id.slice(0, 6)}`;
|
|
983
|
+
} finally {
|
|
984
|
+
this.agentInstance.off("agent_event", captureHandler);
|
|
985
|
+
this.clearBuffer();
|
|
986
|
+
this.resume();
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
/** Fire-and-forget warm-up: primes model cache while user types their first message */
|
|
990
|
+
async warmup() {
|
|
991
|
+
await this.queue.enqueue("\0__warmup__");
|
|
992
|
+
}
|
|
993
|
+
async runWarmup() {
|
|
994
|
+
this.pause((_event, args) => {
|
|
995
|
+
const agentEvent = args[0];
|
|
996
|
+
return agentEvent?.type === "commands_update";
|
|
997
|
+
});
|
|
998
|
+
try {
|
|
999
|
+
const start = Date.now();
|
|
1000
|
+
await this.agentInstance.prompt('Reply with only "ready".');
|
|
1001
|
+
this.activate();
|
|
1002
|
+
this.log.info({ durationMs: Date.now() - start }, "Warm-up complete");
|
|
1003
|
+
} catch (err) {
|
|
1004
|
+
this.log.error({ err }, "Warm-up failed");
|
|
1005
|
+
} finally {
|
|
1006
|
+
this.clearBuffer();
|
|
1007
|
+
this.resume();
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
1010
|
+
/** Cancel the current prompt and clear the queue. Stays in active state. */
|
|
1011
|
+
async abortPrompt() {
|
|
1012
|
+
this.queue.clear();
|
|
1013
|
+
this.log.info("Prompt aborted");
|
|
1014
|
+
await this.agentInstance.cancel();
|
|
1015
|
+
}
|
|
1016
|
+
async destroy() {
|
|
1017
|
+
this.log.info("Session destroyed");
|
|
1018
|
+
await this.agentInstance.destroy();
|
|
1019
|
+
}
|
|
1020
|
+
};
|
|
1021
|
+
|
|
1022
|
+
// src/core/session-manager.ts
|
|
1023
|
+
var SessionManager = class {
|
|
1024
|
+
sessions = /* @__PURE__ */ new Map();
|
|
1025
|
+
store;
|
|
1026
|
+
eventBus;
|
|
1027
|
+
setEventBus(eventBus) {
|
|
1028
|
+
this.eventBus = eventBus;
|
|
1029
|
+
}
|
|
1030
|
+
constructor(store = null) {
|
|
1031
|
+
this.store = store;
|
|
1032
|
+
}
|
|
1033
|
+
async createSession(channelId, agentName, workingDirectory, agentManager) {
|
|
1034
|
+
const agentInstance = await agentManager.spawn(agentName, workingDirectory);
|
|
1035
|
+
const session = new Session({
|
|
1036
|
+
channelId,
|
|
1037
|
+
agentName,
|
|
1038
|
+
workingDirectory,
|
|
1039
|
+
agentInstance
|
|
1040
|
+
});
|
|
1041
|
+
this.sessions.set(session.id, session);
|
|
1042
|
+
session.agentSessionId = session.agentInstance.sessionId;
|
|
1043
|
+
if (this.store) {
|
|
1044
|
+
await this.store.save({
|
|
1045
|
+
sessionId: session.id,
|
|
1046
|
+
agentSessionId: session.agentInstance.sessionId,
|
|
1047
|
+
agentName: session.agentName,
|
|
1048
|
+
workingDir: session.workingDirectory,
|
|
1049
|
+
channelId,
|
|
1050
|
+
status: session.status,
|
|
1051
|
+
createdAt: session.createdAt.toISOString(),
|
|
1052
|
+
lastActiveAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1053
|
+
name: session.name,
|
|
1054
|
+
dangerousMode: false,
|
|
1055
|
+
platform: {}
|
|
1056
|
+
});
|
|
1057
|
+
}
|
|
1058
|
+
return session;
|
|
1059
|
+
}
|
|
1060
|
+
getSession(sessionId) {
|
|
1061
|
+
return this.sessions.get(sessionId);
|
|
1062
|
+
}
|
|
1063
|
+
getSessionByThread(channelId, threadId) {
|
|
1064
|
+
for (const session of this.sessions.values()) {
|
|
1065
|
+
if (session.channelId === channelId && session.threadId === threadId) {
|
|
1066
|
+
return session;
|
|
1067
|
+
}
|
|
1068
|
+
}
|
|
1069
|
+
return void 0;
|
|
1070
|
+
}
|
|
1071
|
+
getSessionByAgentSessionId(agentSessionId) {
|
|
1072
|
+
for (const session of this.sessions.values()) {
|
|
1073
|
+
if (session.agentSessionId === agentSessionId) {
|
|
1074
|
+
return session;
|
|
1075
|
+
}
|
|
1076
|
+
}
|
|
1077
|
+
return void 0;
|
|
1078
|
+
}
|
|
1079
|
+
getRecordByAgentSessionId(agentSessionId) {
|
|
1080
|
+
return this.store?.findByAgentSessionId(agentSessionId);
|
|
1081
|
+
}
|
|
1082
|
+
getRecordByThread(channelId, threadId) {
|
|
1083
|
+
return this.store?.findByPlatform(
|
|
1084
|
+
channelId,
|
|
1085
|
+
(p) => String(p.topicId) === threadId || p.threadId === threadId
|
|
1086
|
+
);
|
|
1087
|
+
}
|
|
1088
|
+
registerSession(session) {
|
|
1089
|
+
this.sessions.set(session.id, session);
|
|
1090
|
+
}
|
|
1091
|
+
async patchRecord(sessionId, patch) {
|
|
1092
|
+
if (!this.store) return;
|
|
1093
|
+
const record = this.store.get(sessionId);
|
|
1094
|
+
if (record) {
|
|
1095
|
+
await this.store.save({ ...record, ...patch });
|
|
1096
|
+
} else if (patch.sessionId) {
|
|
1097
|
+
await this.store.save(patch);
|
|
1098
|
+
}
|
|
1099
|
+
}
|
|
1100
|
+
getSessionRecord(sessionId) {
|
|
1101
|
+
return this.store?.get(sessionId);
|
|
1102
|
+
}
|
|
1103
|
+
async cancelSession(sessionId) {
|
|
1104
|
+
const session = this.sessions.get(sessionId);
|
|
1105
|
+
if (session) {
|
|
1106
|
+
await session.abortPrompt();
|
|
1107
|
+
session.markCancelled();
|
|
1108
|
+
}
|
|
1109
|
+
if (this.store) {
|
|
1110
|
+
const record = this.store.get(sessionId);
|
|
1111
|
+
if (record && record.status !== "cancelled") {
|
|
1112
|
+
await this.store.save({ ...record, status: "cancelled" });
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
listSessions(channelId) {
|
|
1117
|
+
const all = Array.from(this.sessions.values());
|
|
1118
|
+
if (channelId) return all.filter((s) => s.channelId === channelId);
|
|
1119
|
+
return all;
|
|
1120
|
+
}
|
|
1121
|
+
listRecords(filter) {
|
|
1122
|
+
if (!this.store) return [];
|
|
1123
|
+
let records = this.store.list();
|
|
1124
|
+
if (filter?.statuses?.length) {
|
|
1125
|
+
records = records.filter((r) => filter.statuses.includes(r.status));
|
|
1126
|
+
}
|
|
1127
|
+
return records;
|
|
1128
|
+
}
|
|
1129
|
+
async removeRecord(sessionId) {
|
|
1130
|
+
if (!this.store) return;
|
|
1131
|
+
await this.store.remove(sessionId);
|
|
1132
|
+
this.eventBus?.emit("session:deleted", { sessionId });
|
|
1133
|
+
}
|
|
1134
|
+
async destroyAll() {
|
|
1135
|
+
if (this.store) {
|
|
1136
|
+
for (const session of this.sessions.values()) {
|
|
1137
|
+
const record = this.store.get(session.id);
|
|
1138
|
+
if (record) {
|
|
1139
|
+
await this.store.save({ ...record, status: "finished" });
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
for (const session of this.sessions.values()) {
|
|
1144
|
+
await session.destroy();
|
|
1145
|
+
}
|
|
1146
|
+
this.sessions.clear();
|
|
1147
|
+
}
|
|
1148
|
+
};
|
|
1149
|
+
|
|
1150
|
+
// src/core/file-service.ts
|
|
1151
|
+
import fs3 from "fs";
|
|
1152
|
+
import path2 from "path";
|
|
1153
|
+
import { OggOpusDecoder } from "ogg-opus-decoder";
|
|
1154
|
+
import wav from "node-wav";
|
|
1155
|
+
var MIME_TO_EXT = {
|
|
1156
|
+
"image/jpeg": ".jpg",
|
|
1157
|
+
"image/png": ".png",
|
|
1158
|
+
"image/gif": ".gif",
|
|
1159
|
+
"image/webp": ".webp",
|
|
1160
|
+
"image/svg+xml": ".svg",
|
|
1161
|
+
"audio/ogg": ".ogg",
|
|
1162
|
+
"audio/mpeg": ".mp3",
|
|
1163
|
+
"audio/wav": ".wav",
|
|
1164
|
+
"audio/webm": ".webm",
|
|
1165
|
+
"audio/mp4": ".m4a",
|
|
1166
|
+
"video/mp4": ".mp4",
|
|
1167
|
+
"video/webm": ".webm",
|
|
1168
|
+
"application/pdf": ".pdf",
|
|
1169
|
+
"text/plain": ".txt"
|
|
1170
|
+
};
|
|
1171
|
+
var EXT_TO_MIME = {
|
|
1172
|
+
".jpg": "image/jpeg",
|
|
1173
|
+
".jpeg": "image/jpeg",
|
|
1174
|
+
".png": "image/png",
|
|
1175
|
+
".gif": "image/gif",
|
|
1176
|
+
".webp": "image/webp",
|
|
1177
|
+
".svg": "image/svg+xml",
|
|
1178
|
+
".ogg": "audio/ogg",
|
|
1179
|
+
".oga": "audio/ogg",
|
|
1180
|
+
".mp3": "audio/mpeg",
|
|
1181
|
+
".wav": "audio/wav",
|
|
1182
|
+
".m4a": "audio/mp4",
|
|
1183
|
+
".mp4": "video/mp4",
|
|
1184
|
+
".pdf": "application/pdf",
|
|
1185
|
+
".txt": "text/plain"
|
|
1186
|
+
};
|
|
1187
|
+
function classifyMime(mimeType) {
|
|
1188
|
+
if (mimeType.startsWith("image/")) return "image";
|
|
1189
|
+
if (mimeType.startsWith("audio/")) return "audio";
|
|
1190
|
+
return "file";
|
|
1191
|
+
}
|
|
1192
|
+
var FileService = class {
|
|
1193
|
+
constructor(baseDir) {
|
|
1194
|
+
this.baseDir = baseDir;
|
|
1195
|
+
}
|
|
1196
|
+
async saveFile(sessionId, fileName, data, mimeType) {
|
|
1197
|
+
const sessionDir = path2.join(this.baseDir, sessionId);
|
|
1198
|
+
await fs3.promises.mkdir(sessionDir, { recursive: true });
|
|
1199
|
+
const safeName = `${Date.now()}-${fileName.replace(/[^a-zA-Z0-9._-]/g, "_")}`;
|
|
1200
|
+
const filePath = path2.join(sessionDir, safeName);
|
|
1201
|
+
await fs3.promises.writeFile(filePath, data);
|
|
1202
|
+
return {
|
|
1203
|
+
type: classifyMime(mimeType),
|
|
1204
|
+
filePath,
|
|
1205
|
+
fileName,
|
|
1206
|
+
mimeType,
|
|
1207
|
+
size: data.length
|
|
1208
|
+
};
|
|
1209
|
+
}
|
|
1210
|
+
async resolveFile(filePath) {
|
|
1211
|
+
try {
|
|
1212
|
+
const stat = await fs3.promises.stat(filePath);
|
|
1213
|
+
if (!stat.isFile()) return null;
|
|
1214
|
+
const ext = path2.extname(filePath).toLowerCase();
|
|
1215
|
+
const mimeType = EXT_TO_MIME[ext] || "application/octet-stream";
|
|
1216
|
+
return {
|
|
1217
|
+
type: classifyMime(mimeType),
|
|
1218
|
+
filePath,
|
|
1219
|
+
fileName: path2.basename(filePath),
|
|
1220
|
+
mimeType,
|
|
1221
|
+
size: stat.size
|
|
1222
|
+
};
|
|
1223
|
+
} catch {
|
|
1224
|
+
return null;
|
|
1225
|
+
}
|
|
1226
|
+
}
|
|
1227
|
+
/**
|
|
1228
|
+
* Convert OGG Opus audio to WAV format.
|
|
1229
|
+
* Telegram voice messages use OGG Opus which many AI agents can't read.
|
|
1230
|
+
*/
|
|
1231
|
+
async convertOggToWav(oggData) {
|
|
1232
|
+
const decoder = new OggOpusDecoder();
|
|
1233
|
+
await decoder.ready;
|
|
1234
|
+
try {
|
|
1235
|
+
const { channelData, sampleRate } = await decoder.decode(new Uint8Array(oggData));
|
|
1236
|
+
const wavData = wav.encode(channelData, { sampleRate, float: true, bitDepth: 32 });
|
|
1237
|
+
return Buffer.from(wavData);
|
|
1238
|
+
} finally {
|
|
1239
|
+
decoder.free();
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
static extensionFromMime(mimeType) {
|
|
1243
|
+
return MIME_TO_EXT[mimeType] || ".bin";
|
|
1244
|
+
}
|
|
1245
|
+
};
|
|
1246
|
+
|
|
1247
|
+
// src/core/session-bridge.ts
|
|
1248
|
+
var log2 = createChildLogger({ module: "session-bridge" });
|
|
1249
|
+
var SessionBridge = class {
|
|
1250
|
+
constructor(session, adapter, deps) {
|
|
1251
|
+
this.session = session;
|
|
1252
|
+
this.adapter = adapter;
|
|
1253
|
+
this.deps = deps;
|
|
1254
|
+
}
|
|
1255
|
+
connected = false;
|
|
1256
|
+
agentEventHandler;
|
|
1257
|
+
sessionEventHandler;
|
|
1258
|
+
statusChangeHandler;
|
|
1259
|
+
namedHandler;
|
|
1260
|
+
connect() {
|
|
1261
|
+
if (this.connected) return;
|
|
1262
|
+
this.connected = true;
|
|
1263
|
+
this.wireAgentToSession();
|
|
1264
|
+
this.wireSessionToAdapter();
|
|
1265
|
+
this.wirePermissions();
|
|
1266
|
+
this.wireLifecycle();
|
|
1267
|
+
}
|
|
1268
|
+
disconnect() {
|
|
1269
|
+
if (!this.connected) return;
|
|
1270
|
+
this.connected = false;
|
|
1271
|
+
if (this.agentEventHandler) {
|
|
1272
|
+
this.session.agentInstance.off("agent_event", this.agentEventHandler);
|
|
1273
|
+
}
|
|
1274
|
+
if (this.sessionEventHandler) {
|
|
1275
|
+
this.session.off("agent_event", this.sessionEventHandler);
|
|
1276
|
+
}
|
|
1277
|
+
if (this.statusChangeHandler) {
|
|
1278
|
+
this.session.off("status_change", this.statusChangeHandler);
|
|
1279
|
+
}
|
|
1280
|
+
if (this.namedHandler) {
|
|
1281
|
+
this.session.off("named", this.namedHandler);
|
|
1282
|
+
}
|
|
1283
|
+
this.session.agentInstance.onPermissionRequest = async () => "";
|
|
1284
|
+
}
|
|
1285
|
+
wireAgentToSession() {
|
|
1286
|
+
this.agentEventHandler = (event) => {
|
|
1287
|
+
this.session.emit("agent_event", event);
|
|
1288
|
+
};
|
|
1289
|
+
this.session.agentInstance.on("agent_event", this.agentEventHandler);
|
|
1290
|
+
}
|
|
1291
|
+
wireSessionToAdapter() {
|
|
1292
|
+
const session = this.session;
|
|
1293
|
+
const ctx = {
|
|
1294
|
+
get id() {
|
|
1295
|
+
return session.id;
|
|
1296
|
+
},
|
|
1297
|
+
get workingDirectory() {
|
|
1298
|
+
return session.workingDirectory;
|
|
1299
|
+
}
|
|
1300
|
+
};
|
|
1301
|
+
this.sessionEventHandler = (event) => {
|
|
1302
|
+
switch (event.type) {
|
|
1303
|
+
case "text":
|
|
1304
|
+
case "thought":
|
|
1305
|
+
case "tool_call":
|
|
1306
|
+
case "tool_update":
|
|
1307
|
+
case "plan":
|
|
1308
|
+
case "usage":
|
|
1309
|
+
this.adapter.sendMessage(
|
|
1310
|
+
this.session.id,
|
|
1311
|
+
this.deps.messageTransformer.transform(event, ctx)
|
|
1312
|
+
);
|
|
1313
|
+
break;
|
|
1314
|
+
case "session_end":
|
|
1315
|
+
this.session.finish(event.reason);
|
|
1316
|
+
this.adapter.cleanupSkillCommands(this.session.id);
|
|
1317
|
+
this.adapter.sendMessage(
|
|
1318
|
+
this.session.id,
|
|
1319
|
+
this.deps.messageTransformer.transform(event)
|
|
1320
|
+
);
|
|
1321
|
+
this.deps.notificationManager.notify(this.session.channelId, {
|
|
1322
|
+
sessionId: this.session.id,
|
|
1323
|
+
sessionName: this.session.name,
|
|
1324
|
+
type: "completed",
|
|
1325
|
+
summary: `Session "${this.session.name || this.session.id}" completed`
|
|
1326
|
+
});
|
|
1327
|
+
break;
|
|
1328
|
+
case "error":
|
|
1329
|
+
this.session.fail(event.message);
|
|
1330
|
+
this.adapter.cleanupSkillCommands(this.session.id);
|
|
1331
|
+
this.adapter.sendMessage(
|
|
1332
|
+
this.session.id,
|
|
1333
|
+
this.deps.messageTransformer.transform(event)
|
|
1334
|
+
);
|
|
1335
|
+
this.deps.notificationManager.notify(this.session.channelId, {
|
|
1336
|
+
sessionId: this.session.id,
|
|
1337
|
+
sessionName: this.session.name,
|
|
1338
|
+
type: "error",
|
|
1339
|
+
summary: event.message
|
|
1340
|
+
});
|
|
1341
|
+
break;
|
|
1342
|
+
case "image_content": {
|
|
1343
|
+
if (this.deps.fileService) {
|
|
1344
|
+
const fs8 = this.deps.fileService;
|
|
1345
|
+
const sid = this.session.id;
|
|
1346
|
+
const { data, mimeType } = event;
|
|
1347
|
+
const buffer = Buffer.from(data, "base64");
|
|
1348
|
+
const ext = FileService.extensionFromMime(mimeType);
|
|
1349
|
+
fs8.saveFile(sid, `agent-image${ext}`, buffer, mimeType).then((att) => {
|
|
1350
|
+
this.adapter.sendMessage(sid, {
|
|
1351
|
+
type: "attachment",
|
|
1352
|
+
text: "",
|
|
1353
|
+
attachment: att
|
|
1354
|
+
});
|
|
1355
|
+
}).catch((err) => log2.error({ err }, "Failed to save agent image"));
|
|
1356
|
+
}
|
|
1357
|
+
break;
|
|
1358
|
+
}
|
|
1359
|
+
case "audio_content": {
|
|
1360
|
+
if (this.deps.fileService) {
|
|
1361
|
+
const fs8 = this.deps.fileService;
|
|
1362
|
+
const sid = this.session.id;
|
|
1363
|
+
const { data, mimeType } = event;
|
|
1364
|
+
const buffer = Buffer.from(data, "base64");
|
|
1365
|
+
const ext = FileService.extensionFromMime(mimeType);
|
|
1366
|
+
fs8.saveFile(sid, `agent-audio${ext}`, buffer, mimeType).then((att) => {
|
|
1367
|
+
this.adapter.sendMessage(sid, {
|
|
1368
|
+
type: "attachment",
|
|
1369
|
+
text: "",
|
|
1370
|
+
attachment: att
|
|
1371
|
+
});
|
|
1372
|
+
}).catch((err) => log2.error({ err }, "Failed to save agent audio"));
|
|
1373
|
+
}
|
|
1374
|
+
break;
|
|
1375
|
+
}
|
|
1376
|
+
case "commands_update":
|
|
1377
|
+
log2.debug({ commands: event.commands }, "Commands available");
|
|
1378
|
+
this.adapter.sendSkillCommands(this.session.id, event.commands);
|
|
1379
|
+
break;
|
|
1380
|
+
case "system_message":
|
|
1381
|
+
this.adapter.sendMessage(
|
|
1382
|
+
this.session.id,
|
|
1383
|
+
this.deps.messageTransformer.transform(event)
|
|
1384
|
+
);
|
|
1385
|
+
break;
|
|
1386
|
+
}
|
|
1387
|
+
this.deps.eventBus?.emit("agent:event", {
|
|
1388
|
+
sessionId: this.session.id,
|
|
1389
|
+
event
|
|
1390
|
+
});
|
|
1391
|
+
};
|
|
1392
|
+
this.session.on("agent_event", this.sessionEventHandler);
|
|
1393
|
+
}
|
|
1394
|
+
wirePermissions() {
|
|
1395
|
+
this.session.agentInstance.onPermissionRequest = async (request) => {
|
|
1396
|
+
this.session.emit("permission_request", request);
|
|
1397
|
+
this.deps.eventBus?.emit("permission:request", {
|
|
1398
|
+
sessionId: this.session.id,
|
|
1399
|
+
permission: request
|
|
1400
|
+
});
|
|
1401
|
+
if (request.description.toLowerCase().includes("openacp")) {
|
|
1402
|
+
const allowOption = request.options.find((o) => o.isAllow);
|
|
1403
|
+
if (allowOption) {
|
|
1404
|
+
log2.info(
|
|
1405
|
+
{ sessionId: this.session.id, requestId: request.id },
|
|
1406
|
+
"Auto-approving openacp command"
|
|
1407
|
+
);
|
|
1408
|
+
return allowOption.id;
|
|
1409
|
+
}
|
|
1410
|
+
}
|
|
1411
|
+
if (this.session.dangerousMode) {
|
|
1412
|
+
const allowOption = request.options.find((o) => o.isAllow);
|
|
1413
|
+
if (allowOption) {
|
|
1414
|
+
log2.info(
|
|
1415
|
+
{ sessionId: this.session.id, requestId: request.id, optionId: allowOption.id },
|
|
1416
|
+
"Dangerous mode: auto-approving permission"
|
|
1417
|
+
);
|
|
1418
|
+
return allowOption.id;
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
const promise = this.session.permissionGate.setPending(request);
|
|
1422
|
+
await this.adapter.sendPermissionRequest(this.session.id, request);
|
|
1423
|
+
return promise;
|
|
1424
|
+
};
|
|
1425
|
+
}
|
|
1426
|
+
wireLifecycle() {
|
|
1427
|
+
this.statusChangeHandler = (from, to) => {
|
|
1428
|
+
this.deps.sessionManager.patchRecord(this.session.id, {
|
|
1429
|
+
status: to,
|
|
1430
|
+
lastActiveAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1431
|
+
});
|
|
1432
|
+
this.deps.eventBus?.emit("session:updated", {
|
|
1433
|
+
sessionId: this.session.id,
|
|
1434
|
+
status: to
|
|
1435
|
+
});
|
|
1436
|
+
if (to === "finished" || to === "cancelled") {
|
|
1437
|
+
queueMicrotask(() => this.disconnect());
|
|
1438
|
+
}
|
|
1439
|
+
};
|
|
1440
|
+
this.session.on("status_change", this.statusChangeHandler);
|
|
1441
|
+
this.namedHandler = (name) => {
|
|
1442
|
+
this.deps.sessionManager.patchRecord(this.session.id, { name });
|
|
1443
|
+
this.deps.eventBus?.emit("session:updated", {
|
|
1444
|
+
sessionId: this.session.id,
|
|
1445
|
+
name
|
|
1446
|
+
});
|
|
1447
|
+
this.adapter.renameSessionThread(this.session.id, name);
|
|
1448
|
+
};
|
|
1449
|
+
this.session.on("named", this.namedHandler);
|
|
1450
|
+
}
|
|
1451
|
+
};
|
|
1452
|
+
|
|
1453
|
+
// src/core/notification.ts
|
|
1454
|
+
var NotificationManager = class {
|
|
1455
|
+
constructor(adapters) {
|
|
1456
|
+
this.adapters = adapters;
|
|
1457
|
+
}
|
|
1458
|
+
async notify(channelId, notification) {
|
|
1459
|
+
const adapter = this.adapters.get(channelId);
|
|
1460
|
+
if (adapter) {
|
|
1461
|
+
await adapter.sendNotification(notification);
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
async notifyAll(notification) {
|
|
1465
|
+
for (const adapter of this.adapters.values()) {
|
|
1466
|
+
await adapter.sendNotification(notification);
|
|
1467
|
+
}
|
|
1468
|
+
}
|
|
1469
|
+
};
|
|
1470
|
+
|
|
1471
|
+
// src/tunnel/extract-file-info.ts
|
|
1472
|
+
function extractFileInfo(name, kind, content, rawInput, meta) {
|
|
1473
|
+
if (kind && !["read", "edit", "write"].includes(kind)) return null;
|
|
1474
|
+
let info = null;
|
|
1475
|
+
if (meta) {
|
|
1476
|
+
const m = meta;
|
|
1477
|
+
const claudeCode = m?.claudeCode;
|
|
1478
|
+
const tr = claudeCode?.toolResponse;
|
|
1479
|
+
const file = tr?.file;
|
|
1480
|
+
if (typeof file?.filePath === "string" && typeof file?.content === "string") {
|
|
1481
|
+
info = { filePath: file.filePath, content: file.content };
|
|
1482
|
+
}
|
|
1483
|
+
if (!info && typeof tr?.filePath === "string" && typeof tr?.content === "string") {
|
|
1484
|
+
info = { filePath: tr.filePath, content: tr.content };
|
|
1485
|
+
}
|
|
1486
|
+
}
|
|
1487
|
+
if (!info && rawInput && typeof rawInput === "object") {
|
|
1488
|
+
const ri = rawInput;
|
|
1489
|
+
const filePath = ri?.file_path || ri?.filePath || ri?.path;
|
|
1490
|
+
if (typeof filePath === "string") {
|
|
1491
|
+
const parsed = content ? parseContent(content) : null;
|
|
1492
|
+
const riContent = typeof ri?.content === "string" ? ri.content : void 0;
|
|
1493
|
+
info = { filePath, content: parsed?.content || riContent, oldContent: parsed?.oldContent };
|
|
1494
|
+
}
|
|
1495
|
+
}
|
|
1496
|
+
if (!info && content) {
|
|
1497
|
+
info = parseContent(content);
|
|
1498
|
+
}
|
|
1499
|
+
if (!info) return null;
|
|
1500
|
+
if (!info.filePath) {
|
|
1501
|
+
const pathMatch = name.match(/(?:Read|Edit|Write|View)\s+(.+)/i);
|
|
1502
|
+
if (pathMatch) info.filePath = pathMatch[1].trim();
|
|
1503
|
+
}
|
|
1504
|
+
if (!info.filePath || !info.content) return null;
|
|
1505
|
+
return info;
|
|
1506
|
+
}
|
|
1507
|
+
function parseContent(content) {
|
|
1508
|
+
if (typeof content === "string") {
|
|
1509
|
+
return { content };
|
|
1510
|
+
}
|
|
1511
|
+
if (Array.isArray(content)) {
|
|
1512
|
+
for (const block of content) {
|
|
1513
|
+
const result = parseContent(block);
|
|
1514
|
+
if (result?.content || result?.filePath) return result;
|
|
1515
|
+
}
|
|
1516
|
+
return null;
|
|
1517
|
+
}
|
|
1518
|
+
if (typeof content === "object" && content !== null) {
|
|
1519
|
+
const c = content;
|
|
1520
|
+
if (c.type === "diff" && typeof c.path === "string") {
|
|
1521
|
+
const newText = c.newText;
|
|
1522
|
+
const oldText = c.oldText;
|
|
1523
|
+
if (newText) {
|
|
1524
|
+
return {
|
|
1525
|
+
filePath: c.path,
|
|
1526
|
+
content: newText,
|
|
1527
|
+
oldContent: oldText ?? void 0
|
|
1528
|
+
};
|
|
1529
|
+
}
|
|
1530
|
+
}
|
|
1531
|
+
if (c.type === "content" && c.content) {
|
|
1532
|
+
return parseContent(c.content);
|
|
1533
|
+
}
|
|
1534
|
+
if (c.type === "text" && typeof c.text === "string") {
|
|
1535
|
+
return { content: c.text, filePath: c.filePath };
|
|
1536
|
+
}
|
|
1537
|
+
if (typeof c.text === "string") {
|
|
1538
|
+
return { content: c.text, filePath: c.filePath };
|
|
1539
|
+
}
|
|
1540
|
+
if (typeof c.file_path === "string" || typeof c.filePath === "string" || typeof c.path === "string") {
|
|
1541
|
+
const filePath = c.file_path || c.filePath || c.path;
|
|
1542
|
+
const fileContent = c.content || c.text || c.output || c.newText;
|
|
1543
|
+
if (typeof fileContent === "string") {
|
|
1544
|
+
return {
|
|
1545
|
+
filePath,
|
|
1546
|
+
content: fileContent,
|
|
1547
|
+
oldContent: c.old_content || c.oldText
|
|
1548
|
+
};
|
|
1549
|
+
}
|
|
1550
|
+
}
|
|
1551
|
+
if (c.input) {
|
|
1552
|
+
const result = parseContent(c.input);
|
|
1553
|
+
if (result) return result;
|
|
1554
|
+
}
|
|
1555
|
+
if (c.output) {
|
|
1556
|
+
const result = parseContent(c.output);
|
|
1557
|
+
if (result) return result;
|
|
1558
|
+
}
|
|
1559
|
+
}
|
|
1560
|
+
return null;
|
|
1561
|
+
}
|
|
1562
|
+
|
|
1563
|
+
// src/core/message-transformer.ts
|
|
1564
|
+
var log3 = createChildLogger({ module: "message-transformer" });
|
|
1565
|
+
var MessageTransformer = class {
|
|
1566
|
+
constructor(tunnelService) {
|
|
1567
|
+
this.tunnelService = tunnelService;
|
|
1568
|
+
}
|
|
1569
|
+
transform(event, sessionContext) {
|
|
1570
|
+
switch (event.type) {
|
|
1571
|
+
case "text":
|
|
1572
|
+
return { type: "text", text: event.content };
|
|
1573
|
+
case "thought":
|
|
1574
|
+
return { type: "thought", text: event.content };
|
|
1575
|
+
case "tool_call": {
|
|
1576
|
+
const metadata = {
|
|
1577
|
+
id: event.id,
|
|
1578
|
+
name: event.name,
|
|
1579
|
+
kind: event.kind,
|
|
1580
|
+
status: event.status,
|
|
1581
|
+
content: event.content,
|
|
1582
|
+
locations: event.locations
|
|
1583
|
+
};
|
|
1584
|
+
this.enrichWithViewerLinks(event, metadata, sessionContext);
|
|
1585
|
+
return { type: "tool_call", text: event.name, metadata };
|
|
1586
|
+
}
|
|
1587
|
+
case "tool_update": {
|
|
1588
|
+
const metadata = {
|
|
1589
|
+
id: event.id,
|
|
1590
|
+
name: event.name,
|
|
1591
|
+
kind: event.kind,
|
|
1592
|
+
status: event.status,
|
|
1593
|
+
content: event.content
|
|
1594
|
+
};
|
|
1595
|
+
this.enrichWithViewerLinks(event, metadata, sessionContext);
|
|
1596
|
+
return { type: "tool_update", text: "", metadata };
|
|
1597
|
+
}
|
|
1598
|
+
case "plan":
|
|
1599
|
+
return {
|
|
1600
|
+
type: "plan",
|
|
1601
|
+
text: "",
|
|
1602
|
+
metadata: { entries: event.entries }
|
|
1603
|
+
};
|
|
1604
|
+
case "usage":
|
|
1605
|
+
return {
|
|
1606
|
+
type: "usage",
|
|
1607
|
+
text: "",
|
|
1608
|
+
metadata: {
|
|
1609
|
+
tokensUsed: event.tokensUsed,
|
|
1610
|
+
contextSize: event.contextSize,
|
|
1611
|
+
cost: event.cost
|
|
1612
|
+
}
|
|
1613
|
+
};
|
|
1614
|
+
case "session_end":
|
|
1615
|
+
return { type: "session_end", text: `Done (${event.reason})` };
|
|
1616
|
+
case "error":
|
|
1617
|
+
return { type: "error", text: event.message };
|
|
1618
|
+
case "system_message":
|
|
1619
|
+
return { type: "system_message", text: event.message };
|
|
1620
|
+
default:
|
|
1621
|
+
return { type: "text", text: "" };
|
|
1622
|
+
}
|
|
1623
|
+
}
|
|
1624
|
+
enrichWithViewerLinks(event, metadata, sessionContext) {
|
|
1625
|
+
if (!this.tunnelService || !sessionContext) return;
|
|
1626
|
+
const name = "name" in event ? event.name || "" : "";
|
|
1627
|
+
const kind = "kind" in event ? event.kind : void 0;
|
|
1628
|
+
log3.debug(
|
|
1629
|
+
{ name, kind, status: event.status, hasContent: !!event.content },
|
|
1630
|
+
"enrichWithViewerLinks: inspecting event"
|
|
1631
|
+
);
|
|
1632
|
+
const fileInfo = extractFileInfo(
|
|
1633
|
+
name,
|
|
1634
|
+
kind,
|
|
1635
|
+
event.content,
|
|
1636
|
+
event.rawInput,
|
|
1637
|
+
event.meta
|
|
1638
|
+
);
|
|
1639
|
+
if (!fileInfo) return;
|
|
1640
|
+
log3.info(
|
|
1641
|
+
{
|
|
1642
|
+
name,
|
|
1643
|
+
kind,
|
|
1644
|
+
filePath: fileInfo.filePath,
|
|
1645
|
+
hasOldContent: !!fileInfo.oldContent
|
|
1646
|
+
},
|
|
1647
|
+
"enrichWithViewerLinks: extracted file info"
|
|
1648
|
+
);
|
|
1649
|
+
const store = this.tunnelService.getStore();
|
|
1650
|
+
const viewerLinks = {};
|
|
1651
|
+
if (fileInfo.oldContent) {
|
|
1652
|
+
const id2 = store.storeDiff(
|
|
1653
|
+
sessionContext.id,
|
|
1654
|
+
fileInfo.filePath,
|
|
1655
|
+
fileInfo.oldContent,
|
|
1656
|
+
fileInfo.content,
|
|
1657
|
+
sessionContext.workingDirectory
|
|
1658
|
+
);
|
|
1659
|
+
if (id2) viewerLinks.diff = this.tunnelService.diffUrl(id2);
|
|
1660
|
+
}
|
|
1661
|
+
const id = store.storeFile(
|
|
1662
|
+
sessionContext.id,
|
|
1663
|
+
fileInfo.filePath,
|
|
1664
|
+
fileInfo.content,
|
|
1665
|
+
sessionContext.workingDirectory
|
|
1666
|
+
);
|
|
1667
|
+
if (id) viewerLinks.file = this.tunnelService.fileUrl(id);
|
|
1668
|
+
if (Object.keys(viewerLinks).length > 0) {
|
|
1669
|
+
metadata.viewerLinks = viewerLinks;
|
|
1670
|
+
metadata.viewerFilePath = fileInfo.filePath;
|
|
1671
|
+
}
|
|
1672
|
+
}
|
|
1673
|
+
};
|
|
1674
|
+
|
|
1675
|
+
// src/core/usage-store.ts
|
|
1676
|
+
import fs4 from "fs";
|
|
1677
|
+
import path3 from "path";
|
|
1678
|
+
var log4 = createChildLogger({ module: "usage-store" });
|
|
1679
|
+
var DEBOUNCE_MS = 2e3;
|
|
1680
|
+
var UsageStore = class {
|
|
1681
|
+
constructor(filePath, retentionDays) {
|
|
1682
|
+
this.filePath = filePath;
|
|
1683
|
+
this.retentionDays = retentionDays;
|
|
1684
|
+
this.load();
|
|
1685
|
+
this.cleanup();
|
|
1686
|
+
this.cleanupInterval = setInterval(
|
|
1687
|
+
() => this.cleanup(),
|
|
1688
|
+
24 * 60 * 60 * 1e3
|
|
1689
|
+
);
|
|
1690
|
+
this.flushHandler = () => {
|
|
1691
|
+
try {
|
|
1692
|
+
this.flushSync();
|
|
1693
|
+
} catch {
|
|
1694
|
+
}
|
|
1695
|
+
};
|
|
1696
|
+
process.on("SIGTERM", this.flushHandler);
|
|
1697
|
+
process.on("SIGINT", this.flushHandler);
|
|
1698
|
+
process.on("exit", this.flushHandler);
|
|
1699
|
+
}
|
|
1700
|
+
records = [];
|
|
1701
|
+
debounceTimer = null;
|
|
1702
|
+
cleanupInterval = null;
|
|
1703
|
+
flushHandler = null;
|
|
1704
|
+
append(record) {
|
|
1705
|
+
this.records.push(record);
|
|
1706
|
+
this.scheduleDiskWrite();
|
|
1707
|
+
}
|
|
1708
|
+
query(period) {
|
|
1709
|
+
const cutoff = this.getCutoff(period);
|
|
1710
|
+
const filtered = cutoff ? this.records.filter((r) => new Date(r.timestamp).getTime() >= cutoff) : this.records;
|
|
1711
|
+
const totalTokens = filtered.reduce((sum, r) => sum + r.tokensUsed, 0);
|
|
1712
|
+
const totalCost = filtered.reduce(
|
|
1713
|
+
(sum, r) => sum + (r.cost?.amount ?? 0),
|
|
1714
|
+
0
|
|
1715
|
+
);
|
|
1716
|
+
const sessionIds = new Set(filtered.map((r) => r.sessionId));
|
|
1717
|
+
const currency = filtered.find((r) => r.cost?.currency)?.cost?.currency ?? "USD";
|
|
1718
|
+
return {
|
|
1719
|
+
period,
|
|
1720
|
+
totalTokens,
|
|
1721
|
+
totalCost,
|
|
1722
|
+
currency,
|
|
1723
|
+
sessionCount: sessionIds.size,
|
|
1724
|
+
recordCount: filtered.length
|
|
1725
|
+
};
|
|
1726
|
+
}
|
|
1727
|
+
getMonthlyTotal() {
|
|
1728
|
+
const now = /* @__PURE__ */ new Date();
|
|
1729
|
+
const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
|
|
1730
|
+
const cutoff = startOfMonth.getTime();
|
|
1731
|
+
const filtered = this.records.filter(
|
|
1732
|
+
(r) => new Date(r.timestamp).getTime() >= cutoff
|
|
1733
|
+
);
|
|
1734
|
+
const totalCost = filtered.reduce(
|
|
1735
|
+
(sum, r) => sum + (r.cost?.amount ?? 0),
|
|
1736
|
+
0
|
|
1737
|
+
);
|
|
1738
|
+
const currency = filtered.find((r) => r.cost?.currency)?.cost?.currency ?? "USD";
|
|
1739
|
+
return { totalCost, currency };
|
|
1740
|
+
}
|
|
1741
|
+
cleanup() {
|
|
1742
|
+
const cutoff = Date.now() - this.retentionDays * 24 * 60 * 60 * 1e3;
|
|
1743
|
+
const before = this.records.length;
|
|
1744
|
+
this.records = this.records.filter(
|
|
1745
|
+
(r) => new Date(r.timestamp).getTime() >= cutoff
|
|
1746
|
+
);
|
|
1747
|
+
const removed = before - this.records.length;
|
|
1748
|
+
if (removed > 0) {
|
|
1749
|
+
log4.info({ removed }, "Cleaned up expired usage records");
|
|
1750
|
+
this.scheduleDiskWrite();
|
|
1751
|
+
}
|
|
1752
|
+
}
|
|
1753
|
+
flushSync() {
|
|
1754
|
+
if (this.debounceTimer) {
|
|
1755
|
+
clearTimeout(this.debounceTimer);
|
|
1756
|
+
this.debounceTimer = null;
|
|
1757
|
+
}
|
|
1758
|
+
const data = { version: 1, records: this.records };
|
|
1759
|
+
const dir = path3.dirname(this.filePath);
|
|
1760
|
+
if (!fs4.existsSync(dir)) fs4.mkdirSync(dir, { recursive: true });
|
|
1761
|
+
fs4.writeFileSync(this.filePath, JSON.stringify(data, null, 2));
|
|
1762
|
+
}
|
|
1763
|
+
destroy() {
|
|
1764
|
+
if (this.debounceTimer) this.flushSync();
|
|
1765
|
+
if (this.cleanupInterval) clearInterval(this.cleanupInterval);
|
|
1766
|
+
if (this.flushHandler) {
|
|
1767
|
+
process.removeListener("SIGTERM", this.flushHandler);
|
|
1768
|
+
process.removeListener("SIGINT", this.flushHandler);
|
|
1769
|
+
process.removeListener("exit", this.flushHandler);
|
|
1770
|
+
this.flushHandler = null;
|
|
1771
|
+
}
|
|
1772
|
+
}
|
|
1773
|
+
load() {
|
|
1774
|
+
if (!fs4.existsSync(this.filePath)) return;
|
|
1775
|
+
try {
|
|
1776
|
+
const raw = JSON.parse(
|
|
1777
|
+
fs4.readFileSync(this.filePath, "utf-8")
|
|
1778
|
+
);
|
|
1779
|
+
if (raw.version !== 1) {
|
|
1780
|
+
log4.warn(
|
|
1781
|
+
{ version: raw.version },
|
|
1782
|
+
"Unknown usage store version, skipping load"
|
|
1783
|
+
);
|
|
1784
|
+
return;
|
|
1785
|
+
}
|
|
1786
|
+
this.records = raw.records || [];
|
|
1787
|
+
log4.debug({ count: this.records.length }, "Loaded usage records");
|
|
1788
|
+
} catch (err) {
|
|
1789
|
+
log4.error({ err }, "Failed to load usage store, backing up corrupt file");
|
|
1790
|
+
try {
|
|
1791
|
+
fs4.copyFileSync(this.filePath, this.filePath + ".bak");
|
|
1792
|
+
} catch {
|
|
1793
|
+
}
|
|
1794
|
+
this.records = [];
|
|
1795
|
+
}
|
|
1796
|
+
}
|
|
1797
|
+
getCutoff(period) {
|
|
1798
|
+
const now = /* @__PURE__ */ new Date();
|
|
1799
|
+
switch (period) {
|
|
1800
|
+
case "today": {
|
|
1801
|
+
const start = new Date(now);
|
|
1802
|
+
start.setHours(0, 0, 0, 0);
|
|
1803
|
+
return start.getTime();
|
|
1804
|
+
}
|
|
1805
|
+
case "week":
|
|
1806
|
+
return Date.now() - 7 * 24 * 60 * 60 * 1e3;
|
|
1807
|
+
case "month": {
|
|
1808
|
+
const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
|
|
1809
|
+
return startOfMonth.getTime();
|
|
1810
|
+
}
|
|
1811
|
+
case "all":
|
|
1812
|
+
return null;
|
|
1813
|
+
}
|
|
1814
|
+
}
|
|
1815
|
+
scheduleDiskWrite() {
|
|
1816
|
+
if (this.debounceTimer) clearTimeout(this.debounceTimer);
|
|
1817
|
+
this.debounceTimer = setTimeout(() => {
|
|
1818
|
+
this.flushSync();
|
|
1819
|
+
}, DEBOUNCE_MS);
|
|
1820
|
+
}
|
|
1821
|
+
};
|
|
1822
|
+
|
|
1823
|
+
// src/core/usage-budget.ts
|
|
1824
|
+
var UsageBudget = class {
|
|
1825
|
+
constructor(store, config, now = () => /* @__PURE__ */ new Date()) {
|
|
1826
|
+
this.store = store;
|
|
1827
|
+
this.config = config;
|
|
1828
|
+
this.now = now;
|
|
1829
|
+
this.lastNotifiedMonth = this.now().getMonth();
|
|
1830
|
+
}
|
|
1831
|
+
lastNotifiedStatus = "ok";
|
|
1832
|
+
lastNotifiedMonth;
|
|
1833
|
+
check() {
|
|
1834
|
+
if (!this.config.monthlyBudget) {
|
|
1835
|
+
return { status: "ok" };
|
|
1836
|
+
}
|
|
1837
|
+
const currentMonth = this.now().getMonth();
|
|
1838
|
+
if (currentMonth !== this.lastNotifiedMonth) {
|
|
1839
|
+
this.lastNotifiedStatus = "ok";
|
|
1840
|
+
this.lastNotifiedMonth = currentMonth;
|
|
1841
|
+
}
|
|
1842
|
+
const { totalCost } = this.store.getMonthlyTotal();
|
|
1843
|
+
const budget = this.config.monthlyBudget;
|
|
1844
|
+
const threshold = this.config.warningThreshold;
|
|
1845
|
+
let status;
|
|
1846
|
+
if (totalCost >= budget) {
|
|
1847
|
+
status = "exceeded";
|
|
1848
|
+
} else if (totalCost >= threshold * budget) {
|
|
1849
|
+
status = "warning";
|
|
1850
|
+
} else {
|
|
1851
|
+
status = "ok";
|
|
1852
|
+
}
|
|
1853
|
+
let message;
|
|
1854
|
+
if (status !== "ok" && status !== this.lastNotifiedStatus) {
|
|
1855
|
+
const pct = Math.round(totalCost / budget * 100);
|
|
1856
|
+
const filled = Math.round(Math.min(totalCost / budget, 1) * 10);
|
|
1857
|
+
const bar = "\u2593".repeat(filled) + "\u2591".repeat(10 - filled);
|
|
1858
|
+
if (status === "warning") {
|
|
1859
|
+
message = `\u26A0\uFE0F <b>Budget Warning</b>
|
|
1860
|
+
Monthly usage: $${totalCost.toFixed(2)} / $${budget.toFixed(2)} (${pct}%)
|
|
1861
|
+
${bar} ${pct}%`;
|
|
1862
|
+
} else {
|
|
1863
|
+
message = `\u{1F6A8} <b>Budget Exceeded</b>
|
|
1864
|
+
Monthly usage: $${totalCost.toFixed(2)} / $${budget.toFixed(2)} (${pct}%)
|
|
1865
|
+
${bar} ${pct}%
|
|
1866
|
+
Sessions are NOT blocked \u2014 this is a warning only.`;
|
|
1867
|
+
}
|
|
1868
|
+
}
|
|
1869
|
+
this.lastNotifiedStatus = status;
|
|
1870
|
+
return { status, message };
|
|
1871
|
+
}
|
|
1872
|
+
getStatus() {
|
|
1873
|
+
const { totalCost } = this.store.getMonthlyTotal();
|
|
1874
|
+
const budget = this.config.monthlyBudget ?? 0;
|
|
1875
|
+
let status = "ok";
|
|
1876
|
+
if (budget > 0) {
|
|
1877
|
+
if (totalCost >= budget) {
|
|
1878
|
+
status = "exceeded";
|
|
1879
|
+
} else if (totalCost >= this.config.warningThreshold * budget) {
|
|
1880
|
+
status = "warning";
|
|
1881
|
+
}
|
|
1882
|
+
}
|
|
1883
|
+
const percent = budget > 0 ? Math.round(totalCost / budget * 100) : 0;
|
|
1884
|
+
return { status, used: totalCost, budget, percent };
|
|
1885
|
+
}
|
|
1886
|
+
};
|
|
1887
|
+
|
|
1888
|
+
// src/core/security-guard.ts
|
|
1889
|
+
var SecurityGuard = class {
|
|
1890
|
+
constructor(configManager, sessionManager) {
|
|
1891
|
+
this.configManager = configManager;
|
|
1892
|
+
this.sessionManager = sessionManager;
|
|
1893
|
+
}
|
|
1894
|
+
checkAccess(message) {
|
|
1895
|
+
const config = this.configManager.get();
|
|
1896
|
+
if (config.security.allowedUserIds.length > 0) {
|
|
1897
|
+
const userId = String(message.userId);
|
|
1898
|
+
if (!config.security.allowedUserIds.includes(userId)) {
|
|
1899
|
+
return { allowed: false, reason: "Unauthorized user" };
|
|
1900
|
+
}
|
|
1901
|
+
}
|
|
1902
|
+
const active = this.sessionManager.listSessions().filter((s) => s.status === "active" || s.status === "initializing");
|
|
1903
|
+
if (active.length >= config.security.maxConcurrentSessions) {
|
|
1904
|
+
return { allowed: false, reason: `Session limit reached (${config.security.maxConcurrentSessions})` };
|
|
1905
|
+
}
|
|
1906
|
+
return { allowed: true };
|
|
1907
|
+
}
|
|
1908
|
+
};
|
|
1909
|
+
|
|
1910
|
+
// src/core/session-factory.ts
|
|
1911
|
+
import { nanoid as nanoid2 } from "nanoid";
|
|
1912
|
+
var log5 = createChildLogger({ module: "session-factory" });
|
|
1913
|
+
var SessionFactory = class {
|
|
1914
|
+
constructor(agentManager, sessionManager, speechService, eventBus) {
|
|
1915
|
+
this.agentManager = agentManager;
|
|
1916
|
+
this.sessionManager = sessionManager;
|
|
1917
|
+
this.speechService = speechService;
|
|
1918
|
+
this.eventBus = eventBus;
|
|
1919
|
+
}
|
|
1920
|
+
async create(params) {
|
|
1921
|
+
const agentInstance = params.resumeAgentSessionId ? await this.agentManager.resume(
|
|
1922
|
+
params.agentName,
|
|
1923
|
+
params.workingDirectory,
|
|
1924
|
+
params.resumeAgentSessionId
|
|
1925
|
+
) : await this.agentManager.spawn(
|
|
1926
|
+
params.agentName,
|
|
1927
|
+
params.workingDirectory
|
|
1928
|
+
);
|
|
1929
|
+
const session = new Session({
|
|
1930
|
+
id: params.existingSessionId,
|
|
1931
|
+
channelId: params.channelId,
|
|
1932
|
+
agentName: params.agentName,
|
|
1933
|
+
workingDirectory: params.workingDirectory,
|
|
1934
|
+
agentInstance,
|
|
1935
|
+
speechService: this.speechService
|
|
1936
|
+
});
|
|
1937
|
+
session.agentSessionId = agentInstance.sessionId;
|
|
1938
|
+
if (params.initialName) {
|
|
1939
|
+
session.name = params.initialName;
|
|
1940
|
+
}
|
|
1941
|
+
this.sessionManager.registerSession(session);
|
|
1942
|
+
this.eventBus.emit("session:created", {
|
|
1943
|
+
sessionId: session.id,
|
|
1944
|
+
agent: session.agentName,
|
|
1945
|
+
status: session.status
|
|
1946
|
+
});
|
|
1947
|
+
return session;
|
|
1948
|
+
}
|
|
1949
|
+
wireSideEffects(session, deps) {
|
|
1950
|
+
if (deps.usageStore) {
|
|
1951
|
+
const usageStore = deps.usageStore;
|
|
1952
|
+
const usageBudget = deps.usageBudget;
|
|
1953
|
+
const notificationManager = deps.notificationManager;
|
|
1954
|
+
session.on("agent_event", (event) => {
|
|
1955
|
+
if (event.type !== "usage") return;
|
|
1956
|
+
const record = {
|
|
1957
|
+
id: nanoid2(),
|
|
1958
|
+
sessionId: session.id,
|
|
1959
|
+
agentName: session.agentName,
|
|
1960
|
+
tokensUsed: event.tokensUsed ?? 0,
|
|
1961
|
+
contextSize: event.contextSize ?? 0,
|
|
1962
|
+
cost: event.cost,
|
|
1963
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
1964
|
+
};
|
|
1965
|
+
usageStore.append(record);
|
|
1966
|
+
if (usageBudget) {
|
|
1967
|
+
const result = usageBudget.check();
|
|
1968
|
+
if (result.message) {
|
|
1969
|
+
notificationManager.notifyAll({
|
|
1970
|
+
sessionId: session.id,
|
|
1971
|
+
sessionName: session.name,
|
|
1972
|
+
type: "budget_warning",
|
|
1973
|
+
summary: result.message
|
|
1974
|
+
});
|
|
1975
|
+
}
|
|
1976
|
+
}
|
|
1977
|
+
});
|
|
1978
|
+
}
|
|
1979
|
+
session.on("status_change", (_from, to) => {
|
|
1980
|
+
if ((to === "finished" || to === "cancelled") && deps.tunnelService) {
|
|
1981
|
+
deps.tunnelService.stopBySession(session.id).then((stopped) => {
|
|
1982
|
+
for (const entry of stopped) {
|
|
1983
|
+
deps.notificationManager.notifyAll({
|
|
1984
|
+
sessionId: session.id,
|
|
1985
|
+
sessionName: session.name,
|
|
1986
|
+
type: "completed",
|
|
1987
|
+
summary: `Tunnel stopped: port ${entry.port}${entry.label ? ` (${entry.label})` : ""} \u2014 session ended`
|
|
1988
|
+
}).catch(() => {
|
|
1989
|
+
});
|
|
1990
|
+
}
|
|
1991
|
+
}).catch(() => {
|
|
1992
|
+
});
|
|
1993
|
+
}
|
|
1994
|
+
});
|
|
1995
|
+
}
|
|
1996
|
+
};
|
|
1997
|
+
|
|
1998
|
+
// src/core/event-bus.ts
|
|
1999
|
+
var EventBus = class extends TypedEmitter {
|
|
2000
|
+
};
|
|
2001
|
+
|
|
2002
|
+
// src/core/speech/speech-service.ts
|
|
2003
|
+
var SpeechService = class {
|
|
2004
|
+
constructor(config) {
|
|
2005
|
+
this.config = config;
|
|
2006
|
+
}
|
|
2007
|
+
sttProviders = /* @__PURE__ */ new Map();
|
|
2008
|
+
ttsProviders = /* @__PURE__ */ new Map();
|
|
2009
|
+
registerSTTProvider(name, provider) {
|
|
2010
|
+
this.sttProviders.set(name, provider);
|
|
2011
|
+
}
|
|
2012
|
+
registerTTSProvider(name, provider) {
|
|
2013
|
+
this.ttsProviders.set(name, provider);
|
|
2014
|
+
}
|
|
2015
|
+
isSTTAvailable() {
|
|
2016
|
+
const { provider, providers } = this.config.stt;
|
|
2017
|
+
return provider !== null && providers[provider]?.apiKey !== void 0;
|
|
2018
|
+
}
|
|
2019
|
+
isTTSAvailable() {
|
|
2020
|
+
const provider = this.config.tts.provider;
|
|
2021
|
+
return provider !== null && this.ttsProviders.has(provider);
|
|
2022
|
+
}
|
|
2023
|
+
async transcribe(audioBuffer, mimeType, options) {
|
|
2024
|
+
const providerName = this.config.stt.provider;
|
|
2025
|
+
if (!providerName || !this.config.stt.providers[providerName]?.apiKey) {
|
|
2026
|
+
throw new Error("STT not configured. Set speech.stt.provider and API key in config.");
|
|
2027
|
+
}
|
|
2028
|
+
const provider = this.sttProviders.get(providerName);
|
|
2029
|
+
if (!provider) {
|
|
2030
|
+
throw new Error(`STT provider "${providerName}" not registered. Available: ${[...this.sttProviders.keys()].join(", ") || "none"}`);
|
|
2031
|
+
}
|
|
2032
|
+
return provider.transcribe(audioBuffer, mimeType, options);
|
|
2033
|
+
}
|
|
2034
|
+
async synthesize(text, options) {
|
|
2035
|
+
const providerName = this.config.tts.provider;
|
|
2036
|
+
if (!providerName) {
|
|
2037
|
+
throw new Error("TTS not configured. Set speech.tts.provider in config.");
|
|
2038
|
+
}
|
|
2039
|
+
const provider = this.ttsProviders.get(providerName);
|
|
2040
|
+
if (!provider) {
|
|
2041
|
+
throw new Error(`TTS provider "${providerName}" not registered. Available: ${[...this.ttsProviders.keys()].join(", ") || "none"}`);
|
|
2042
|
+
}
|
|
2043
|
+
return provider.synthesize(text, options);
|
|
2044
|
+
}
|
|
2045
|
+
updateConfig(config) {
|
|
2046
|
+
this.config = config;
|
|
2047
|
+
}
|
|
2048
|
+
};
|
|
2049
|
+
|
|
2050
|
+
// src/core/speech/providers/groq.ts
|
|
2051
|
+
var GROQ_API_URL = "https://api.groq.com/openai/v1/audio/transcriptions";
|
|
2052
|
+
var GroqSTT = class {
|
|
2053
|
+
constructor(apiKey, defaultModel = "whisper-large-v3-turbo") {
|
|
2054
|
+
this.apiKey = apiKey;
|
|
2055
|
+
this.defaultModel = defaultModel;
|
|
2056
|
+
}
|
|
2057
|
+
name = "groq";
|
|
2058
|
+
async transcribe(audioBuffer, mimeType, options) {
|
|
2059
|
+
const ext = mimeToExt(mimeType);
|
|
2060
|
+
const form = new FormData();
|
|
2061
|
+
form.append("file", new Blob([new Uint8Array(audioBuffer)], { type: mimeType }), `audio${ext}`);
|
|
2062
|
+
form.append("model", options?.model || this.defaultModel);
|
|
2063
|
+
form.append("response_format", "verbose_json");
|
|
2064
|
+
if (options?.language) {
|
|
2065
|
+
form.append("language", options.language);
|
|
2066
|
+
}
|
|
2067
|
+
const resp = await fetch(GROQ_API_URL, {
|
|
2068
|
+
method: "POST",
|
|
2069
|
+
headers: { Authorization: `Bearer ${this.apiKey}` },
|
|
2070
|
+
body: form
|
|
2071
|
+
});
|
|
2072
|
+
if (!resp.ok) {
|
|
2073
|
+
const body = await resp.text();
|
|
2074
|
+
if (resp.status === 401) {
|
|
2075
|
+
throw new Error("Invalid Groq API key. Check your key at console.groq.com.");
|
|
2076
|
+
}
|
|
2077
|
+
if (resp.status === 413) {
|
|
2078
|
+
throw new Error("Audio file too large for Groq API (max 25MB).");
|
|
2079
|
+
}
|
|
2080
|
+
if (resp.status === 429) {
|
|
2081
|
+
throw new Error("Groq rate limit exceeded. Free tier: 28,800 seconds/day. Try again later.");
|
|
2082
|
+
}
|
|
2083
|
+
throw new Error(`Groq STT error (${resp.status}): ${body}`);
|
|
2084
|
+
}
|
|
2085
|
+
const data = await resp.json();
|
|
2086
|
+
return {
|
|
2087
|
+
text: data.text,
|
|
2088
|
+
language: data.language,
|
|
2089
|
+
duration: data.duration
|
|
2090
|
+
};
|
|
2091
|
+
}
|
|
2092
|
+
};
|
|
2093
|
+
function mimeToExt(mimeType) {
|
|
2094
|
+
const map = {
|
|
2095
|
+
"audio/ogg": ".ogg",
|
|
2096
|
+
"audio/wav": ".wav",
|
|
2097
|
+
"audio/mpeg": ".mp3",
|
|
2098
|
+
"audio/mp4": ".m4a",
|
|
2099
|
+
"audio/webm": ".webm",
|
|
2100
|
+
"audio/flac": ".flac"
|
|
2101
|
+
};
|
|
2102
|
+
return map[mimeType] || ".bin";
|
|
2103
|
+
}
|
|
2104
|
+
|
|
2105
|
+
// src/core/speech/providers/edge-tts.ts
|
|
2106
|
+
var DEFAULT_VOICE = "en-US-AriaNeural";
|
|
2107
|
+
var EdgeTTS = class {
|
|
2108
|
+
name = "edge-tts";
|
|
2109
|
+
voice;
|
|
2110
|
+
constructor(voice) {
|
|
2111
|
+
this.voice = voice || DEFAULT_VOICE;
|
|
2112
|
+
}
|
|
2113
|
+
async synthesize(text, options) {
|
|
2114
|
+
const { MsEdgeTTS, OUTPUT_FORMAT } = await import("msedge-tts");
|
|
2115
|
+
const tts = new MsEdgeTTS();
|
|
2116
|
+
const voice = options?.voice || this.voice;
|
|
2117
|
+
const format = OUTPUT_FORMAT.AUDIO_24KHZ_48KBITRATE_MONO_MP3;
|
|
2118
|
+
await tts.setMetadata(voice, format);
|
|
2119
|
+
const { audioStream } = tts.toStream(text);
|
|
2120
|
+
const chunks = [];
|
|
2121
|
+
for await (const chunk of audioStream) {
|
|
2122
|
+
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
2123
|
+
}
|
|
2124
|
+
tts.close();
|
|
2125
|
+
return {
|
|
2126
|
+
audioBuffer: Buffer.concat(chunks),
|
|
2127
|
+
mimeType: "audio/mpeg"
|
|
2128
|
+
};
|
|
2129
|
+
}
|
|
2130
|
+
};
|
|
2131
|
+
|
|
2132
|
+
// src/core/core.ts
|
|
2133
|
+
import path5 from "path";
|
|
2134
|
+
import os from "os";
|
|
2135
|
+
|
|
2136
|
+
// src/core/session-store.ts
|
|
2137
|
+
import fs5 from "fs";
|
|
2138
|
+
import path4 from "path";
|
|
2139
|
+
var log6 = createChildLogger({ module: "session-store" });
|
|
2140
|
+
var DEBOUNCE_MS2 = 2e3;
|
|
2141
|
+
var JsonFileSessionStore = class {
|
|
2142
|
+
records = /* @__PURE__ */ new Map();
|
|
2143
|
+
filePath;
|
|
2144
|
+
ttlDays;
|
|
2145
|
+
debounceTimer = null;
|
|
2146
|
+
cleanupInterval = null;
|
|
2147
|
+
flushHandler = null;
|
|
2148
|
+
constructor(filePath, ttlDays) {
|
|
2149
|
+
this.filePath = filePath;
|
|
2150
|
+
this.ttlDays = ttlDays;
|
|
2151
|
+
this.load();
|
|
2152
|
+
this.cleanup();
|
|
2153
|
+
this.cleanupInterval = setInterval(
|
|
2154
|
+
() => this.cleanup(),
|
|
2155
|
+
24 * 60 * 60 * 1e3
|
|
2156
|
+
);
|
|
2157
|
+
this.flushHandler = () => this.flushSync();
|
|
2158
|
+
process.on("SIGTERM", this.flushHandler);
|
|
2159
|
+
process.on("SIGINT", this.flushHandler);
|
|
2160
|
+
process.on("exit", this.flushHandler);
|
|
2161
|
+
}
|
|
2162
|
+
async save(record) {
|
|
2163
|
+
this.records.set(record.sessionId, { ...record });
|
|
2164
|
+
this.scheduleDiskWrite();
|
|
2165
|
+
}
|
|
2166
|
+
get(sessionId) {
|
|
2167
|
+
return this.records.get(sessionId);
|
|
2168
|
+
}
|
|
2169
|
+
findByPlatform(channelId, predicate) {
|
|
2170
|
+
for (const record of this.records.values()) {
|
|
2171
|
+
if (record.channelId === channelId && predicate(record.platform)) {
|
|
2172
|
+
return record;
|
|
2173
|
+
}
|
|
2174
|
+
}
|
|
2175
|
+
return void 0;
|
|
2176
|
+
}
|
|
2177
|
+
findByAgentSessionId(agentSessionId) {
|
|
2178
|
+
return [...this.records.values()].find(
|
|
2179
|
+
(r) => r.agentSessionId === agentSessionId || r.originalAgentSessionId === agentSessionId
|
|
2180
|
+
);
|
|
2181
|
+
}
|
|
2182
|
+
list(channelId) {
|
|
2183
|
+
const all = [...this.records.values()];
|
|
2184
|
+
if (channelId) return all.filter((r) => r.channelId === channelId);
|
|
2185
|
+
return all;
|
|
2186
|
+
}
|
|
2187
|
+
async remove(sessionId) {
|
|
2188
|
+
this.records.delete(sessionId);
|
|
2189
|
+
this.scheduleDiskWrite();
|
|
2190
|
+
}
|
|
2191
|
+
flushSync() {
|
|
2192
|
+
if (this.debounceTimer) {
|
|
2193
|
+
clearTimeout(this.debounceTimer);
|
|
2194
|
+
this.debounceTimer = null;
|
|
2195
|
+
}
|
|
2196
|
+
const data = {
|
|
2197
|
+
version: 1,
|
|
2198
|
+
sessions: Object.fromEntries(this.records)
|
|
2199
|
+
};
|
|
2200
|
+
const dir = path4.dirname(this.filePath);
|
|
2201
|
+
if (!fs5.existsSync(dir)) fs5.mkdirSync(dir, { recursive: true });
|
|
2202
|
+
fs5.writeFileSync(this.filePath, JSON.stringify(data, null, 2));
|
|
2203
|
+
}
|
|
2204
|
+
destroy() {
|
|
2205
|
+
if (this.debounceTimer) clearTimeout(this.debounceTimer);
|
|
2206
|
+
if (this.cleanupInterval) clearInterval(this.cleanupInterval);
|
|
2207
|
+
if (this.flushHandler) {
|
|
2208
|
+
process.removeListener("SIGTERM", this.flushHandler);
|
|
2209
|
+
process.removeListener("SIGINT", this.flushHandler);
|
|
2210
|
+
process.removeListener("exit", this.flushHandler);
|
|
2211
|
+
this.flushHandler = null;
|
|
2212
|
+
}
|
|
2213
|
+
}
|
|
2214
|
+
load() {
|
|
2215
|
+
if (!fs5.existsSync(this.filePath)) return;
|
|
2216
|
+
try {
|
|
2217
|
+
const raw = JSON.parse(
|
|
2218
|
+
fs5.readFileSync(this.filePath, "utf-8")
|
|
2219
|
+
);
|
|
2220
|
+
if (raw.version !== 1) {
|
|
2221
|
+
log6.warn(
|
|
2222
|
+
{ version: raw.version },
|
|
2223
|
+
"Unknown session store version, skipping load"
|
|
2224
|
+
);
|
|
2225
|
+
return;
|
|
2226
|
+
}
|
|
2227
|
+
for (const [id, record] of Object.entries(raw.sessions)) {
|
|
2228
|
+
this.records.set(id, record);
|
|
2229
|
+
}
|
|
2230
|
+
log6.debug({ count: this.records.size }, "Loaded session records");
|
|
2231
|
+
} catch (err) {
|
|
2232
|
+
log6.error({ err }, "Failed to load session store");
|
|
2233
|
+
}
|
|
2234
|
+
}
|
|
2235
|
+
cleanup() {
|
|
2236
|
+
const cutoff = Date.now() - this.ttlDays * 24 * 60 * 60 * 1e3;
|
|
2237
|
+
let removed = 0;
|
|
2238
|
+
for (const [id, record] of this.records) {
|
|
2239
|
+
if (record.status === "active" || record.status === "initializing")
|
|
2240
|
+
continue;
|
|
2241
|
+
const lastActive = new Date(record.lastActiveAt).getTime();
|
|
2242
|
+
if (lastActive < cutoff) {
|
|
2243
|
+
this.records.delete(id);
|
|
2244
|
+
removed++;
|
|
2245
|
+
}
|
|
2246
|
+
}
|
|
2247
|
+
if (removed > 0) {
|
|
2248
|
+
log6.info({ removed }, "Cleaned up expired session records");
|
|
2249
|
+
this.scheduleDiskWrite();
|
|
2250
|
+
}
|
|
2251
|
+
}
|
|
2252
|
+
scheduleDiskWrite() {
|
|
2253
|
+
if (this.debounceTimer) clearTimeout(this.debounceTimer);
|
|
2254
|
+
this.debounceTimer = setTimeout(() => {
|
|
2255
|
+
this.flushSync();
|
|
2256
|
+
}, DEBOUNCE_MS2);
|
|
2257
|
+
}
|
|
2258
|
+
};
|
|
2259
|
+
|
|
2260
|
+
// src/core/core.ts
|
|
2261
|
+
var log7 = createChildLogger({ module: "core" });
|
|
2262
|
+
var OpenACPCore = class {
|
|
2263
|
+
configManager;
|
|
2264
|
+
agentCatalog;
|
|
2265
|
+
agentManager;
|
|
2266
|
+
sessionManager;
|
|
2267
|
+
notificationManager;
|
|
2268
|
+
messageTransformer;
|
|
2269
|
+
fileService;
|
|
2270
|
+
speechService;
|
|
2271
|
+
securityGuard;
|
|
2272
|
+
adapters = /* @__PURE__ */ new Map();
|
|
2273
|
+
/** Set by main.ts — triggers graceful shutdown with restart exit code */
|
|
2274
|
+
requestRestart = null;
|
|
2275
|
+
_tunnelService;
|
|
2276
|
+
sessionStore = null;
|
|
2277
|
+
resumeLocks = /* @__PURE__ */ new Map();
|
|
2278
|
+
eventBus;
|
|
2279
|
+
sessionFactory;
|
|
2280
|
+
usageStore = null;
|
|
2281
|
+
usageBudget = null;
|
|
2282
|
+
constructor(configManager) {
|
|
2283
|
+
this.configManager = configManager;
|
|
2284
|
+
const config = configManager.get();
|
|
2285
|
+
this.agentCatalog = new AgentCatalog();
|
|
2286
|
+
this.agentCatalog.load();
|
|
2287
|
+
this.agentManager = new AgentManager(this.agentCatalog);
|
|
2288
|
+
const storePath = path5.join(os.homedir(), ".openacp", "sessions.json");
|
|
2289
|
+
this.sessionStore = new JsonFileSessionStore(
|
|
2290
|
+
storePath,
|
|
2291
|
+
config.sessionStore.ttlDays
|
|
2292
|
+
);
|
|
2293
|
+
this.sessionManager = new SessionManager(this.sessionStore);
|
|
2294
|
+
this.securityGuard = new SecurityGuard(configManager, this.sessionManager);
|
|
2295
|
+
this.notificationManager = new NotificationManager(this.adapters);
|
|
2296
|
+
const usageConfig = config.usage;
|
|
2297
|
+
if (usageConfig.enabled) {
|
|
2298
|
+
const usagePath = path5.join(os.homedir(), ".openacp", "usage.json");
|
|
2299
|
+
this.usageStore = new UsageStore(usagePath, usageConfig.retentionDays);
|
|
2300
|
+
this.usageBudget = new UsageBudget(this.usageStore, usageConfig);
|
|
2301
|
+
}
|
|
2302
|
+
this.messageTransformer = new MessageTransformer();
|
|
2303
|
+
this.eventBus = new EventBus();
|
|
2304
|
+
this.sessionManager.setEventBus(this.eventBus);
|
|
2305
|
+
this.fileService = new FileService(
|
|
2306
|
+
path5.join(os.homedir(), ".openacp", "files")
|
|
2307
|
+
);
|
|
2308
|
+
const speechConfig = config.speech ?? {
|
|
2309
|
+
stt: { provider: null, providers: {} },
|
|
2310
|
+
tts: { provider: "edge-tts", providers: {} }
|
|
2311
|
+
};
|
|
2312
|
+
if (speechConfig.tts.provider == null) {
|
|
2313
|
+
speechConfig.tts.provider = "edge-tts";
|
|
2314
|
+
}
|
|
2315
|
+
this.speechService = new SpeechService(speechConfig);
|
|
2316
|
+
const groqConfig = speechConfig.stt?.providers?.groq;
|
|
2317
|
+
if (groqConfig?.apiKey) {
|
|
2318
|
+
this.speechService.registerSTTProvider(
|
|
2319
|
+
"groq",
|
|
2320
|
+
new GroqSTT(groqConfig.apiKey, groqConfig.model)
|
|
2321
|
+
);
|
|
2322
|
+
}
|
|
2323
|
+
{
|
|
2324
|
+
const edgeConfig = speechConfig.tts?.providers?.["edge-tts"];
|
|
2325
|
+
const voice = edgeConfig?.voice;
|
|
2326
|
+
this.speechService.registerTTSProvider("edge-tts", new EdgeTTS(voice));
|
|
2327
|
+
}
|
|
2328
|
+
this.sessionFactory = new SessionFactory(
|
|
2329
|
+
this.agentManager,
|
|
2330
|
+
this.sessionManager,
|
|
2331
|
+
this.speechService,
|
|
2332
|
+
this.eventBus
|
|
2333
|
+
);
|
|
2334
|
+
this.configManager.on(
|
|
2335
|
+
"config:changed",
|
|
2336
|
+
async ({ path: configPath, value }) => {
|
|
2337
|
+
if (configPath === "logging.level" && typeof value === "string") {
|
|
2338
|
+
const { setLogLevel: setLogLevel2 } = await import("./log-RCVBXLTN.js");
|
|
2339
|
+
setLogLevel2(value);
|
|
2340
|
+
log7.info({ level: value }, "Log level changed at runtime");
|
|
2341
|
+
}
|
|
2342
|
+
if (configPath.startsWith("speech.")) {
|
|
2343
|
+
const newConfig = this.configManager.get();
|
|
2344
|
+
const newSpeechConfig = newConfig.speech ?? {
|
|
2345
|
+
stt: { provider: null, providers: {} },
|
|
2346
|
+
tts: { provider: null, providers: {} }
|
|
2347
|
+
};
|
|
2348
|
+
this.speechService.updateConfig(newSpeechConfig);
|
|
2349
|
+
const groqCfg = newSpeechConfig.stt?.providers?.groq;
|
|
2350
|
+
if (groqCfg?.apiKey) {
|
|
2351
|
+
this.speechService.registerSTTProvider(
|
|
2352
|
+
"groq",
|
|
2353
|
+
new GroqSTT(groqCfg.apiKey, groqCfg.model)
|
|
2354
|
+
);
|
|
2355
|
+
}
|
|
2356
|
+
{
|
|
2357
|
+
const edgeConfig = newSpeechConfig.tts?.providers?.["edge-tts"];
|
|
2358
|
+
const voice = edgeConfig?.voice;
|
|
2359
|
+
this.speechService.registerTTSProvider("edge-tts", new EdgeTTS(voice));
|
|
2360
|
+
}
|
|
2361
|
+
log7.info("Speech service config updated at runtime");
|
|
2362
|
+
}
|
|
2363
|
+
}
|
|
2364
|
+
);
|
|
2365
|
+
}
|
|
2366
|
+
get tunnelService() {
|
|
2367
|
+
return this._tunnelService;
|
|
2368
|
+
}
|
|
2369
|
+
set tunnelService(service) {
|
|
2370
|
+
this._tunnelService = service;
|
|
2371
|
+
this.messageTransformer = new MessageTransformer(service);
|
|
2372
|
+
}
|
|
2373
|
+
registerAdapter(name, adapter) {
|
|
2374
|
+
this.adapters.set(name, adapter);
|
|
2375
|
+
}
|
|
2376
|
+
async start() {
|
|
2377
|
+
this.agentCatalog.refreshRegistryIfStale().catch((err) => {
|
|
2378
|
+
log7.warn({ err }, "Background registry refresh failed");
|
|
2379
|
+
});
|
|
2380
|
+
for (const adapter of this.adapters.values()) {
|
|
2381
|
+
await adapter.start();
|
|
2382
|
+
}
|
|
2383
|
+
}
|
|
2384
|
+
async stop() {
|
|
2385
|
+
try {
|
|
2386
|
+
await this.notificationManager.notifyAll({
|
|
2387
|
+
sessionId: "system",
|
|
2388
|
+
type: "error",
|
|
2389
|
+
summary: "OpenACP is shutting down"
|
|
2390
|
+
});
|
|
2391
|
+
} catch {
|
|
2392
|
+
}
|
|
2393
|
+
await this.sessionManager.destroyAll();
|
|
2394
|
+
for (const adapter of this.adapters.values()) {
|
|
2395
|
+
await adapter.stop();
|
|
2396
|
+
}
|
|
2397
|
+
if (this.usageStore) {
|
|
2398
|
+
this.usageStore.destroy();
|
|
2399
|
+
}
|
|
2400
|
+
}
|
|
2401
|
+
// --- Archive ---
|
|
2402
|
+
async archiveSession(sessionId) {
|
|
2403
|
+
const session = this.sessionManager.getSession(sessionId);
|
|
2404
|
+
if (!session) return { ok: false, error: "Session not found" };
|
|
2405
|
+
if (session.status === "initializing")
|
|
2406
|
+
return { ok: false, error: "Session is still initializing" };
|
|
2407
|
+
if (session.status !== "active")
|
|
2408
|
+
return { ok: false, error: `Session is ${session.status}` };
|
|
2409
|
+
const adapter = this.adapters.get(session.channelId);
|
|
2410
|
+
if (!adapter) return { ok: false, error: "Adapter not found for session" };
|
|
2411
|
+
try {
|
|
2412
|
+
const result = await adapter.archiveSessionTopic(session.id);
|
|
2413
|
+
if (!result)
|
|
2414
|
+
return { ok: false, error: "Adapter does not support archiving" };
|
|
2415
|
+
return { ok: true, newThreadId: result.newThreadId };
|
|
2416
|
+
} catch (err) {
|
|
2417
|
+
return { ok: false, error: err.message };
|
|
2418
|
+
}
|
|
2419
|
+
}
|
|
2420
|
+
// --- Message Routing ---
|
|
2421
|
+
async handleMessage(message) {
|
|
2422
|
+
log7.debug(
|
|
2423
|
+
{
|
|
2424
|
+
channelId: message.channelId,
|
|
2425
|
+
threadId: message.threadId,
|
|
2426
|
+
userId: message.userId
|
|
2427
|
+
},
|
|
2428
|
+
"Incoming message"
|
|
2429
|
+
);
|
|
2430
|
+
const access = this.securityGuard.checkAccess(message);
|
|
2431
|
+
if (!access.allowed) {
|
|
2432
|
+
log7.warn({ userId: message.userId, reason: access.reason }, "Access denied");
|
|
2433
|
+
if (access.reason.includes("Session limit")) {
|
|
2434
|
+
const adapter = this.adapters.get(message.channelId);
|
|
2435
|
+
if (adapter) {
|
|
2436
|
+
await adapter.sendMessage(message.threadId, {
|
|
2437
|
+
type: "error",
|
|
2438
|
+
text: `\u26A0\uFE0F ${access.reason}. Please cancel existing sessions with /cancel before starting new ones.`
|
|
2439
|
+
});
|
|
2440
|
+
}
|
|
2441
|
+
}
|
|
2442
|
+
return;
|
|
2443
|
+
}
|
|
2444
|
+
let session = this.sessionManager.getSessionByThread(
|
|
2445
|
+
message.channelId,
|
|
2446
|
+
message.threadId
|
|
2447
|
+
);
|
|
2448
|
+
if (!session) {
|
|
2449
|
+
session = await this.lazyResume(message) ?? void 0;
|
|
2450
|
+
}
|
|
2451
|
+
if (!session) {
|
|
2452
|
+
log7.warn(
|
|
2453
|
+
{ channelId: message.channelId, threadId: message.threadId },
|
|
2454
|
+
"No session found for thread (in-memory miss + lazy resume returned null)"
|
|
2455
|
+
);
|
|
2456
|
+
return;
|
|
2457
|
+
}
|
|
2458
|
+
this.sessionManager.patchRecord(session.id, {
|
|
2459
|
+
lastActiveAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
2460
|
+
});
|
|
2461
|
+
await session.enqueuePrompt(message.text, message.attachments);
|
|
2462
|
+
}
|
|
2463
|
+
// --- Unified Session Creation Pipeline ---
|
|
2464
|
+
async createSession(params) {
|
|
2465
|
+
const session = await this.sessionFactory.create(params);
|
|
2466
|
+
const adapter = this.adapters.get(params.channelId);
|
|
2467
|
+
if (params.createThread && adapter) {
|
|
2468
|
+
const threadId = await adapter.createSessionThread(
|
|
2469
|
+
session.id,
|
|
2470
|
+
params.initialName ?? `\u{1F504} ${params.agentName} \u2014 New Session`
|
|
2471
|
+
);
|
|
2472
|
+
session.threadId = threadId;
|
|
2473
|
+
}
|
|
2474
|
+
if (adapter) {
|
|
2475
|
+
const bridge = this.createBridge(session, adapter);
|
|
2476
|
+
bridge.connect();
|
|
2477
|
+
}
|
|
2478
|
+
this.sessionFactory.wireSideEffects(session, {
|
|
2479
|
+
usageStore: this.usageStore,
|
|
2480
|
+
usageBudget: this.usageBudget,
|
|
2481
|
+
notificationManager: this.notificationManager,
|
|
2482
|
+
tunnelService: this._tunnelService
|
|
2483
|
+
});
|
|
2484
|
+
const existingRecord = this.sessionStore?.get(session.id);
|
|
2485
|
+
const platform = {
|
|
2486
|
+
...existingRecord?.platform ?? {}
|
|
2487
|
+
};
|
|
2488
|
+
if (session.threadId) {
|
|
2489
|
+
if (params.channelId === "telegram") {
|
|
2490
|
+
platform.topicId = Number(session.threadId);
|
|
2491
|
+
} else {
|
|
2492
|
+
platform.threadId = session.threadId;
|
|
2493
|
+
}
|
|
2494
|
+
}
|
|
2495
|
+
await this.sessionManager.patchRecord(session.id, {
|
|
2496
|
+
sessionId: session.id,
|
|
2497
|
+
agentSessionId: session.agentSessionId,
|
|
2498
|
+
agentName: params.agentName,
|
|
2499
|
+
workingDir: params.workingDirectory,
|
|
2500
|
+
channelId: params.channelId,
|
|
2501
|
+
status: session.status,
|
|
2502
|
+
createdAt: session.createdAt.toISOString(),
|
|
2503
|
+
lastActiveAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2504
|
+
name: session.name,
|
|
2505
|
+
platform
|
|
2506
|
+
});
|
|
2507
|
+
log7.info(
|
|
2508
|
+
{ sessionId: session.id, agentName: params.agentName },
|
|
2509
|
+
"Session created via pipeline"
|
|
2510
|
+
);
|
|
2511
|
+
return session;
|
|
2512
|
+
}
|
|
2513
|
+
async handleNewSession(channelId, agentName, workspacePath, options) {
|
|
2514
|
+
const config = this.configManager.get();
|
|
2515
|
+
const resolvedAgent = agentName || config.defaultAgent;
|
|
2516
|
+
log7.info({ channelId, agentName: resolvedAgent }, "New session request");
|
|
2517
|
+
const agentDef = this.agentCatalog.resolve(resolvedAgent);
|
|
2518
|
+
const resolvedWorkspace = this.configManager.resolveWorkspace(
|
|
2519
|
+
workspacePath || agentDef?.workingDirectory
|
|
2520
|
+
);
|
|
2521
|
+
return this.createSession({
|
|
2522
|
+
channelId,
|
|
2523
|
+
agentName: resolvedAgent,
|
|
2524
|
+
workingDirectory: resolvedWorkspace,
|
|
2525
|
+
createThread: options?.createThread
|
|
2526
|
+
});
|
|
2527
|
+
}
|
|
2528
|
+
async adoptSession(agentName, agentSessionId, cwd, channelId) {
|
|
2529
|
+
const caps = getAgentCapabilities(agentName);
|
|
2530
|
+
if (!caps.supportsResume) {
|
|
2531
|
+
return {
|
|
2532
|
+
ok: false,
|
|
2533
|
+
error: "agent_not_supported",
|
|
2534
|
+
message: `Agent '${agentName}' does not support session resume`
|
|
2535
|
+
};
|
|
2536
|
+
}
|
|
2537
|
+
const agentDef = this.agentManager.getAgent(agentName);
|
|
2538
|
+
if (!agentDef) {
|
|
2539
|
+
return {
|
|
2540
|
+
ok: false,
|
|
2541
|
+
error: "agent_not_supported",
|
|
2542
|
+
message: `Agent '${agentName}' not found`
|
|
2543
|
+
};
|
|
2544
|
+
}
|
|
2545
|
+
const { existsSync: existsSync2 } = await import("fs");
|
|
2546
|
+
if (!existsSync2(cwd)) {
|
|
2547
|
+
return {
|
|
2548
|
+
ok: false,
|
|
2549
|
+
error: "invalid_cwd",
|
|
2550
|
+
message: `Directory does not exist: ${cwd}`
|
|
2551
|
+
};
|
|
2552
|
+
}
|
|
2553
|
+
const maxSessions = this.configManager.get().security.maxConcurrentSessions;
|
|
2554
|
+
if (this.sessionManager.listSessions().length >= maxSessions) {
|
|
2555
|
+
return {
|
|
2556
|
+
ok: false,
|
|
2557
|
+
error: "session_limit",
|
|
2558
|
+
message: "Maximum concurrent sessions reached"
|
|
2559
|
+
};
|
|
2560
|
+
}
|
|
2561
|
+
const existingRecord = this.sessionManager.getRecordByAgentSessionId(agentSessionId);
|
|
2562
|
+
if (existingRecord) {
|
|
2563
|
+
const sameChannel = !channelId || existingRecord.channelId === channelId;
|
|
2564
|
+
const platform = existingRecord.platform;
|
|
2565
|
+
const existingThreadId = platform?.topicId ? String(platform.topicId) : platform?.threadId;
|
|
2566
|
+
if (existingThreadId && sameChannel) {
|
|
2567
|
+
const adapter = this.adapters.get(existingRecord.channelId) ?? this.adapters.values().next().value;
|
|
2568
|
+
if (adapter) {
|
|
2569
|
+
try {
|
|
2570
|
+
await adapter.sendMessage(existingRecord.sessionId, {
|
|
2571
|
+
type: "text",
|
|
2572
|
+
text: "Session resumed from CLI."
|
|
2573
|
+
});
|
|
2574
|
+
} catch {
|
|
2575
|
+
}
|
|
2576
|
+
}
|
|
2577
|
+
return {
|
|
2578
|
+
ok: true,
|
|
2579
|
+
sessionId: existingRecord.sessionId,
|
|
2580
|
+
threadId: existingThreadId,
|
|
2581
|
+
status: "existing"
|
|
2582
|
+
};
|
|
2583
|
+
}
|
|
2584
|
+
}
|
|
2585
|
+
let adapterChannelId;
|
|
2586
|
+
if (channelId) {
|
|
2587
|
+
if (!this.adapters.has(channelId)) {
|
|
2588
|
+
const available = Array.from(this.adapters.keys()).join(", ") || "none";
|
|
2589
|
+
return { ok: false, error: "adapter_not_found", message: `Adapter '${channelId}' is not connected. Available: ${available}` };
|
|
2590
|
+
}
|
|
2591
|
+
adapterChannelId = channelId;
|
|
2592
|
+
} else {
|
|
2593
|
+
const firstEntry = this.adapters.entries().next().value;
|
|
2594
|
+
if (!firstEntry) {
|
|
2595
|
+
return { ok: false, error: "no_adapter", message: "No channel adapter registered" };
|
|
2596
|
+
}
|
|
2597
|
+
adapterChannelId = firstEntry[0];
|
|
2598
|
+
}
|
|
2599
|
+
let session;
|
|
2600
|
+
try {
|
|
2601
|
+
session = await this.createSession({
|
|
2602
|
+
channelId: adapterChannelId,
|
|
2603
|
+
agentName,
|
|
2604
|
+
workingDirectory: cwd,
|
|
2605
|
+
resumeAgentSessionId: agentSessionId,
|
|
2606
|
+
createThread: true,
|
|
2607
|
+
initialName: "Adopted session"
|
|
2608
|
+
});
|
|
2609
|
+
} catch (err) {
|
|
2610
|
+
return {
|
|
2611
|
+
ok: false,
|
|
2612
|
+
error: "resume_failed",
|
|
2613
|
+
message: `Failed to resume session: ${err instanceof Error ? err.message : String(err)}`
|
|
2614
|
+
};
|
|
2615
|
+
}
|
|
2616
|
+
const adoptPlatform = {};
|
|
2617
|
+
if (adapterChannelId === "telegram") {
|
|
2618
|
+
adoptPlatform.topicId = Number(session.threadId);
|
|
2619
|
+
} else {
|
|
2620
|
+
adoptPlatform.threadId = session.threadId;
|
|
2621
|
+
}
|
|
2622
|
+
await this.sessionManager.patchRecord(session.id, {
|
|
2623
|
+
originalAgentSessionId: agentSessionId,
|
|
2624
|
+
platform: adoptPlatform
|
|
2625
|
+
});
|
|
2626
|
+
return {
|
|
2627
|
+
ok: true,
|
|
2628
|
+
sessionId: session.id,
|
|
2629
|
+
threadId: session.threadId,
|
|
2630
|
+
status: "adopted"
|
|
2631
|
+
};
|
|
2632
|
+
}
|
|
2633
|
+
async handleNewChat(channelId, currentThreadId) {
|
|
2634
|
+
const currentSession = this.sessionManager.getSessionByThread(
|
|
2635
|
+
channelId,
|
|
2636
|
+
currentThreadId
|
|
2637
|
+
);
|
|
2638
|
+
if (currentSession) {
|
|
2639
|
+
return this.handleNewSession(
|
|
2640
|
+
channelId,
|
|
2641
|
+
currentSession.agentName,
|
|
2642
|
+
currentSession.workingDirectory
|
|
2643
|
+
);
|
|
2644
|
+
}
|
|
2645
|
+
const record = this.sessionManager.getRecordByThread(
|
|
2646
|
+
channelId,
|
|
2647
|
+
currentThreadId
|
|
2648
|
+
);
|
|
2649
|
+
if (!record || record.status === "cancelled" || record.status === "error")
|
|
2650
|
+
return null;
|
|
2651
|
+
return this.handleNewSession(
|
|
2652
|
+
channelId,
|
|
2653
|
+
record.agentName,
|
|
2654
|
+
record.workingDir
|
|
2655
|
+
);
|
|
2656
|
+
}
|
|
2657
|
+
// --- Lazy Resume ---
|
|
2658
|
+
/**
|
|
2659
|
+
* Get active session by thread, or attempt lazy resume from store.
|
|
2660
|
+
* Used by adapter command handlers that need a session but don't go through handleMessage().
|
|
2661
|
+
*/
|
|
2662
|
+
async getOrResumeSession(channelId, threadId) {
|
|
2663
|
+
const session = this.sessionManager.getSessionByThread(channelId, threadId);
|
|
2664
|
+
if (session) return session;
|
|
2665
|
+
return this.lazyResume({ channelId, threadId, userId: "", text: "" });
|
|
2666
|
+
}
|
|
2667
|
+
async lazyResume(message) {
|
|
2668
|
+
const store = this.sessionStore;
|
|
2669
|
+
if (!store) return null;
|
|
2670
|
+
const lockKey = `${message.channelId}:${message.threadId}`;
|
|
2671
|
+
const existing = this.resumeLocks.get(lockKey);
|
|
2672
|
+
if (existing) return existing;
|
|
2673
|
+
const record = store.findByPlatform(
|
|
2674
|
+
message.channelId,
|
|
2675
|
+
(p) => String(p.topicId) === message.threadId
|
|
2676
|
+
);
|
|
2677
|
+
if (!record) {
|
|
2678
|
+
log7.debug(
|
|
2679
|
+
{ threadId: message.threadId, channelId: message.channelId },
|
|
2680
|
+
"No session record found for thread"
|
|
2681
|
+
);
|
|
2682
|
+
return null;
|
|
2683
|
+
}
|
|
2684
|
+
if (record.status === "error") {
|
|
2685
|
+
log7.debug(
|
|
2686
|
+
{
|
|
2687
|
+
threadId: message.threadId,
|
|
2688
|
+
sessionId: record.sessionId,
|
|
2689
|
+
status: record.status
|
|
2690
|
+
},
|
|
2691
|
+
"Skipping resume of error session"
|
|
2692
|
+
);
|
|
2693
|
+
return null;
|
|
2694
|
+
}
|
|
2695
|
+
log7.info(
|
|
2696
|
+
{
|
|
2697
|
+
threadId: message.threadId,
|
|
2698
|
+
sessionId: record.sessionId,
|
|
2699
|
+
status: record.status
|
|
2700
|
+
},
|
|
2701
|
+
"Lazy resume: found record, attempting resume"
|
|
2702
|
+
);
|
|
2703
|
+
const resumePromise = (async () => {
|
|
2704
|
+
try {
|
|
2705
|
+
const session = await this.createSession({
|
|
2706
|
+
channelId: record.channelId,
|
|
2707
|
+
agentName: record.agentName,
|
|
2708
|
+
workingDirectory: record.workingDir,
|
|
2709
|
+
resumeAgentSessionId: record.agentSessionId,
|
|
2710
|
+
existingSessionId: record.sessionId,
|
|
2711
|
+
initialName: record.name
|
|
2712
|
+
});
|
|
2713
|
+
session.threadId = message.threadId;
|
|
2714
|
+
session.activate();
|
|
2715
|
+
session.dangerousMode = record.dangerousMode ?? false;
|
|
2716
|
+
log7.info(
|
|
2717
|
+
{ sessionId: session.id, threadId: message.threadId },
|
|
2718
|
+
"Lazy resume successful"
|
|
2719
|
+
);
|
|
2720
|
+
return session;
|
|
2721
|
+
} catch (err) {
|
|
2722
|
+
log7.error({ err, record }, "Lazy resume failed");
|
|
2723
|
+
const adapter = this.adapters.get(message.channelId);
|
|
2724
|
+
if (adapter) {
|
|
2725
|
+
try {
|
|
2726
|
+
await adapter.sendMessage(message.threadId, {
|
|
2727
|
+
type: "error",
|
|
2728
|
+
text: `\u26A0\uFE0F Failed to resume session: ${err instanceof Error ? err.message : String(err)}`
|
|
2729
|
+
});
|
|
2730
|
+
} catch {
|
|
2731
|
+
}
|
|
2732
|
+
}
|
|
2733
|
+
return null;
|
|
2734
|
+
} finally {
|
|
2735
|
+
this.resumeLocks.delete(lockKey);
|
|
2736
|
+
}
|
|
2737
|
+
})();
|
|
2738
|
+
this.resumeLocks.set(lockKey, resumePromise);
|
|
2739
|
+
return resumePromise;
|
|
2740
|
+
}
|
|
2741
|
+
// --- Event Wiring ---
|
|
2742
|
+
/** Create a SessionBridge for the given session and adapter */
|
|
2743
|
+
createBridge(session, adapter) {
|
|
2744
|
+
return new SessionBridge(session, adapter, {
|
|
2745
|
+
messageTransformer: this.messageTransformer,
|
|
2746
|
+
notificationManager: this.notificationManager,
|
|
2747
|
+
sessionManager: this.sessionManager,
|
|
2748
|
+
eventBus: this.eventBus,
|
|
2749
|
+
fileService: this.fileService
|
|
2750
|
+
});
|
|
2751
|
+
}
|
|
2752
|
+
};
|
|
2753
|
+
|
|
2754
|
+
// src/core/sse-manager.ts
|
|
2755
|
+
var SSEManager = class {
|
|
2756
|
+
constructor(eventBus, getSessionStats, startedAt) {
|
|
2757
|
+
this.eventBus = eventBus;
|
|
2758
|
+
this.getSessionStats = getSessionStats;
|
|
2759
|
+
this.startedAt = startedAt;
|
|
2760
|
+
}
|
|
2761
|
+
sseConnections = /* @__PURE__ */ new Set();
|
|
2762
|
+
sseCleanupHandlers = /* @__PURE__ */ new Map();
|
|
2763
|
+
healthInterval;
|
|
2764
|
+
boundHandlers = [];
|
|
2765
|
+
setup() {
|
|
2766
|
+
if (!this.eventBus) return;
|
|
2767
|
+
const events = [
|
|
2768
|
+
"session:created",
|
|
2769
|
+
"session:updated",
|
|
2770
|
+
"session:deleted",
|
|
2771
|
+
"agent:event",
|
|
2772
|
+
"permission:request"
|
|
2773
|
+
];
|
|
2774
|
+
for (const eventName of events) {
|
|
2775
|
+
const handler = (data) => {
|
|
2776
|
+
this.broadcast(eventName, data);
|
|
2777
|
+
};
|
|
2778
|
+
this.eventBus.on(eventName, handler);
|
|
2779
|
+
this.boundHandlers.push({ event: eventName, handler });
|
|
2780
|
+
}
|
|
2781
|
+
this.healthInterval = setInterval(() => {
|
|
2782
|
+
const mem = process.memoryUsage();
|
|
2783
|
+
const stats = this.getSessionStats();
|
|
2784
|
+
this.broadcast("health", {
|
|
2785
|
+
uptime: Date.now() - this.startedAt,
|
|
2786
|
+
memory: {
|
|
2787
|
+
rss: mem.rss,
|
|
2788
|
+
heapUsed: mem.heapUsed,
|
|
2789
|
+
heapTotal: mem.heapTotal
|
|
2790
|
+
},
|
|
2791
|
+
sessions: stats
|
|
2792
|
+
});
|
|
2793
|
+
}, 3e4);
|
|
2794
|
+
}
|
|
2795
|
+
handleRequest(req, res) {
|
|
2796
|
+
const parsedUrl = new URL(req.url || "", "http://localhost");
|
|
2797
|
+
const sessionFilter = parsedUrl.searchParams.get("sessionId");
|
|
2798
|
+
res.writeHead(200, {
|
|
2799
|
+
"Content-Type": "text/event-stream",
|
|
2800
|
+
"Cache-Control": "no-cache",
|
|
2801
|
+
Connection: "keep-alive"
|
|
2802
|
+
});
|
|
2803
|
+
res.flushHeaders();
|
|
2804
|
+
res.sessionFilter = sessionFilter ?? void 0;
|
|
2805
|
+
this.sseConnections.add(res);
|
|
2806
|
+
const cleanup = () => {
|
|
2807
|
+
this.sseConnections.delete(res);
|
|
2808
|
+
this.sseCleanupHandlers.delete(res);
|
|
2809
|
+
};
|
|
2810
|
+
this.sseCleanupHandlers.set(res, cleanup);
|
|
2811
|
+
req.on("close", cleanup);
|
|
2812
|
+
}
|
|
2813
|
+
broadcast(event, data) {
|
|
2814
|
+
const payload = `event: ${event}
|
|
2815
|
+
data: ${JSON.stringify(data)}
|
|
2816
|
+
|
|
2817
|
+
`;
|
|
2818
|
+
const sessionEvents = [
|
|
2819
|
+
"agent:event",
|
|
2820
|
+
"permission:request",
|
|
2821
|
+
"session:updated"
|
|
2822
|
+
];
|
|
2823
|
+
for (const res of this.sseConnections) {
|
|
2824
|
+
const filter = res.sessionFilter;
|
|
2825
|
+
if (filter && sessionEvents.includes(event)) {
|
|
2826
|
+
const eventData = data;
|
|
2827
|
+
if (eventData.sessionId !== filter) continue;
|
|
2828
|
+
}
|
|
2829
|
+
try {
|
|
2830
|
+
if (res.writable) res.write(payload);
|
|
2831
|
+
} catch {
|
|
2832
|
+
}
|
|
2833
|
+
}
|
|
2834
|
+
}
|
|
2835
|
+
stop() {
|
|
2836
|
+
if (this.healthInterval) clearInterval(this.healthInterval);
|
|
2837
|
+
if (this.eventBus) {
|
|
2838
|
+
for (const { event, handler } of this.boundHandlers) {
|
|
2839
|
+
this.eventBus.off(event, handler);
|
|
2840
|
+
}
|
|
2841
|
+
}
|
|
2842
|
+
this.boundHandlers = [];
|
|
2843
|
+
const entries = [...this.sseCleanupHandlers];
|
|
2844
|
+
for (const [res, cleanup] of entries) {
|
|
2845
|
+
res.end();
|
|
2846
|
+
cleanup();
|
|
2847
|
+
}
|
|
2848
|
+
}
|
|
2849
|
+
};
|
|
2850
|
+
|
|
2851
|
+
// src/core/static-server.ts
|
|
2852
|
+
import * as fs6 from "fs";
|
|
2853
|
+
import * as path6 from "path";
|
|
2854
|
+
import { fileURLToPath } from "url";
|
|
2855
|
+
var MIME_TYPES = {
|
|
2856
|
+
".html": "text/html; charset=utf-8",
|
|
2857
|
+
".js": "application/javascript; charset=utf-8",
|
|
2858
|
+
".css": "text/css; charset=utf-8",
|
|
2859
|
+
".json": "application/json; charset=utf-8",
|
|
2860
|
+
".png": "image/png",
|
|
2861
|
+
".jpg": "image/jpeg",
|
|
2862
|
+
".svg": "image/svg+xml",
|
|
2863
|
+
".ico": "image/x-icon",
|
|
2864
|
+
".woff": "font/woff",
|
|
2865
|
+
".woff2": "font/woff2"
|
|
2866
|
+
};
|
|
2867
|
+
var StaticServer = class {
|
|
2868
|
+
uiDir;
|
|
2869
|
+
constructor(uiDir) {
|
|
2870
|
+
this.uiDir = uiDir;
|
|
2871
|
+
if (!this.uiDir) {
|
|
2872
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
2873
|
+
const candidate = path6.resolve(path6.dirname(__filename), "../../ui/dist");
|
|
2874
|
+
if (fs6.existsSync(path6.join(candidate, "index.html"))) {
|
|
2875
|
+
this.uiDir = candidate;
|
|
2876
|
+
}
|
|
2877
|
+
if (!this.uiDir) {
|
|
2878
|
+
const publishCandidate = path6.resolve(
|
|
2879
|
+
path6.dirname(__filename),
|
|
2880
|
+
"../ui"
|
|
2881
|
+
);
|
|
2882
|
+
if (fs6.existsSync(path6.join(publishCandidate, "index.html"))) {
|
|
2883
|
+
this.uiDir = publishCandidate;
|
|
2884
|
+
}
|
|
2885
|
+
}
|
|
2886
|
+
}
|
|
2887
|
+
}
|
|
2888
|
+
isAvailable() {
|
|
2889
|
+
return this.uiDir !== void 0;
|
|
2890
|
+
}
|
|
2891
|
+
serve(req, res) {
|
|
2892
|
+
if (!this.uiDir) return false;
|
|
2893
|
+
const urlPath = (req.url || "/").split("?")[0];
|
|
2894
|
+
const safePath = path6.normalize(urlPath);
|
|
2895
|
+
const filePath = path6.join(this.uiDir, safePath);
|
|
2896
|
+
if (!filePath.startsWith(this.uiDir + path6.sep) && filePath !== this.uiDir)
|
|
2897
|
+
return false;
|
|
2898
|
+
if (fs6.existsSync(filePath) && fs6.statSync(filePath).isFile()) {
|
|
2899
|
+
const ext = path6.extname(filePath);
|
|
2900
|
+
const contentType = MIME_TYPES[ext] ?? "application/octet-stream";
|
|
2901
|
+
const isHashed = /\.[a-zA-Z0-9]{8,}\.(js|css)$/.test(filePath);
|
|
2902
|
+
const cacheControl = isHashed ? "public, max-age=31536000, immutable" : "no-cache";
|
|
2903
|
+
res.writeHead(200, {
|
|
2904
|
+
"Content-Type": contentType,
|
|
2905
|
+
"Cache-Control": cacheControl
|
|
2906
|
+
});
|
|
2907
|
+
fs6.createReadStream(filePath).pipe(res);
|
|
2908
|
+
return true;
|
|
2909
|
+
}
|
|
2910
|
+
const indexPath = path6.join(this.uiDir, "index.html");
|
|
2911
|
+
if (fs6.existsSync(indexPath)) {
|
|
2912
|
+
res.writeHead(200, {
|
|
2913
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
2914
|
+
"Cache-Control": "no-cache"
|
|
2915
|
+
});
|
|
2916
|
+
fs6.createReadStream(indexPath).pipe(res);
|
|
2917
|
+
return true;
|
|
2918
|
+
}
|
|
2919
|
+
return false;
|
|
2920
|
+
}
|
|
2921
|
+
};
|
|
2922
|
+
|
|
2923
|
+
// src/core/api/index.ts
|
|
2924
|
+
import * as http from "http";
|
|
2925
|
+
import * as fs7 from "fs";
|
|
2926
|
+
import * as path7 from "path";
|
|
2927
|
+
import * as os2 from "os";
|
|
2928
|
+
import * as crypto from "crypto";
|
|
2929
|
+
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
2930
|
+
|
|
2931
|
+
// src/core/api/router.ts
|
|
2932
|
+
var Router = class {
|
|
2933
|
+
routes = [];
|
|
2934
|
+
get(path8, handler) {
|
|
2935
|
+
this.add("GET", path8, handler);
|
|
2936
|
+
}
|
|
2937
|
+
post(path8, handler) {
|
|
2938
|
+
this.add("POST", path8, handler);
|
|
2939
|
+
}
|
|
2940
|
+
put(path8, handler) {
|
|
2941
|
+
this.add("PUT", path8, handler);
|
|
2942
|
+
}
|
|
2943
|
+
patch(path8, handler) {
|
|
2944
|
+
this.add("PATCH", path8, handler);
|
|
2945
|
+
}
|
|
2946
|
+
delete(path8, handler) {
|
|
2947
|
+
this.add("DELETE", path8, handler);
|
|
2948
|
+
}
|
|
2949
|
+
match(method, url) {
|
|
2950
|
+
const pathname = url.split("?")[0];
|
|
2951
|
+
for (const route of this.routes) {
|
|
2952
|
+
if (route.method !== method) continue;
|
|
2953
|
+
const m = pathname.match(route.pattern);
|
|
2954
|
+
if (!m) continue;
|
|
2955
|
+
const params = {};
|
|
2956
|
+
for (let i = 0; i < route.keys.length; i++) {
|
|
2957
|
+
params[route.keys[i]] = m[i + 1];
|
|
2958
|
+
}
|
|
2959
|
+
return { handler: route.handler, params };
|
|
2960
|
+
}
|
|
2961
|
+
return null;
|
|
2962
|
+
}
|
|
2963
|
+
add(method, path8, handler) {
|
|
2964
|
+
const keys = [];
|
|
2965
|
+
const pattern = path8.replace(/:(\w+)/g, (_, key) => {
|
|
2966
|
+
keys.push(key);
|
|
2967
|
+
return "([^/]+)";
|
|
2968
|
+
});
|
|
2969
|
+
this.routes.push({
|
|
2970
|
+
method,
|
|
2971
|
+
pattern: new RegExp(`^${pattern}$`),
|
|
2972
|
+
keys,
|
|
2973
|
+
handler
|
|
2974
|
+
});
|
|
2975
|
+
}
|
|
2976
|
+
};
|
|
2977
|
+
|
|
2978
|
+
// src/core/api/routes/health.ts
|
|
2979
|
+
function registerHealthRoutes(router, deps) {
|
|
2980
|
+
router.get("/api/health", async (_req, res) => {
|
|
2981
|
+
const activeSessions = deps.core.sessionManager.listSessions();
|
|
2982
|
+
const allRecords = deps.core.sessionManager.listRecords();
|
|
2983
|
+
const mem = process.memoryUsage();
|
|
2984
|
+
const tunnel = deps.core.tunnelService;
|
|
2985
|
+
deps.sendJson(res, 200, {
|
|
2986
|
+
status: "ok",
|
|
2987
|
+
uptime: Date.now() - deps.startedAt,
|
|
2988
|
+
version: deps.getVersion(),
|
|
2989
|
+
memory: {
|
|
2990
|
+
rss: mem.rss,
|
|
2991
|
+
heapUsed: mem.heapUsed,
|
|
2992
|
+
heapTotal: mem.heapTotal
|
|
2993
|
+
},
|
|
2994
|
+
sessions: {
|
|
2995
|
+
active: activeSessions.filter(
|
|
2996
|
+
(s) => s.status === "active" || s.status === "initializing"
|
|
2997
|
+
).length,
|
|
2998
|
+
total: allRecords.length
|
|
2999
|
+
},
|
|
3000
|
+
adapters: Array.from(deps.core.adapters.keys()),
|
|
3001
|
+
tunnel: tunnel ? { enabled: true, url: tunnel.getPublicUrl() } : { enabled: false }
|
|
3002
|
+
});
|
|
3003
|
+
});
|
|
3004
|
+
router.get("/api/version", async (_req, res) => {
|
|
3005
|
+
deps.sendJson(res, 200, { version: deps.getVersion() });
|
|
3006
|
+
});
|
|
3007
|
+
router.post("/api/restart", async (_req, res) => {
|
|
3008
|
+
if (!deps.core.requestRestart) {
|
|
3009
|
+
deps.sendJson(res, 501, { error: "Restart not available" });
|
|
3010
|
+
return;
|
|
3011
|
+
}
|
|
3012
|
+
deps.sendJson(res, 200, { ok: true, message: "Restarting..." });
|
|
3013
|
+
setImmediate(() => deps.core.requestRestart());
|
|
3014
|
+
});
|
|
3015
|
+
router.get("/api/adapters", async (_req, res) => {
|
|
3016
|
+
const adapters = Array.from(deps.core.adapters.entries()).map(([name]) => ({
|
|
3017
|
+
name,
|
|
3018
|
+
type: "built-in"
|
|
3019
|
+
}));
|
|
3020
|
+
deps.sendJson(res, 200, { adapters });
|
|
3021
|
+
});
|
|
3022
|
+
}
|
|
3023
|
+
|
|
3024
|
+
// src/core/api/routes/sessions.ts
|
|
3025
|
+
var log8 = createChildLogger({ module: "api-server" });
|
|
3026
|
+
function registerSessionRoutes(router, deps) {
|
|
3027
|
+
router.post("/api/sessions/adopt", async (req, res) => {
|
|
3028
|
+
const body = await deps.readBody(req);
|
|
3029
|
+
if (body === null) {
|
|
3030
|
+
return deps.sendJson(res, 413, { error: "Request body too large" });
|
|
3031
|
+
}
|
|
3032
|
+
if (!body) {
|
|
3033
|
+
return deps.sendJson(res, 400, {
|
|
3034
|
+
error: "bad_request",
|
|
3035
|
+
message: "Empty request body"
|
|
3036
|
+
});
|
|
3037
|
+
}
|
|
3038
|
+
let parsed;
|
|
3039
|
+
try {
|
|
3040
|
+
parsed = JSON.parse(body);
|
|
3041
|
+
} catch {
|
|
3042
|
+
return deps.sendJson(res, 400, {
|
|
3043
|
+
error: "bad_request",
|
|
3044
|
+
message: "Invalid JSON"
|
|
3045
|
+
});
|
|
3046
|
+
}
|
|
3047
|
+
const { agent, agentSessionId, cwd, channel } = parsed;
|
|
3048
|
+
if (!agent || !agentSessionId) {
|
|
3049
|
+
return deps.sendJson(res, 400, {
|
|
3050
|
+
error: "bad_request",
|
|
3051
|
+
message: "Missing required fields: agent, agentSessionId"
|
|
3052
|
+
});
|
|
3053
|
+
}
|
|
3054
|
+
const result = await deps.core.adoptSession(
|
|
3055
|
+
agent,
|
|
3056
|
+
agentSessionId,
|
|
3057
|
+
cwd ?? process.cwd(),
|
|
3058
|
+
channel
|
|
3059
|
+
);
|
|
3060
|
+
if (result.ok) {
|
|
3061
|
+
return deps.sendJson(res, 200, result);
|
|
3062
|
+
} else {
|
|
3063
|
+
const status = result.error === "session_limit" ? 429 : result.error === "agent_not_supported" ? 400 : 500;
|
|
3064
|
+
return deps.sendJson(res, status, result);
|
|
3065
|
+
}
|
|
3066
|
+
});
|
|
3067
|
+
router.post("/api/sessions", async (req, res) => {
|
|
3068
|
+
const body = await deps.readBody(req);
|
|
3069
|
+
let agent;
|
|
3070
|
+
let workspace;
|
|
3071
|
+
if (body) {
|
|
3072
|
+
try {
|
|
3073
|
+
const parsed = JSON.parse(body);
|
|
3074
|
+
agent = parsed.agent;
|
|
3075
|
+
workspace = parsed.workspace;
|
|
3076
|
+
} catch {
|
|
3077
|
+
deps.sendJson(res, 400, { error: "Invalid JSON body" });
|
|
3078
|
+
return;
|
|
3079
|
+
}
|
|
3080
|
+
}
|
|
3081
|
+
const config = deps.core.configManager.get();
|
|
3082
|
+
const activeSessions = deps.core.sessionManager.listSessions().filter((s) => s.status === "active" || s.status === "initializing");
|
|
3083
|
+
if (activeSessions.length >= config.security.maxConcurrentSessions) {
|
|
3084
|
+
deps.sendJson(res, 429, {
|
|
3085
|
+
error: `Max concurrent sessions (${config.security.maxConcurrentSessions}) reached. Cancel a session first.`
|
|
3086
|
+
});
|
|
3087
|
+
return;
|
|
3088
|
+
}
|
|
3089
|
+
const [adapterId, adapter] = deps.core.adapters.entries().next().value ?? [
|
|
3090
|
+
null,
|
|
3091
|
+
null
|
|
3092
|
+
];
|
|
3093
|
+
const channelId = adapterId ?? "api";
|
|
3094
|
+
const resolvedAgent = agent || config.defaultAgent;
|
|
3095
|
+
const resolvedWorkspace = deps.core.configManager.resolveWorkspace(
|
|
3096
|
+
workspace || config.agents[resolvedAgent]?.workingDirectory
|
|
3097
|
+
);
|
|
3098
|
+
const session = await deps.core.createSession({
|
|
3099
|
+
channelId,
|
|
3100
|
+
agentName: resolvedAgent,
|
|
3101
|
+
workingDirectory: resolvedWorkspace,
|
|
3102
|
+
createThread: !!adapter,
|
|
3103
|
+
initialName: `\u{1F504} ${resolvedAgent} \u2014 New Session`
|
|
3104
|
+
});
|
|
3105
|
+
if (!adapter) {
|
|
3106
|
+
session.agentInstance.onPermissionRequest = async (request) => {
|
|
3107
|
+
const allowOption = request.options.find((o) => o.isAllow);
|
|
3108
|
+
log8.debug(
|
|
3109
|
+
{
|
|
3110
|
+
sessionId: session.id,
|
|
3111
|
+
permissionId: request.id,
|
|
3112
|
+
option: allowOption?.id
|
|
3113
|
+
},
|
|
3114
|
+
"Auto-approving permission for API session"
|
|
3115
|
+
);
|
|
3116
|
+
return allowOption?.id ?? request.options[0]?.id ?? "";
|
|
3117
|
+
};
|
|
3118
|
+
}
|
|
3119
|
+
session.warmup().catch(
|
|
3120
|
+
(err) => log8.warn({ err, sessionId: session.id }, "API session warmup failed")
|
|
3121
|
+
);
|
|
3122
|
+
deps.sendJson(res, 200, {
|
|
3123
|
+
sessionId: session.id,
|
|
3124
|
+
agent: session.agentName,
|
|
3125
|
+
status: session.status,
|
|
3126
|
+
workspace: session.workingDirectory
|
|
3127
|
+
});
|
|
3128
|
+
});
|
|
3129
|
+
router.post("/api/sessions/:sessionId/prompt", async (req, res, params) => {
|
|
3130
|
+
const sessionId = decodeURIComponent(params.sessionId);
|
|
3131
|
+
const session = deps.core.sessionManager.getSession(sessionId);
|
|
3132
|
+
if (!session) {
|
|
3133
|
+
deps.sendJson(res, 404, { error: `Session "${sessionId}" not found` });
|
|
3134
|
+
return;
|
|
3135
|
+
}
|
|
3136
|
+
if (session.status === "cancelled" || session.status === "finished" || session.status === "error") {
|
|
3137
|
+
deps.sendJson(res, 400, { error: `Session is ${session.status}` });
|
|
3138
|
+
return;
|
|
3139
|
+
}
|
|
3140
|
+
const body = await deps.readBody(req);
|
|
3141
|
+
let prompt;
|
|
3142
|
+
if (body) {
|
|
3143
|
+
try {
|
|
3144
|
+
const parsed = JSON.parse(body);
|
|
3145
|
+
prompt = parsed.prompt;
|
|
3146
|
+
} catch {
|
|
3147
|
+
deps.sendJson(res, 400, { error: "Invalid JSON body" });
|
|
3148
|
+
return;
|
|
3149
|
+
}
|
|
3150
|
+
}
|
|
3151
|
+
if (!prompt) {
|
|
3152
|
+
deps.sendJson(res, 400, { error: "Missing prompt" });
|
|
3153
|
+
return;
|
|
3154
|
+
}
|
|
3155
|
+
session.enqueuePrompt(prompt).catch(() => {
|
|
3156
|
+
});
|
|
3157
|
+
deps.sendJson(res, 200, {
|
|
3158
|
+
ok: true,
|
|
3159
|
+
sessionId,
|
|
3160
|
+
queueDepth: session.queueDepth
|
|
3161
|
+
});
|
|
3162
|
+
});
|
|
3163
|
+
router.post(
|
|
3164
|
+
"/api/sessions/:sessionId/permission",
|
|
3165
|
+
async (req, res, params) => {
|
|
3166
|
+
const sessionId = decodeURIComponent(params.sessionId);
|
|
3167
|
+
const session = deps.core.sessionManager.getSession(sessionId);
|
|
3168
|
+
if (!session) {
|
|
3169
|
+
deps.sendJson(res, 404, { error: `Session "${sessionId}" not found` });
|
|
3170
|
+
return;
|
|
3171
|
+
}
|
|
3172
|
+
const body = await deps.readBody(req);
|
|
3173
|
+
let permissionId;
|
|
3174
|
+
let optionId;
|
|
3175
|
+
if (body) {
|
|
3176
|
+
try {
|
|
3177
|
+
const parsed = JSON.parse(body);
|
|
3178
|
+
permissionId = parsed.permissionId;
|
|
3179
|
+
optionId = parsed.optionId;
|
|
3180
|
+
} catch {
|
|
3181
|
+
deps.sendJson(res, 400, { error: "Invalid JSON body" });
|
|
3182
|
+
return;
|
|
3183
|
+
}
|
|
3184
|
+
}
|
|
3185
|
+
if (!permissionId || !optionId) {
|
|
3186
|
+
deps.sendJson(res, 400, {
|
|
3187
|
+
error: "Missing permissionId or optionId"
|
|
3188
|
+
});
|
|
3189
|
+
return;
|
|
3190
|
+
}
|
|
3191
|
+
if (!session.permissionGate.isPending || session.permissionGate.requestId !== permissionId) {
|
|
3192
|
+
deps.sendJson(res, 400, {
|
|
3193
|
+
error: "No matching pending permission request"
|
|
3194
|
+
});
|
|
3195
|
+
return;
|
|
3196
|
+
}
|
|
3197
|
+
session.permissionGate.resolve(optionId);
|
|
3198
|
+
deps.sendJson(res, 200, { ok: true });
|
|
3199
|
+
}
|
|
3200
|
+
);
|
|
3201
|
+
router.patch(
|
|
3202
|
+
"/api/sessions/:sessionId/dangerous",
|
|
3203
|
+
async (req, res, params) => {
|
|
3204
|
+
const sessionId = decodeURIComponent(params.sessionId);
|
|
3205
|
+
const session = deps.core.sessionManager.getSession(sessionId);
|
|
3206
|
+
if (!session) {
|
|
3207
|
+
deps.sendJson(res, 404, { error: `Session "${sessionId}" not found` });
|
|
3208
|
+
return;
|
|
3209
|
+
}
|
|
3210
|
+
const body = await deps.readBody(req);
|
|
3211
|
+
let enabled;
|
|
3212
|
+
if (body) {
|
|
3213
|
+
try {
|
|
3214
|
+
const parsed = JSON.parse(body);
|
|
3215
|
+
enabled = parsed.enabled;
|
|
3216
|
+
} catch {
|
|
3217
|
+
deps.sendJson(res, 400, { error: "Invalid JSON body" });
|
|
3218
|
+
return;
|
|
3219
|
+
}
|
|
3220
|
+
}
|
|
3221
|
+
if (typeof enabled !== "boolean") {
|
|
3222
|
+
deps.sendJson(res, 400, { error: "Missing enabled boolean" });
|
|
3223
|
+
return;
|
|
3224
|
+
}
|
|
3225
|
+
session.dangerousMode = enabled;
|
|
3226
|
+
await deps.core.sessionManager.patchRecord(sessionId, {
|
|
3227
|
+
dangerousMode: enabled
|
|
3228
|
+
});
|
|
3229
|
+
deps.sendJson(res, 200, { ok: true, dangerousMode: enabled });
|
|
3230
|
+
}
|
|
3231
|
+
);
|
|
3232
|
+
router.get("/api/sessions/:sessionId", async (_req, res, params) => {
|
|
3233
|
+
const sessionId = decodeURIComponent(params.sessionId);
|
|
3234
|
+
const session = deps.core.sessionManager.getSession(sessionId);
|
|
3235
|
+
if (!session) {
|
|
3236
|
+
deps.sendJson(res, 404, { error: `Session "${sessionId}" not found` });
|
|
3237
|
+
return;
|
|
3238
|
+
}
|
|
3239
|
+
deps.sendJson(res, 200, {
|
|
3240
|
+
session: {
|
|
3241
|
+
id: session.id,
|
|
3242
|
+
agent: session.agentName,
|
|
3243
|
+
status: session.status,
|
|
3244
|
+
name: session.name ?? null,
|
|
3245
|
+
workspace: session.workingDirectory,
|
|
3246
|
+
createdAt: session.createdAt.toISOString(),
|
|
3247
|
+
dangerousMode: session.dangerousMode,
|
|
3248
|
+
queueDepth: session.queueDepth,
|
|
3249
|
+
promptRunning: session.promptRunning,
|
|
3250
|
+
threadId: session.threadId,
|
|
3251
|
+
channelId: session.channelId,
|
|
3252
|
+
agentSessionId: session.agentSessionId
|
|
3253
|
+
}
|
|
3254
|
+
});
|
|
3255
|
+
});
|
|
3256
|
+
router.post("/api/sessions/:sessionId/archive", async (_req, res, params) => {
|
|
3257
|
+
const sessionId = decodeURIComponent(params.sessionId);
|
|
3258
|
+
const result = await deps.core.archiveSession(sessionId);
|
|
3259
|
+
if (result.ok) {
|
|
3260
|
+
deps.sendJson(res, 200, result);
|
|
3261
|
+
} else {
|
|
3262
|
+
deps.sendJson(res, 400, result);
|
|
3263
|
+
}
|
|
3264
|
+
});
|
|
3265
|
+
router.delete("/api/sessions/:sessionId", async (_req, res, params) => {
|
|
3266
|
+
const sessionId = decodeURIComponent(params.sessionId);
|
|
3267
|
+
const session = deps.core.sessionManager.getSession(sessionId);
|
|
3268
|
+
if (!session) {
|
|
3269
|
+
deps.sendJson(res, 404, { error: `Session "${sessionId}" not found` });
|
|
3270
|
+
return;
|
|
3271
|
+
}
|
|
3272
|
+
await deps.core.sessionManager.cancelSession(sessionId);
|
|
3273
|
+
deps.sendJson(res, 200, { ok: true });
|
|
3274
|
+
});
|
|
3275
|
+
router.get("/api/sessions", async (_req, res) => {
|
|
3276
|
+
const sessions = deps.core.sessionManager.listSessions();
|
|
3277
|
+
deps.sendJson(res, 200, {
|
|
3278
|
+
sessions: sessions.map((s) => ({
|
|
3279
|
+
id: s.id,
|
|
3280
|
+
agent: s.agentName,
|
|
3281
|
+
status: s.status,
|
|
3282
|
+
name: s.name ?? null,
|
|
3283
|
+
workspace: s.workingDirectory,
|
|
3284
|
+
createdAt: s.createdAt.toISOString(),
|
|
3285
|
+
dangerousMode: s.dangerousMode,
|
|
3286
|
+
queueDepth: s.queueDepth,
|
|
3287
|
+
promptRunning: s.promptRunning,
|
|
3288
|
+
lastActiveAt: deps.core.sessionManager.getSessionRecord(s.id)?.lastActiveAt ?? null
|
|
3289
|
+
}))
|
|
3290
|
+
});
|
|
3291
|
+
});
|
|
3292
|
+
}
|
|
3293
|
+
|
|
3294
|
+
// src/core/api/routes/config.ts
|
|
3295
|
+
var SENSITIVE_KEYS = [
|
|
3296
|
+
"botToken",
|
|
3297
|
+
"token",
|
|
3298
|
+
"apiKey",
|
|
3299
|
+
"secret",
|
|
3300
|
+
"password",
|
|
3301
|
+
"webhookSecret"
|
|
3302
|
+
];
|
|
3303
|
+
function redactConfig(config) {
|
|
3304
|
+
const redacted = structuredClone(config);
|
|
3305
|
+
redactDeep(redacted);
|
|
3306
|
+
return redacted;
|
|
3307
|
+
}
|
|
3308
|
+
function redactDeep(obj) {
|
|
3309
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
3310
|
+
if (SENSITIVE_KEYS.includes(key) && typeof value === "string") {
|
|
3311
|
+
obj[key] = "***";
|
|
3312
|
+
} else if (Array.isArray(value)) {
|
|
3313
|
+
for (const item of value) {
|
|
3314
|
+
if (item && typeof item === "object")
|
|
3315
|
+
redactDeep(item);
|
|
3316
|
+
}
|
|
3317
|
+
} else if (value && typeof value === "object") {
|
|
3318
|
+
redactDeep(value);
|
|
3319
|
+
}
|
|
3320
|
+
}
|
|
3321
|
+
}
|
|
3322
|
+
function registerConfigRoutes(router, deps) {
|
|
3323
|
+
router.get("/api/config/editable", async (_req, res) => {
|
|
3324
|
+
const { getSafeFields: getSafeFields2, resolveOptions: resolveOptions2, getConfigValue: getConfigValue2 } = await import("./config-registry-7I6GGDOY.js");
|
|
3325
|
+
const config = deps.core.configManager.get();
|
|
3326
|
+
const safeFields = getSafeFields2();
|
|
3327
|
+
const fields = safeFields.map((def) => ({
|
|
3328
|
+
path: def.path,
|
|
3329
|
+
displayName: def.displayName,
|
|
3330
|
+
group: def.group,
|
|
3331
|
+
type: def.type,
|
|
3332
|
+
options: resolveOptions2(def, config),
|
|
3333
|
+
value: getConfigValue2(config, def.path),
|
|
3334
|
+
hotReload: def.hotReload
|
|
3335
|
+
}));
|
|
3336
|
+
deps.sendJson(res, 200, { fields });
|
|
3337
|
+
});
|
|
3338
|
+
router.get("/api/config", async (_req, res) => {
|
|
3339
|
+
const config = deps.core.configManager.get();
|
|
3340
|
+
deps.sendJson(res, 200, { config: redactConfig(config) });
|
|
3341
|
+
});
|
|
3342
|
+
router.patch("/api/config", async (req, res) => {
|
|
3343
|
+
const body = await deps.readBody(req);
|
|
3344
|
+
let configPath;
|
|
3345
|
+
let value;
|
|
3346
|
+
if (body) {
|
|
3347
|
+
try {
|
|
3348
|
+
const parsed = JSON.parse(body);
|
|
3349
|
+
configPath = parsed.path;
|
|
3350
|
+
value = parsed.value;
|
|
3351
|
+
} catch {
|
|
3352
|
+
deps.sendJson(res, 400, { error: "Invalid JSON body" });
|
|
3353
|
+
return;
|
|
3354
|
+
}
|
|
3355
|
+
}
|
|
3356
|
+
if (!configPath) {
|
|
3357
|
+
deps.sendJson(res, 400, { error: "Missing path" });
|
|
3358
|
+
return;
|
|
3359
|
+
}
|
|
3360
|
+
const BLOCKED_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
|
|
3361
|
+
const parts = configPath.split(".");
|
|
3362
|
+
if (parts.some((p) => BLOCKED_KEYS.has(p))) {
|
|
3363
|
+
deps.sendJson(res, 400, { error: "Invalid config path" });
|
|
3364
|
+
return;
|
|
3365
|
+
}
|
|
3366
|
+
const { getFieldDef: getFieldDef2 } = await import("./config-registry-7I6GGDOY.js");
|
|
3367
|
+
const fieldDef = getFieldDef2(configPath);
|
|
3368
|
+
if (!fieldDef || fieldDef.scope !== "safe") {
|
|
3369
|
+
deps.sendJson(res, 403, {
|
|
3370
|
+
error: "This config field cannot be modified via the API"
|
|
3371
|
+
});
|
|
3372
|
+
return;
|
|
3373
|
+
}
|
|
3374
|
+
const currentConfig = deps.core.configManager.get();
|
|
3375
|
+
const cloned = structuredClone(currentConfig);
|
|
3376
|
+
let target = cloned;
|
|
3377
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
3378
|
+
const part = parts[i];
|
|
3379
|
+
if (target[part] && typeof target[part] === "object" && !Array.isArray(target[part])) {
|
|
3380
|
+
target = target[part];
|
|
3381
|
+
} else if (target[part] === void 0 || target[part] === null) {
|
|
3382
|
+
target[part] = {};
|
|
3383
|
+
target = target[part];
|
|
3384
|
+
} else {
|
|
3385
|
+
deps.sendJson(res, 400, { error: "Invalid config path" });
|
|
3386
|
+
return;
|
|
3387
|
+
}
|
|
3388
|
+
}
|
|
3389
|
+
const lastKey = parts[parts.length - 1];
|
|
3390
|
+
target[lastKey] = value;
|
|
3391
|
+
const { ConfigSchema } = await import("./config-B26J3XXN.js");
|
|
3392
|
+
const result = ConfigSchema.safeParse(cloned);
|
|
3393
|
+
if (!result.success) {
|
|
3394
|
+
deps.sendJson(res, 400, {
|
|
3395
|
+
error: "Validation failed",
|
|
3396
|
+
details: result.error.issues.map((i) => ({
|
|
3397
|
+
path: i.path.join("."),
|
|
3398
|
+
message: i.message
|
|
3399
|
+
}))
|
|
3400
|
+
});
|
|
3401
|
+
return;
|
|
3402
|
+
}
|
|
3403
|
+
const updates = {};
|
|
3404
|
+
let updateTarget = updates;
|
|
3405
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
3406
|
+
updateTarget[parts[i]] = {};
|
|
3407
|
+
updateTarget = updateTarget[parts[i]];
|
|
3408
|
+
}
|
|
3409
|
+
updateTarget[lastKey] = value;
|
|
3410
|
+
await deps.core.configManager.save(updates, configPath);
|
|
3411
|
+
const { isHotReloadable: isHotReloadable2 } = await import("./config-registry-7I6GGDOY.js");
|
|
3412
|
+
const needsRestart = !isHotReloadable2(configPath);
|
|
3413
|
+
deps.sendJson(res, 200, {
|
|
3414
|
+
ok: true,
|
|
3415
|
+
needsRestart,
|
|
3416
|
+
config: redactConfig(deps.core.configManager.get())
|
|
3417
|
+
});
|
|
3418
|
+
});
|
|
3419
|
+
}
|
|
3420
|
+
|
|
3421
|
+
// src/core/api/routes/topics.ts
|
|
3422
|
+
function registerTopicRoutes(router, deps) {
|
|
3423
|
+
router.get("/api/topics", async (req, res) => {
|
|
3424
|
+
if (!deps.topicManager) {
|
|
3425
|
+
deps.sendJson(res, 501, { error: "Topic management not available" });
|
|
3426
|
+
return;
|
|
3427
|
+
}
|
|
3428
|
+
const url = req.url || "";
|
|
3429
|
+
const params = new URL(url, "http://localhost").searchParams;
|
|
3430
|
+
const statusParam = params.get("status");
|
|
3431
|
+
const filter = statusParam ? { statuses: statusParam.split(",") } : void 0;
|
|
3432
|
+
const topics = deps.topicManager.listTopics(filter);
|
|
3433
|
+
deps.sendJson(res, 200, { topics });
|
|
3434
|
+
});
|
|
3435
|
+
router.post("/api/topics/cleanup", async (req, res) => {
|
|
3436
|
+
if (!deps.topicManager) {
|
|
3437
|
+
deps.sendJson(res, 501, { error: "Topic management not available" });
|
|
3438
|
+
return;
|
|
3439
|
+
}
|
|
3440
|
+
const body = await deps.readBody(req);
|
|
3441
|
+
let statuses;
|
|
3442
|
+
if (body) {
|
|
3443
|
+
try {
|
|
3444
|
+
statuses = JSON.parse(body).statuses;
|
|
3445
|
+
} catch {
|
|
3446
|
+
}
|
|
3447
|
+
}
|
|
3448
|
+
const result = await deps.topicManager.cleanup(statuses);
|
|
3449
|
+
deps.sendJson(res, 200, result);
|
|
3450
|
+
});
|
|
3451
|
+
router.delete("/api/topics/:sessionId", async (req, res, params) => {
|
|
3452
|
+
if (!deps.topicManager) {
|
|
3453
|
+
deps.sendJson(res, 501, { error: "Topic management not available" });
|
|
3454
|
+
return;
|
|
3455
|
+
}
|
|
3456
|
+
const sessionId = decodeURIComponent(params.sessionId);
|
|
3457
|
+
const url = req.url || "";
|
|
3458
|
+
const urlParams = new URL(url, "http://localhost").searchParams;
|
|
3459
|
+
const force = urlParams.get("force") === "true";
|
|
3460
|
+
const result = await deps.topicManager.deleteTopic(
|
|
3461
|
+
sessionId,
|
|
3462
|
+
force ? { confirmed: true } : void 0
|
|
3463
|
+
);
|
|
3464
|
+
if (result.ok) {
|
|
3465
|
+
deps.sendJson(res, 200, result);
|
|
3466
|
+
} else if (result.needsConfirmation) {
|
|
3467
|
+
deps.sendJson(res, 409, {
|
|
3468
|
+
error: "Session is active",
|
|
3469
|
+
needsConfirmation: true,
|
|
3470
|
+
session: result.session
|
|
3471
|
+
});
|
|
3472
|
+
} else if (result.error === "Cannot delete system topic") {
|
|
3473
|
+
deps.sendJson(res, 403, { error: result.error });
|
|
3474
|
+
} else {
|
|
3475
|
+
deps.sendJson(res, 404, { error: result.error ?? "Not found" });
|
|
3476
|
+
}
|
|
3477
|
+
});
|
|
3478
|
+
}
|
|
3479
|
+
|
|
3480
|
+
// src/core/api/routes/tunnel.ts
|
|
3481
|
+
function registerTunnelRoutes(router, deps) {
|
|
3482
|
+
router.get("/api/tunnel", async (_req, res) => {
|
|
3483
|
+
const tunnel = deps.core.tunnelService;
|
|
3484
|
+
if (tunnel) {
|
|
3485
|
+
deps.sendJson(res, 200, {
|
|
3486
|
+
enabled: true,
|
|
3487
|
+
url: tunnel.getPublicUrl(),
|
|
3488
|
+
provider: deps.core.configManager.get().tunnel.provider
|
|
3489
|
+
});
|
|
3490
|
+
} else {
|
|
3491
|
+
deps.sendJson(res, 200, { enabled: false });
|
|
3492
|
+
}
|
|
3493
|
+
});
|
|
3494
|
+
router.get("/api/tunnel/list", async (_req, res) => {
|
|
3495
|
+
const tunnel = deps.core.tunnelService;
|
|
3496
|
+
if (!tunnel) {
|
|
3497
|
+
deps.sendJson(res, 200, []);
|
|
3498
|
+
return;
|
|
3499
|
+
}
|
|
3500
|
+
deps.sendJson(res, 200, tunnel.listTunnels());
|
|
3501
|
+
});
|
|
3502
|
+
router.post("/api/tunnel", async (req, res) => {
|
|
3503
|
+
const tunnel = deps.core.tunnelService;
|
|
3504
|
+
if (!tunnel) {
|
|
3505
|
+
deps.sendJson(res, 400, { error: "Tunnel service is not enabled" });
|
|
3506
|
+
return;
|
|
3507
|
+
}
|
|
3508
|
+
const body = await deps.readBody(req);
|
|
3509
|
+
if (body === null) {
|
|
3510
|
+
deps.sendJson(res, 413, { error: "Request body too large" });
|
|
3511
|
+
return;
|
|
3512
|
+
}
|
|
3513
|
+
if (!body) {
|
|
3514
|
+
deps.sendJson(res, 400, { error: "Missing request body" });
|
|
3515
|
+
return;
|
|
3516
|
+
}
|
|
3517
|
+
try {
|
|
3518
|
+
const { port, label, sessionId } = JSON.parse(body);
|
|
3519
|
+
if (!port || typeof port !== "number") {
|
|
3520
|
+
deps.sendJson(res, 400, {
|
|
3521
|
+
error: "port is required and must be a number"
|
|
3522
|
+
});
|
|
3523
|
+
return;
|
|
3524
|
+
}
|
|
3525
|
+
const entry = await tunnel.addTunnel(port, { label, sessionId });
|
|
3526
|
+
deps.sendJson(res, 200, entry);
|
|
3527
|
+
} catch (err) {
|
|
3528
|
+
deps.sendJson(res, 400, { error: err.message });
|
|
3529
|
+
}
|
|
3530
|
+
});
|
|
3531
|
+
router.delete("/api/tunnel/:port", async (_req, res, params) => {
|
|
3532
|
+
const tunnel = deps.core.tunnelService;
|
|
3533
|
+
if (!tunnel) {
|
|
3534
|
+
deps.sendJson(res, 400, { error: "Tunnel service is not enabled" });
|
|
3535
|
+
return;
|
|
3536
|
+
}
|
|
3537
|
+
const port = parseInt(params.port, 10);
|
|
3538
|
+
try {
|
|
3539
|
+
await tunnel.stopTunnel(port);
|
|
3540
|
+
deps.sendJson(res, 200, { ok: true });
|
|
3541
|
+
} catch (err) {
|
|
3542
|
+
deps.sendJson(res, 400, { error: err.message });
|
|
3543
|
+
}
|
|
3544
|
+
});
|
|
3545
|
+
router.delete("/api/tunnel", async (_req, res) => {
|
|
3546
|
+
const tunnel = deps.core.tunnelService;
|
|
3547
|
+
if (!tunnel) {
|
|
3548
|
+
deps.sendJson(res, 400, { error: "Tunnel service is not enabled" });
|
|
3549
|
+
return;
|
|
3550
|
+
}
|
|
3551
|
+
const count = tunnel.listTunnels().length;
|
|
3552
|
+
await tunnel.stopAllUser();
|
|
3553
|
+
deps.sendJson(res, 200, { ok: true, stopped: count });
|
|
3554
|
+
});
|
|
3555
|
+
}
|
|
3556
|
+
|
|
3557
|
+
// src/core/api/routes/agents.ts
|
|
3558
|
+
function registerAgentRoutes(router, deps) {
|
|
3559
|
+
router.get("/api/agents", async (_req, res) => {
|
|
3560
|
+
const agents = deps.core.agentManager.getAvailableAgents();
|
|
3561
|
+
const defaultAgent = deps.core.configManager.get().defaultAgent;
|
|
3562
|
+
const agentsWithCaps = agents.map((a) => ({
|
|
3563
|
+
...a,
|
|
3564
|
+
capabilities: getAgentCapabilities(a.name)
|
|
3565
|
+
}));
|
|
3566
|
+
deps.sendJson(res, 200, { agents: agentsWithCaps, default: defaultAgent });
|
|
3567
|
+
});
|
|
3568
|
+
}
|
|
3569
|
+
|
|
3570
|
+
// src/core/api/routes/notify.ts
|
|
3571
|
+
function registerNotifyRoutes(router, deps) {
|
|
3572
|
+
router.post("/api/notify", async (req, res) => {
|
|
3573
|
+
const body = await deps.readBody(req);
|
|
3574
|
+
let message;
|
|
3575
|
+
if (body) {
|
|
3576
|
+
try {
|
|
3577
|
+
const parsed = JSON.parse(body);
|
|
3578
|
+
message = parsed.message;
|
|
3579
|
+
} catch {
|
|
3580
|
+
deps.sendJson(res, 400, { error: "Invalid JSON body" });
|
|
3581
|
+
return;
|
|
3582
|
+
}
|
|
3583
|
+
}
|
|
3584
|
+
if (!message) {
|
|
3585
|
+
deps.sendJson(res, 400, { error: "Missing message" });
|
|
3586
|
+
return;
|
|
3587
|
+
}
|
|
3588
|
+
await deps.core.notificationManager.notifyAll({
|
|
3589
|
+
sessionId: "system",
|
|
3590
|
+
type: "completed",
|
|
3591
|
+
summary: message
|
|
3592
|
+
});
|
|
3593
|
+
deps.sendJson(res, 200, { ok: true });
|
|
3594
|
+
});
|
|
3595
|
+
}
|
|
3596
|
+
|
|
3597
|
+
// src/core/api/index.ts
|
|
3598
|
+
var log9 = createChildLogger({ module: "api-server" });
|
|
3599
|
+
var DEFAULT_PORT_FILE = path7.join(os2.homedir(), ".openacp", "api.port");
|
|
3600
|
+
var cachedVersion;
|
|
3601
|
+
function getVersion() {
|
|
3602
|
+
if (cachedVersion) return cachedVersion;
|
|
3603
|
+
try {
|
|
3604
|
+
const __filename = fileURLToPath2(import.meta.url);
|
|
3605
|
+
const pkgPath = path7.resolve(
|
|
3606
|
+
path7.dirname(__filename),
|
|
3607
|
+
"../../../package.json"
|
|
3608
|
+
);
|
|
3609
|
+
const pkg = JSON.parse(fs7.readFileSync(pkgPath, "utf-8"));
|
|
3610
|
+
cachedVersion = pkg.version ?? "0.0.0-dev";
|
|
3611
|
+
} catch {
|
|
3612
|
+
cachedVersion = "0.0.0-dev";
|
|
3613
|
+
}
|
|
3614
|
+
return cachedVersion;
|
|
3615
|
+
}
|
|
3616
|
+
var ApiServer = class {
|
|
3617
|
+
constructor(core, config, portFilePath, topicManager, secretFilePath, uiDir) {
|
|
3618
|
+
this.core = core;
|
|
3619
|
+
this.config = config;
|
|
3620
|
+
this.topicManager = topicManager;
|
|
3621
|
+
this.portFilePath = portFilePath ?? DEFAULT_PORT_FILE;
|
|
3622
|
+
this.secretFilePath = secretFilePath ?? path7.join(os2.homedir(), ".openacp", "api-secret");
|
|
3623
|
+
this.staticServer = new StaticServer(uiDir);
|
|
3624
|
+
this.sseManager = new SSEManager(
|
|
3625
|
+
core.eventBus,
|
|
3626
|
+
() => {
|
|
3627
|
+
const sessions = this.core.sessionManager.listSessions();
|
|
3628
|
+
return {
|
|
3629
|
+
active: sessions.filter(
|
|
3630
|
+
(s) => s.status === "active" || s.status === "initializing"
|
|
3631
|
+
).length,
|
|
3632
|
+
total: sessions.length
|
|
3633
|
+
};
|
|
3634
|
+
},
|
|
3635
|
+
this.startedAt
|
|
3636
|
+
);
|
|
3637
|
+
this.router = new Router();
|
|
3638
|
+
const deps = {
|
|
3639
|
+
core: this.core,
|
|
3640
|
+
topicManager: this.topicManager,
|
|
3641
|
+
startedAt: this.startedAt,
|
|
3642
|
+
getVersion,
|
|
3643
|
+
sendJson: this.sendJson.bind(this),
|
|
3644
|
+
readBody: this.readBody.bind(this)
|
|
3645
|
+
};
|
|
3646
|
+
registerHealthRoutes(this.router, deps);
|
|
3647
|
+
registerSessionRoutes(this.router, deps);
|
|
3648
|
+
registerConfigRoutes(this.router, deps);
|
|
3649
|
+
registerTopicRoutes(this.router, deps);
|
|
3650
|
+
registerTunnelRoutes(this.router, deps);
|
|
3651
|
+
registerAgentRoutes(this.router, deps);
|
|
3652
|
+
registerNotifyRoutes(this.router, deps);
|
|
3653
|
+
}
|
|
3654
|
+
server = null;
|
|
3655
|
+
actualPort = 0;
|
|
3656
|
+
portFilePath;
|
|
3657
|
+
startedAt = Date.now();
|
|
3658
|
+
secret = "";
|
|
3659
|
+
secretFilePath;
|
|
3660
|
+
sseManager;
|
|
3661
|
+
staticServer;
|
|
3662
|
+
router;
|
|
3663
|
+
async start() {
|
|
3664
|
+
this.loadOrCreateSecret();
|
|
3665
|
+
this.server = http.createServer((req, res) => this.handleRequest(req, res));
|
|
3666
|
+
await new Promise((resolve3, reject) => {
|
|
3667
|
+
this.server.on("error", (err) => {
|
|
3668
|
+
if (err.code === "EADDRINUSE") {
|
|
3669
|
+
log9.warn(
|
|
3670
|
+
{ port: this.config.port },
|
|
3671
|
+
"API port in use, continuing without API server"
|
|
3672
|
+
);
|
|
3673
|
+
this.server = null;
|
|
3674
|
+
resolve3();
|
|
3675
|
+
} else {
|
|
3676
|
+
reject(err);
|
|
3677
|
+
}
|
|
3678
|
+
});
|
|
3679
|
+
this.server.listen(this.config.port, this.config.host, () => {
|
|
3680
|
+
const addr = this.server.address();
|
|
3681
|
+
if (addr && typeof addr === "object") {
|
|
3682
|
+
this.actualPort = addr.port;
|
|
3683
|
+
}
|
|
3684
|
+
this.writePortFile();
|
|
3685
|
+
log9.info(
|
|
3686
|
+
{ host: this.config.host, port: this.actualPort },
|
|
3687
|
+
"API server listening"
|
|
3688
|
+
);
|
|
3689
|
+
this.sseManager.setup();
|
|
3690
|
+
if (this.config.host !== "127.0.0.1" && this.config.host !== "localhost") {
|
|
3691
|
+
log9.warn(
|
|
3692
|
+
"API server binding to non-localhost. Ensure api-secret file is secured."
|
|
3693
|
+
);
|
|
3694
|
+
}
|
|
3695
|
+
resolve3();
|
|
3696
|
+
});
|
|
3697
|
+
});
|
|
3698
|
+
}
|
|
3699
|
+
async stop() {
|
|
3700
|
+
this.sseManager.stop();
|
|
3701
|
+
this.removePortFile();
|
|
3702
|
+
if (this.server) {
|
|
3703
|
+
await new Promise((resolve3) => {
|
|
3704
|
+
this.server.close(() => resolve3());
|
|
3705
|
+
});
|
|
3706
|
+
this.server = null;
|
|
3707
|
+
}
|
|
3708
|
+
}
|
|
3709
|
+
getPort() {
|
|
3710
|
+
return this.actualPort;
|
|
3711
|
+
}
|
|
3712
|
+
getSecret() {
|
|
3713
|
+
return this.secret;
|
|
3714
|
+
}
|
|
3715
|
+
writePortFile() {
|
|
3716
|
+
const dir = path7.dirname(this.portFilePath);
|
|
3717
|
+
fs7.mkdirSync(dir, { recursive: true });
|
|
3718
|
+
fs7.writeFileSync(this.portFilePath, String(this.actualPort));
|
|
3719
|
+
}
|
|
3720
|
+
removePortFile() {
|
|
3721
|
+
try {
|
|
3722
|
+
fs7.unlinkSync(this.portFilePath);
|
|
3723
|
+
} catch {
|
|
3724
|
+
}
|
|
3725
|
+
}
|
|
3726
|
+
loadOrCreateSecret() {
|
|
3727
|
+
const dir = path7.dirname(this.secretFilePath);
|
|
3728
|
+
fs7.mkdirSync(dir, { recursive: true });
|
|
3729
|
+
try {
|
|
3730
|
+
this.secret = fs7.readFileSync(this.secretFilePath, "utf-8").trim();
|
|
3731
|
+
if (this.secret) {
|
|
3732
|
+
try {
|
|
3733
|
+
const stat = fs7.statSync(this.secretFilePath);
|
|
3734
|
+
const mode = stat.mode & 511;
|
|
3735
|
+
if (mode & 63) {
|
|
3736
|
+
log9.warn(
|
|
3737
|
+
{ path: this.secretFilePath, mode: "0" + mode.toString(8) },
|
|
3738
|
+
"API secret file has insecure permissions (should be 0600). Run: chmod 600 %s",
|
|
3739
|
+
this.secretFilePath
|
|
3740
|
+
);
|
|
3741
|
+
}
|
|
3742
|
+
} catch {
|
|
3743
|
+
}
|
|
3744
|
+
return;
|
|
3745
|
+
}
|
|
3746
|
+
} catch {
|
|
3747
|
+
}
|
|
3748
|
+
this.secret = crypto.randomBytes(32).toString("hex");
|
|
3749
|
+
fs7.writeFileSync(this.secretFilePath, this.secret, { mode: 384 });
|
|
3750
|
+
}
|
|
3751
|
+
authenticate(req, allowQueryParam = false) {
|
|
3752
|
+
const authHeader = req.headers.authorization;
|
|
3753
|
+
if (authHeader?.startsWith("Bearer ")) {
|
|
3754
|
+
const token = authHeader.slice(7);
|
|
3755
|
+
if (token.length === this.secret.length && crypto.timingSafeEqual(
|
|
3756
|
+
Buffer.from(token, "utf-8"),
|
|
3757
|
+
Buffer.from(this.secret, "utf-8")
|
|
3758
|
+
)) {
|
|
3759
|
+
return true;
|
|
3760
|
+
}
|
|
3761
|
+
}
|
|
3762
|
+
if (allowQueryParam) {
|
|
3763
|
+
const parsedUrl = new URL(req.url || "", "http://localhost");
|
|
3764
|
+
const qToken = parsedUrl.searchParams.get("token");
|
|
3765
|
+
if (qToken && qToken.length === this.secret.length && crypto.timingSafeEqual(
|
|
3766
|
+
Buffer.from(qToken, "utf-8"),
|
|
3767
|
+
Buffer.from(this.secret, "utf-8")
|
|
3768
|
+
)) {
|
|
3769
|
+
return true;
|
|
3770
|
+
}
|
|
3771
|
+
}
|
|
3772
|
+
return false;
|
|
3773
|
+
}
|
|
3774
|
+
async handleRequest(req, res) {
|
|
3775
|
+
const method = req.method?.toUpperCase();
|
|
3776
|
+
const url = req.url || "";
|
|
3777
|
+
if (url.startsWith("/api/")) {
|
|
3778
|
+
const isExempt = method === "GET" && (url === "/api/health" || url === "/api/version" || url.startsWith("/api/events"));
|
|
3779
|
+
if (!isExempt && !this.authenticate(req)) {
|
|
3780
|
+
this.sendJson(res, 401, { error: "Unauthorized" });
|
|
3781
|
+
return;
|
|
3782
|
+
}
|
|
3783
|
+
}
|
|
3784
|
+
try {
|
|
3785
|
+
if (method === "GET" && url.startsWith("/api/events")) {
|
|
3786
|
+
if (!this.authenticate(req, true)) {
|
|
3787
|
+
this.sendJson(res, 401, { error: "Unauthorized" });
|
|
3788
|
+
return;
|
|
3789
|
+
}
|
|
3790
|
+
this.sseManager.handleRequest(req, res);
|
|
3791
|
+
return;
|
|
3792
|
+
}
|
|
3793
|
+
if (url.startsWith("/api/")) {
|
|
3794
|
+
const match = this.router.match(method, url);
|
|
3795
|
+
if (match) {
|
|
3796
|
+
await match.handler(req, res, match.params);
|
|
3797
|
+
} else {
|
|
3798
|
+
this.sendJson(res, 404, { error: "Not found" });
|
|
3799
|
+
}
|
|
3800
|
+
return;
|
|
3801
|
+
}
|
|
3802
|
+
if (!this.staticServer.serve(req, res)) {
|
|
3803
|
+
this.sendJson(res, 404, { error: "Not found" });
|
|
3804
|
+
}
|
|
3805
|
+
} catch (err) {
|
|
3806
|
+
log9.error({ err }, "API request error");
|
|
3807
|
+
this.sendJson(res, 500, { error: "Internal server error" });
|
|
3808
|
+
}
|
|
3809
|
+
}
|
|
3810
|
+
sendJson(res, status, data) {
|
|
3811
|
+
res.writeHead(status, { "Content-Type": "application/json" });
|
|
3812
|
+
res.end(JSON.stringify(data));
|
|
3813
|
+
}
|
|
3814
|
+
readBody(req) {
|
|
3815
|
+
const MAX_BODY_SIZE = 1024 * 1024;
|
|
3816
|
+
return new Promise((resolve3) => {
|
|
3817
|
+
let data = "";
|
|
3818
|
+
let size = 0;
|
|
3819
|
+
let destroyed = false;
|
|
3820
|
+
req.on("data", (chunk) => {
|
|
3821
|
+
size += chunk.length;
|
|
3822
|
+
if (size > MAX_BODY_SIZE && !destroyed) {
|
|
3823
|
+
destroyed = true;
|
|
3824
|
+
req.destroy();
|
|
3825
|
+
resolve3(null);
|
|
3826
|
+
return;
|
|
3827
|
+
}
|
|
3828
|
+
if (!destroyed) data += chunk;
|
|
3829
|
+
});
|
|
3830
|
+
req.on("end", () => {
|
|
3831
|
+
if (!destroyed) resolve3(data);
|
|
3832
|
+
});
|
|
3833
|
+
req.on("error", () => {
|
|
3834
|
+
if (!destroyed) resolve3("");
|
|
3835
|
+
});
|
|
3836
|
+
});
|
|
3837
|
+
}
|
|
3838
|
+
};
|
|
3839
|
+
|
|
3840
|
+
// src/core/topic-manager.ts
|
|
3841
|
+
var log10 = createChildLogger({ module: "topic-manager" });
|
|
3842
|
+
var TopicManager = class {
|
|
3843
|
+
constructor(sessionManager, adapter, systemTopicIds) {
|
|
3844
|
+
this.sessionManager = sessionManager;
|
|
3845
|
+
this.adapter = adapter;
|
|
3846
|
+
this.systemTopicIds = systemTopicIds;
|
|
3847
|
+
}
|
|
3848
|
+
listTopics(filter) {
|
|
3849
|
+
const records = this.sessionManager.listRecords(filter);
|
|
3850
|
+
return records.filter((r) => !this.isSystemTopic(r)).filter((r) => !filter?.statuses?.length || filter.statuses.includes(r.status)).map((r) => ({
|
|
3851
|
+
sessionId: r.sessionId,
|
|
3852
|
+
topicId: r.platform?.topicId ?? null,
|
|
3853
|
+
name: r.name ?? null,
|
|
3854
|
+
status: r.status,
|
|
3855
|
+
agentName: r.agentName,
|
|
3856
|
+
lastActiveAt: r.lastActiveAt
|
|
3857
|
+
}));
|
|
3858
|
+
}
|
|
3859
|
+
async deleteTopic(sessionId, options) {
|
|
3860
|
+
const records = this.sessionManager.listRecords();
|
|
3861
|
+
const record = records.find((r) => r.sessionId === sessionId);
|
|
3862
|
+
if (!record) return { ok: false, error: "Session not found" };
|
|
3863
|
+
if (this.isSystemTopic(record)) return { ok: false, error: "Cannot delete system topic" };
|
|
3864
|
+
const isActive = record.status === "active" || record.status === "initializing";
|
|
3865
|
+
if (isActive && !options?.confirmed) {
|
|
3866
|
+
return {
|
|
3867
|
+
ok: false,
|
|
3868
|
+
needsConfirmation: true,
|
|
3869
|
+
session: { id: record.sessionId, name: record.name ?? null, status: record.status }
|
|
3870
|
+
};
|
|
3871
|
+
}
|
|
3872
|
+
if (isActive) {
|
|
3873
|
+
await this.sessionManager.cancelSession(sessionId);
|
|
3874
|
+
}
|
|
3875
|
+
const topicId = record.platform?.topicId ?? null;
|
|
3876
|
+
if (this.adapter && topicId) {
|
|
3877
|
+
try {
|
|
3878
|
+
await this.adapter.deleteSessionThread(sessionId);
|
|
3879
|
+
} catch (err) {
|
|
3880
|
+
log10.warn({ err, sessionId, topicId }, "Failed to delete platform thread, removing record anyway");
|
|
3881
|
+
}
|
|
3882
|
+
}
|
|
3883
|
+
await this.sessionManager.removeRecord(sessionId);
|
|
3884
|
+
return { ok: true, topicId };
|
|
3885
|
+
}
|
|
3886
|
+
async cleanup(statuses) {
|
|
3887
|
+
const targetStatuses = statuses?.length ? statuses : ["finished", "error", "cancelled"];
|
|
3888
|
+
const records = this.sessionManager.listRecords({ statuses: targetStatuses });
|
|
3889
|
+
const targets = records.filter((r) => !this.isSystemTopic(r)).filter((r) => targetStatuses.includes(r.status));
|
|
3890
|
+
const deleted = [];
|
|
3891
|
+
const failed = [];
|
|
3892
|
+
for (const record of targets) {
|
|
3893
|
+
try {
|
|
3894
|
+
const isActive = record.status === "active" || record.status === "initializing";
|
|
3895
|
+
if (isActive) {
|
|
3896
|
+
await this.sessionManager.cancelSession(record.sessionId);
|
|
3897
|
+
}
|
|
3898
|
+
const topicId = record.platform?.topicId;
|
|
3899
|
+
if (this.adapter && topicId) {
|
|
3900
|
+
try {
|
|
3901
|
+
await this.adapter.deleteSessionThread(record.sessionId);
|
|
3902
|
+
} catch (err) {
|
|
3903
|
+
log10.warn({ err, sessionId: record.sessionId }, "Failed to delete platform thread during cleanup");
|
|
3904
|
+
}
|
|
3905
|
+
}
|
|
3906
|
+
await this.sessionManager.removeRecord(record.sessionId);
|
|
3907
|
+
deleted.push(record.sessionId);
|
|
3908
|
+
} catch (err) {
|
|
3909
|
+
failed.push({ sessionId: record.sessionId, error: err instanceof Error ? err.message : String(err) });
|
|
3910
|
+
}
|
|
3911
|
+
}
|
|
3912
|
+
return { deleted, failed };
|
|
3913
|
+
}
|
|
3914
|
+
isSystemTopic(record) {
|
|
3915
|
+
const topicId = record.platform?.topicId;
|
|
3916
|
+
if (!topicId) return false;
|
|
3917
|
+
return topicId === this.systemTopicIds.notificationTopicId || topicId === this.systemTopicIds.assistantTopicId;
|
|
3918
|
+
}
|
|
3919
|
+
};
|
|
3920
|
+
|
|
3921
|
+
export {
|
|
3922
|
+
nodeToWebWritable,
|
|
3923
|
+
nodeToWebReadable,
|
|
3924
|
+
StderrCapture,
|
|
3925
|
+
TypedEmitter,
|
|
3926
|
+
AgentInstance,
|
|
3927
|
+
AgentManager,
|
|
3928
|
+
PromptQueue,
|
|
3929
|
+
PermissionGate,
|
|
3930
|
+
Session,
|
|
3931
|
+
SessionManager,
|
|
3932
|
+
FileService,
|
|
3933
|
+
SessionBridge,
|
|
3934
|
+
NotificationManager,
|
|
3935
|
+
MessageTransformer,
|
|
3936
|
+
UsageStore,
|
|
3937
|
+
UsageBudget,
|
|
3938
|
+
SecurityGuard,
|
|
3939
|
+
SessionFactory,
|
|
3940
|
+
EventBus,
|
|
3941
|
+
SpeechService,
|
|
3942
|
+
GroqSTT,
|
|
3943
|
+
OpenACPCore,
|
|
3944
|
+
SSEManager,
|
|
3945
|
+
StaticServer,
|
|
3946
|
+
ApiServer,
|
|
3947
|
+
TopicManager
|
|
3948
|
+
};
|
|
3949
|
+
//# sourceMappingURL=chunk-FEWSQT3U.js.map
|