@openacp/cli 2026.330.3 → 2026.331.2

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