openfox 1.6.51 → 1.6.53

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 (29) hide show
  1. package/dist/{auto-compaction-VM4PWNSL.js → auto-compaction-NVHM75BN.js} +5 -5
  2. package/dist/{chat-handler-AQNAQSBE.js → chat-handler-DERM2S6L.js} +10 -12
  3. package/dist/{chunk-2IIJ6BX6.js → chunk-4MSEK56X.js} +3 -3
  4. package/dist/{chunk-G56V75F2.js → chunk-5STJLSGO.js} +2 -26
  5. package/dist/{chunk-CAWG7OPR.js → chunk-AFIVZZJN.js} +2 -2
  6. package/dist/{chunk-Y6HBEACI.js → chunk-CTAIXOZJ.js} +1 -1
  7. package/dist/{chunk-LAUS4KUS.js → chunk-DAUVWS5W.js} +26 -9
  8. package/dist/{chunk-6ZIAD3UH.js → chunk-JLMCJLTK.js} +102 -531
  9. package/dist/{chunk-QEFIFVTH.js → chunk-UQGY56XJ.js} +1 -1
  10. package/dist/{chunk-ADNH6OIQ.js → chunk-XRPGQKBM.js} +39 -4
  11. package/dist/cli/dev.js +1 -1
  12. package/dist/cli/index.js +1 -1
  13. package/dist/{events-RXX52D3D.js → events-UCHHTT6X.js} +2 -2
  14. package/dist/{orchestrator-FPX4NLIZ.js → orchestrator-FX6SZX4J.js} +6 -6
  15. package/dist/package.json +4 -3
  16. package/dist/{processor-AJ6F6SA6.js → processor-AS6JXF4U.js} +8 -10
  17. package/dist/{protocol-_A3Upt5b.d.ts → protocol-Cmn48nDH.d.ts} +4 -27
  18. package/dist/{protocol-4RE3E3H3.js → protocol-WHHYESPI.js} +3 -15
  19. package/dist/{serve-K56IPLYD.js → serve-W3EZMXAC.js} +7 -8
  20. package/dist/server/index.d.ts +1 -1
  21. package/dist/server/index.js +6 -7
  22. package/dist/shared/index.d.ts +2 -2
  23. package/dist/shared/index.js +1 -1
  24. package/dist/{tools-SBBC6TWC.js → tools-SJN7IGVF.js} +5 -5
  25. package/dist/web/assets/{index--Frce5_n.js → index-Bet4PbsC.js} +65 -65
  26. package/dist/web/index.html +1 -1
  27. package/dist/web/sw.js +1 -1
  28. package/package.json +4 -3
  29. package/dist/chunk-LUEMWIT4.js +0 -44
@@ -1,19 +1,13 @@
1
- import {
2
- generateSessionName,
3
- needsNameGeneration
4
- } from "./chunk-ADNH6OIQ.js";
5
1
  import {
6
2
  createVerifierNudgeConfig,
7
3
  runBuilderTurn,
8
4
  runChatTurn
9
- } from "./chunk-2IIJ6BX6.js";
5
+ } from "./chunk-4MSEK56X.js";
10
6
  import {
11
7
  TurnMetrics,
12
8
  agentExists,
13
- assembleAgentRequest,
14
9
  cancelPathConfirmationsForSession,
15
10
  checkAborted,
16
- createChatDoneEvent,
17
11
  createMessageStartEvent,
18
12
  createToolRegistry,
19
13
  deleteAgent,
@@ -22,13 +16,11 @@ import {
22
16
  executeSubAgent,
23
17
  findAgentById,
24
18
  findSkillById,
25
- getAllInstructions,
26
19
  getDefaultAgentContent,
27
20
  getDefaultAgentIds,
28
21
  getDefaultIds,
29
22
  getDefaultSkillContent,
30
23
  getDefaultSkillIds,
31
- getEnabledSkillMetadata,
32
24
  getToolRegistryForAgent,
33
25
  isSkillEnabled,
34
26
  loadAllAgents,
@@ -39,7 +31,6 @@ import {
39
31
  loadItemsFromDir,
40
32
  loadUserAgents,
41
33
  loadUserSkills,
42
- maybeAutoCompactContext,
43
34
  pathExists,
44
35
  performManualContextCompaction,
45
36
  saveAgent,
@@ -47,7 +38,7 @@ import {
47
38
  setSkillEnabled,
48
39
  skillExists,
49
40
  spawnShellProcess
50
- } from "./chunk-LAUS4KUS.js";
41
+ } from "./chunk-DAUVWS5W.js";
51
42
  import {
52
43
  getPathSeparator,
53
44
  getPlatformShell,
@@ -97,9 +88,8 @@ import {
97
88
  updateSessionProvider,
98
89
  updateSessionRunning,
99
90
  updateSessionSummary
100
- } from "./chunk-QEFIFVTH.js";
91
+ } from "./chunk-UQGY56XJ.js";
101
92
  import {
102
- buildContextMessagesFromEventHistory,
103
93
  buildMessagesFromStoredEvents,
104
94
  foldPendingConfirmations
105
95
  } from "./chunk-LIMBYVO4.js";
@@ -108,17 +98,15 @@ import {
108
98
  createChatMessageMessage,
109
99
  createContextStateMessage,
110
100
  createErrorMessage,
111
- createPhaseChangedMessage,
112
101
  createQueueStateMessage,
113
102
  createSessionRunningMessage,
114
103
  createSessionStateMessage,
115
104
  isAskAnswerPayload,
116
- isChatSendPayload,
117
105
  isSessionLoadPayload,
118
106
  parseClientMessage,
119
107
  serializeServerMessage,
120
108
  storedEventToServerMessage
121
- } from "./chunk-G56V75F2.js";
109
+ } from "./chunk-5STJLSGO.js";
122
110
  import {
123
111
  EventEmitter,
124
112
  cancelQuestionsForSession,
@@ -132,7 +120,7 @@ import {
132
120
  } from "./chunk-B7E3BICY.js";
133
121
  import {
134
122
  createServerMessage
135
- } from "./chunk-Y6HBEACI.js";
123
+ } from "./chunk-CTAIXOZJ.js";
136
124
  import {
137
125
  getGlobalConfigDir
138
126
  } from "./chunk-R4HADRYO.js";
@@ -2006,81 +1994,6 @@ async function runOrchestrator(options) {
2006
1994
  return executeWorkflow(workflow, options);
2007
1995
  }
2008
1996
 
2009
- // src/server/session/summary-generator.ts
2010
- var SUMMARY_INSTRUCTION = "Write a 2-3 sentence summary of what the user wants to accomplish. Focus on WHAT and WHY, not HOW. Output only the summary, no preamble.";
2011
- async function generateSessionSummary(options) {
2012
- const { messages, llmClient, workdir, customInstructions, skills } = options;
2013
- try {
2014
- const messagesText = messages.map((m) => `${m.role}: ${m.content}`).join("\n");
2015
- const userPrompt = `${SUMMARY_INSTRUCTION}
2016
-
2017
- ## Conversation History
2018
- ${messagesText}
2019
-
2020
- ## Summary`;
2021
- const contextMessages = [
2022
- {
2023
- role: "user",
2024
- content: userPrompt,
2025
- source: "history"
2026
- }
2027
- ];
2028
- const mockAgentDef = {
2029
- metadata: {
2030
- id: "summary",
2031
- name: "Summary",
2032
- description: "Session summary generator",
2033
- subagent: false,
2034
- allowedTools: []
2035
- },
2036
- prompt: SUMMARY_INSTRUCTION
2037
- };
2038
- const assembledRequest = assembleAgentRequest({
2039
- agentDef: mockAgentDef,
2040
- workdir,
2041
- messages: contextMessages,
2042
- injectedFiles: [],
2043
- ...customInstructions ? { customInstructions } : {},
2044
- ...skills ? { skills } : {},
2045
- promptTools: [],
2046
- toolChoice: "none",
2047
- disableThinking: true
2048
- });
2049
- const llmMessages = assembledRequest.messages.map((msg) => ({
2050
- role: msg.role,
2051
- content: msg.content
2052
- }));
2053
- const response = await llmClient.complete({
2054
- messages: llmMessages,
2055
- tools: [],
2056
- signal: AbortSignal.timeout(6e4),
2057
- disableThinking: true
2058
- });
2059
- let summary = response.content.trim();
2060
- if (summary.length > 500) {
2061
- summary = summary.substring(0, 497) + "...";
2062
- }
2063
- if (!summary || summary.length < 10) {
2064
- return {
2065
- success: false,
2066
- error: "Generated summary is too short or empty"
2067
- };
2068
- }
2069
- return {
2070
- success: true,
2071
- summary
2072
- };
2073
- } catch (error) {
2074
- return {
2075
- success: false,
2076
- error: error instanceof Error ? error.message : "Unknown error generating summary"
2077
- };
2078
- }
2079
- }
2080
- function needsSummaryGeneration(sessionSummary) {
2081
- return sessionSummary === null || sessionSummary.trim() === "";
2082
- }
2083
-
2084
1997
  // src/server/auth.ts
2085
1998
  import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2 } from "fs/promises";
2086
1999
  import { join as join2, dirname as dirname2 } from "path";
@@ -2206,24 +2119,6 @@ async function isValidToken(token) {
2206
2119
  }
2207
2120
 
2208
2121
  // src/server/ws/server.ts
2209
- function getCurrentWindowMessageOptions2(sessionId) {
2210
- const contextWindowId = getCurrentContextWindowId(sessionId);
2211
- return contextWindowId ? { contextWindowId } : void 0;
2212
- }
2213
- function getSessionMessageCount(sessionId) {
2214
- const eventStore = getEventStore();
2215
- const events = eventStore.getEvents(sessionId);
2216
- let count = 0;
2217
- for (const event of events) {
2218
- if (event.type === "message.start") {
2219
- const data = event.data;
2220
- if (data.role === "user") {
2221
- count++;
2222
- }
2223
- }
2224
- }
2225
- return count;
2226
- }
2227
2122
  function resolveStatsIdentity(llmClient, getActiveProvider) {
2228
2123
  const provider = getActiveProvider?.();
2229
2124
  const model = llmClient.getModel();
@@ -2235,6 +2130,45 @@ function resolveStatsIdentity(llmClient, getActiveProvider) {
2235
2130
  model
2236
2131
  };
2237
2132
  }
2133
+ function buildSessionState(sessionManager, sessionId) {
2134
+ const session = sessionManager.getSession(sessionId);
2135
+ if (!session) {
2136
+ return { session: null, messages: [], pendingConfirmations: [] };
2137
+ }
2138
+ const eventStore = getEventStore();
2139
+ const events = eventStore.getEvents(sessionId);
2140
+ const messages = events.length > 0 ? buildMessagesFromStoredEvents(events) : [];
2141
+ const pendingConfirmations = foldPendingConfirmations(events);
2142
+ return { session, messages, pendingConfirmations };
2143
+ }
2144
+ function addUserMessageAndBroadcast(sessionManager, sessionId, message, broadcastFn) {
2145
+ const userMessage = sessionManager.addMessage(sessionId, {
2146
+ role: "user",
2147
+ content: message.content,
2148
+ ...message.attachments ? { attachments: message.attachments } : {},
2149
+ ...message.messageKind ? { messageKind: message.messageKind } : {}
2150
+ });
2151
+ broadcastFn(sessionId, createChatMessageMessage(userMessage));
2152
+ return userMessage;
2153
+ }
2154
+ function processQueueAndRestartTurn(sessionManager, sessionId, drainFn, queueMode, broadcastFn, activeAgents2, startTurnFn, queueMessageFn) {
2155
+ const messages = drainFn(sessionId);
2156
+ const next = messages[0];
2157
+ if (!next) return false;
2158
+ for (const remaining of messages.slice(1)) {
2159
+ if (queueMessageFn) {
2160
+ queueMessageFn(sessionId, queueMode, remaining.content, remaining.attachments, remaining.messageKind);
2161
+ } else {
2162
+ sessionManager.queueMessage(sessionId, queueMode, remaining.content, remaining.attachments);
2163
+ }
2164
+ }
2165
+ broadcastFn(sessionId, createQueueStateMessage(sessionManager.getQueueState(sessionId)));
2166
+ addUserMessageAndBroadcast(sessionManager, sessionId, { content: next.content, ...next.attachments ? { attachments: next.attachments } : {}, ...next.messageKind ? { messageKind: next.messageKind } : {} }, broadcastFn);
2167
+ const newController = new AbortController();
2168
+ activeAgents2.set(sessionId, newController);
2169
+ startTurnFn(sessionId, newController);
2170
+ return true;
2171
+ }
2238
2172
  var activeAgents = /* @__PURE__ */ new Map();
2239
2173
  function createWebSocketServer(httpServer, config, getLLMClient, getActiveProvider, sessionManager, providerManager) {
2240
2174
  const wss = new WebSocketServer({ server: httpServer });
@@ -2302,6 +2236,43 @@ function createWebSocketServer(httpServer, config, getLLMClient, getActiveProvid
2302
2236
  };
2303
2237
  const llmForSession = (sessionId) => getSessionLLMClient?.(sessionId) ?? getLLMClient();
2304
2238
  const statsForSession = (sessionId) => getSessionStatsIdentity?.(sessionId) ?? resolveStatsIdentity(getLLMClient(), getActiveProvider);
2239
+ function cleanupAfterTurn(sessionId, controller, sendFn, setRunningOnEarlyReturn) {
2240
+ if (activeAgents.get(sessionId) !== controller) {
2241
+ return;
2242
+ }
2243
+ activeAgents.delete(sessionId);
2244
+ const processed = processQueueAndRestartTurn(
2245
+ sessionManager,
2246
+ sessionId,
2247
+ (sid) => sessionManager.drainAsapMessages(sid),
2248
+ "asap",
2249
+ sendFn,
2250
+ activeAgents,
2251
+ startTurnWithCompletionChain,
2252
+ (sid, mode, content, attachments, messageKind) => sessionManager.queueMessage(sid, mode, content, attachments, messageKind)
2253
+ );
2254
+ if (processed) {
2255
+ if (setRunningOnEarlyReturn) sessionManager.setRunning(sessionId, false);
2256
+ return;
2257
+ }
2258
+ const processedCompletion = processQueueAndRestartTurn(
2259
+ sessionManager,
2260
+ sessionId,
2261
+ (sid) => sessionManager.drainCompletionMessages(sid),
2262
+ "completion",
2263
+ sendFn,
2264
+ activeAgents,
2265
+ startTurnWithCompletionChain
2266
+ );
2267
+ if (processedCompletion) {
2268
+ if (setRunningOnEarlyReturn) sessionManager.setRunning(sessionId, false);
2269
+ return;
2270
+ }
2271
+ sessionManager.clearMessageQueue(sessionId);
2272
+ sessionManager.setRunning(sessionId, false);
2273
+ const contextState = sessionManager.getContextState(sessionId);
2274
+ sendFn(sessionId, createContextStateMessage(contextState));
2275
+ }
2305
2276
  function startTurnWithCompletionChain(sessionId, controller) {
2306
2277
  runChatTurn({
2307
2278
  sessionManager,
@@ -2316,51 +2287,7 @@ function createWebSocketServer(httpServer, config, getLLMClient, getActiveProvid
2316
2287
  }
2317
2288
  logger.error("Chat turn error", { error });
2318
2289
  }).finally(() => {
2319
- if (activeAgents.get(sessionId) !== controller) {
2320
- return;
2321
- }
2322
- activeAgents.delete(sessionId);
2323
- const asapMsgs = sessionManager.drainAsapMessages(sessionId);
2324
- const nextAsap = asapMsgs[0];
2325
- if (nextAsap) {
2326
- for (const remaining of asapMsgs.slice(1)) {
2327
- sessionManager.queueMessage(sessionId, "asap", remaining.content, remaining.attachments, remaining.messageKind);
2328
- }
2329
- broadcastForSession(sessionId, createQueueStateMessage(sessionManager.getQueueState(sessionId)));
2330
- const userMessagePayload = {
2331
- role: "user",
2332
- content: nextAsap.content,
2333
- ...nextAsap.attachments ? { attachments: nextAsap.attachments } : {}
2334
- };
2335
- const userMessage = sessionManager.addMessage(sessionId, userMessagePayload);
2336
- broadcastForSession(sessionId, createChatMessageMessage(userMessage));
2337
- const newController = new AbortController();
2338
- activeAgents.set(sessionId, newController);
2339
- startTurnWithCompletionChain(sessionId, newController);
2340
- return;
2341
- }
2342
- const completionMsgs = sessionManager.drainCompletionMessages(sessionId);
2343
- const next = completionMsgs[0];
2344
- if (next) {
2345
- for (const remaining of completionMsgs.slice(1)) {
2346
- sessionManager.queueMessage(sessionId, "completion", remaining.content, remaining.attachments);
2347
- }
2348
- broadcastForSession(sessionId, createQueueStateMessage(sessionManager.getQueueState(sessionId)));
2349
- const userMessage = sessionManager.addMessage(sessionId, {
2350
- role: "user",
2351
- content: next.content,
2352
- ...next.attachments ? { attachments: next.attachments } : {}
2353
- });
2354
- broadcastForSession(sessionId, createChatMessageMessage(userMessage));
2355
- const newController = new AbortController();
2356
- activeAgents.set(sessionId, newController);
2357
- startTurnWithCompletionChain(sessionId, newController);
2358
- return;
2359
- }
2360
- sessionManager.clearMessageQueue(sessionId);
2361
- sessionManager.setRunning(sessionId, false);
2362
- const contextState = sessionManager.getContextState(sessionId);
2363
- broadcastForSession(sessionId, createContextStateMessage(contextState));
2290
+ cleanupAfterTurn(sessionId, controller, broadcastForSession, false);
2364
2291
  });
2365
2292
  }
2366
2293
  function triggerQueueProcessing(sessionId) {
@@ -2381,13 +2308,7 @@ function createWebSocketServer(httpServer, config, getLLMClient, getActiveProvid
2381
2308
  const nextAsap = queue.find((m) => m.mode === "asap") ?? queue[0];
2382
2309
  if (nextAsap) {
2383
2310
  sessionManager.cancelQueuedMessage(sessionId, nextAsap.queueId);
2384
- const userMessage = sessionManager.addMessage(sessionId, {
2385
- role: "user",
2386
- content: nextAsap.content,
2387
- ...nextAsap.attachments ? { attachments: nextAsap.attachments } : {},
2388
- ...nextAsap.messageKind ? { messageKind: nextAsap.messageKind } : {}
2389
- });
2390
- broadcastForSession(sessionId, createChatMessageMessage(userMessage));
2311
+ addUserMessageAndBroadcast(sessionManager, sessionId, { content: nextAsap.content, ...nextAsap.attachments ? { attachments: nextAsap.attachments } : {}, ...nextAsap.messageKind ? { messageKind: nextAsap.messageKind } : {} }, broadcastForSession);
2391
2312
  }
2392
2313
  startTurnWithCompletionChain(sessionId, controller);
2393
2314
  return true;
@@ -2400,22 +2321,15 @@ function createWebSocketServer(httpServer, config, getLLMClient, getActiveProvid
2400
2321
  if (event.type === "session_created") {
2401
2322
  const session = sessionManager.getSession(sessionId);
2402
2323
  if (session) {
2403
- const eventStore = getEventStore();
2404
- const events = eventStore.getEvents(sessionId);
2405
- const messages = events.length > 0 ? buildMessagesFromStoredEvents(events) : [];
2406
- const pendingConfirmations = foldPendingConfirmations(events);
2324
+ const { messages, pendingConfirmations } = buildSessionState(sessionManager, sessionId);
2407
2325
  ws.send(serializeServerMessage({ ...createSessionStateMessage(session, messages, pendingConfirmations), sessionId }));
2408
2326
  }
2409
2327
  continue;
2410
2328
  }
2411
2329
  if (isSubscribedToSession(client, sessionId)) {
2412
2330
  if (event.type === "session_updated") {
2413
- const session = sessionManager.getSession(sessionId);
2331
+ const { session, messages, pendingConfirmations } = buildSessionState(sessionManager, sessionId);
2414
2332
  if (session) {
2415
- const eventStore = getEventStore();
2416
- const events = eventStore.getEvents(sessionId);
2417
- const messages = events.length > 0 ? buildMessagesFromStoredEvents(events) : [];
2418
- const pendingConfirmations = foldPendingConfirmations(events);
2419
2333
  ws.send(serializeServerMessage({ ...createSessionStateMessage(session, messages, pendingConfirmations), sessionId }));
2420
2334
  }
2421
2335
  }
@@ -2500,7 +2414,7 @@ function createWebSocketServer(httpServer, config, getLLMClient, getActiveProvid
2500
2414
  }
2501
2415
  const client = clients.get(ws);
2502
2416
  try {
2503
- await handleClientMessage(ws, client, message, getLLMClient, getActiveProvider, sessionManager, broadcastForSession, providerManager, getSessionLLMClient, getSessionStatsIdentity, llmForSession, statsForSession, startTurnWithCompletionChain);
2417
+ await handleClientMessage(ws, client, message, getLLMClient, getActiveProvider, sessionManager, broadcastForSession, providerManager, getSessionLLMClient, getSessionStatsIdentity, llmForSession, statsForSession, startTurnWithCompletionChain, cleanupAfterTurn);
2504
2418
  } catch (error) {
2505
2419
  logger.error("Error handling client message", { error, type: message.type });
2506
2420
  ws.send(serializeServerMessage(
@@ -2540,7 +2454,7 @@ function createWebSocketServer(httpServer, config, getLLMClient, getActiveProvid
2540
2454
  broadcastForSession
2541
2455
  };
2542
2456
  }
2543
- async function handleClientMessage(ws, client, message, getLLMClient, getActiveProvider, sessionManager, broadcastForSession, providerManager, getSessionLLMClient, getSessionStatsIdentity, llmForSession, statsForSession, startTurnWithCompletionChain) {
2457
+ async function handleClientMessage(ws, client, message, getLLMClient, getActiveProvider, sessionManager, broadcastForSession, providerManager, getSessionLLMClient, getSessionStatsIdentity, llmForSession, statsForSession, startTurnWithCompletionChain, cleanupAfterTurn) {
2544
2458
  const send = (msg) => {
2545
2459
  if (ws.readyState === WebSocket2.OPEN) {
2546
2460
  ws.send(serializeServerMessage(msg));
@@ -2616,308 +2530,6 @@ async function handleClientMessage(ws, client, message, getLLMClient, getActiveP
2616
2530
  break;
2617
2531
  }
2618
2532
  // =========================================================================
2619
- // Unified Chat (replaces plan.message, agent.start, etc.) - WS REQUIRED
2620
- // =========================================================================
2621
- case "chat.send": {
2622
- if (!client.activeSessionId) {
2623
- send(createErrorMessage("NO_SESSION", "No active session", message.id));
2624
- return;
2625
- }
2626
- if (!isChatSendPayload(message.payload)) {
2627
- send(createErrorMessage("INVALID_PAYLOAD", "Invalid chat.send payload", message.id));
2628
- return;
2629
- }
2630
- const currentSession = sessionManager.requireSession(client.activeSessionId);
2631
- if (currentSession.isRunning) {
2632
- send(createErrorMessage("ALREADY_RUNNING", "Session is already running", message.id));
2633
- return;
2634
- }
2635
- if (currentSession.phase === "blocked") {
2636
- logger.info("User intervention - resetting blocked state", { sessionId: client.activeSessionId });
2637
- sessionManager.setPhase(client.activeSessionId, "build");
2638
- sessionManager.resetAllCriteriaAttempts(client.activeSessionId);
2639
- sendForSession(client.activeSessionId, createPhaseChangedMessage("build"));
2640
- }
2641
- const sessionId = client.activeSessionId;
2642
- const eventStore = getEventStore();
2643
- ensureEventStoreSubscription(sessionId);
2644
- const controller = new AbortController();
2645
- const existingController = activeAgents.get(sessionId);
2646
- if (existingController) {
2647
- logger.warn("Aborting existing agent before starting new one", { sessionId });
2648
- existingController.abort();
2649
- }
2650
- activeAgents.set(sessionId, controller);
2651
- sessionManager.setRunning(sessionId, true);
2652
- sendForSession(sessionId, createSessionRunningMessage(true));
2653
- send({ type: "ack", payload: {}, id: message.id });
2654
- try {
2655
- await maybeAutoCompactContext({
2656
- sessionManager,
2657
- sessionId,
2658
- llmClient: llmForSession(sessionId),
2659
- statsIdentity: statsForSession(sessionId),
2660
- signal: controller.signal
2661
- });
2662
- if (controller.signal.aborted) {
2663
- break;
2664
- }
2665
- const userMessage = sessionManager.addMessage(sessionId, {
2666
- role: "user",
2667
- content: message.payload.content,
2668
- ...message.payload.attachments && { attachments: message.payload.attachments },
2669
- ...message.payload.messageKind && { messageKind: message.payload.messageKind },
2670
- ...message.payload.isSystemGenerated && { isSystemGenerated: message.payload.isSystemGenerated }
2671
- });
2672
- sendForSession(sessionId, createChatMessageMessage(userMessage));
2673
- const messageCount = getSessionMessageCount(sessionId);
2674
- if (needsNameGeneration(currentSession.metadata.title, messageCount)) {
2675
- generateSessionName({
2676
- userMessage: message.payload.content,
2677
- llmClient: llmForSession(sessionId),
2678
- signal: controller.signal
2679
- }).then(async (result) => {
2680
- if (result.success && result.name) {
2681
- updateSessionMetadata(sessionId, { title: result.name });
2682
- eventStore.append(sessionId, {
2683
- type: "session.name_generated",
2684
- data: { name: result.name }
2685
- });
2686
- const updatedSession = sessionManager.getSession(sessionId);
2687
- if (updatedSession) {
2688
- const events = eventStore.getEvents(sessionId);
2689
- const messages = buildMessagesFromStoredEvents(events);
2690
- const pendingConfirmations = foldPendingConfirmations(events);
2691
- broadcastForSession(sessionId, createSessionStateMessage(updatedSession, messages, pendingConfirmations));
2692
- }
2693
- logger.info("Session name generated", { sessionId, name: result.name });
2694
- }
2695
- }).catch((error) => {
2696
- logger.warn("Session name generation failed", { sessionId, error: error instanceof Error ? error.message : error });
2697
- });
2698
- }
2699
- startTurnWithCompletionChain(sessionId, controller);
2700
- } catch (error) {
2701
- if (activeAgents.get(sessionId) === controller) {
2702
- activeAgents.delete(sessionId);
2703
- }
2704
- sessionManager.setRunning(sessionId, false);
2705
- sendForSession(sessionId, createSessionRunningMessage(false));
2706
- const contextState = sessionManager.getContextState(sessionId);
2707
- sendForSession(sessionId, createContextStateMessage(contextState));
2708
- if (!(error instanceof Error && error.message === "Aborted")) {
2709
- logger.error("Chat send pre-turn error", { sessionId, error });
2710
- }
2711
- }
2712
- break;
2713
- }
2714
- case "chat.stop": {
2715
- send(createErrorMessage("DEPRECATED", "chat.stop removed. Use REST API: POST /api/sessions/:id/stop", message.id));
2716
- break;
2717
- }
2718
- // =========================================================================
2719
- // Message Queue
2720
- // =========================================================================
2721
- case "queue.asap": {
2722
- send(createErrorMessage("DEPRECATED", "queue.asap removed. Use REST API: POST /api/sessions/:id/queue/asap", message.id));
2723
- break;
2724
- }
2725
- case "queue.completion": {
2726
- send(createErrorMessage("DEPRECATED", "queue.completion removed. Use REST API: POST /api/sessions/:id/queue/completion", message.id));
2727
- break;
2728
- }
2729
- case "queue.cancel": {
2730
- send(createErrorMessage("DEPRECATED", "queue.cancel removed. Use REST API: DELETE /api/sessions/:id/queue/:queueId", message.id));
2731
- break;
2732
- }
2733
- case "chat.continue": {
2734
- send(createErrorMessage("DEPRECATED", "chat.continue removed. Use REST API: POST /api/sessions/:id/continue", message.id));
2735
- break;
2736
- }
2737
- // =========================================================================
2738
- // Mode Switching
2739
- // =========================================================================
2740
- case "mode.switch": {
2741
- send(createErrorMessage("DEPRECATED", "mode.switch removed. Use REST API: PUT /api/sessions/:id/mode", message.id));
2742
- break;
2743
- }
2744
- case "mode.accept": {
2745
- if (!client.activeSessionId) {
2746
- send(createErrorMessage("NO_SESSION", "No active session", message.id));
2747
- return;
2748
- }
2749
- const session = sessionManager.requireSession(client.activeSessionId);
2750
- const acceptPayload = message.payload;
2751
- if (session.isRunning) {
2752
- const content = acceptPayload?.content ?? "";
2753
- const attachments = acceptPayload?.attachments;
2754
- const workflowId = acceptPayload?.workflowId;
2755
- let fullContent = content;
2756
- if (workflowId) {
2757
- const workflowInfo = `// Workflow: ${workflowId}`;
2758
- fullContent = content ? `${workflowInfo}
2759
-
2760
- ${content}` : workflowInfo;
2761
- }
2762
- sessionManager.queueMessage(client.activeSessionId, "asap", fullContent, attachments, "workflow-accept");
2763
- const queueState = sessionManager.getQueueState(client.activeSessionId);
2764
- send({
2765
- type: "queue.state",
2766
- payload: { success: true, queueState },
2767
- id: message.id
2768
- });
2769
- return;
2770
- }
2771
- const acceptPayloadEarly = message.payload;
2772
- if (!acceptPayloadEarly?.workflowId && session.criteria.length === 0) {
2773
- send(createErrorMessage("NO_CRITERIA", "Cannot accept: no criteria defined", message.id));
2774
- return;
2775
- }
2776
- const sessionId = client.activeSessionId;
2777
- const eventStore = getEventStore();
2778
- send({ type: "ack", payload: {}, id: message.id });
2779
- sessionManager.setRunning(sessionId, true);
2780
- eventStore.append(sessionId, { type: "running.changed", data: { isRunning: true } });
2781
- sendForSession(sessionId, createSessionRunningMessage(true));
2782
- const currentSession = sessionManager.requireSession(sessionId);
2783
- if (needsSummaryGeneration(currentSession.summary)) {
2784
- const events = eventStore.getEvents(sessionId);
2785
- const nonSystemEvents = events.filter((event) => {
2786
- if (event.type !== "message.start") return true;
2787
- return event.data.isSystemGenerated !== true;
2788
- });
2789
- const contextMessages = buildContextMessagesFromEventHistory(nonSystemEvents);
2790
- const summaryMessages = contextMessages.filter((m) => m.role === "user" || m.role === "assistant").map((m) => ({ role: m.role, content: m.content }));
2791
- if (summaryMessages.length > 0) {
2792
- const config = getRuntimeConfig();
2793
- const configDir = getGlobalConfigDir(config.mode ?? "production");
2794
- const skills = await getEnabledSkillMetadata(configDir);
2795
- const { content: instructions } = await getAllInstructions(currentSession.workdir, currentSession.projectId);
2796
- generateSessionSummary({
2797
- messages: summaryMessages,
2798
- llmClient: llmForSession(sessionId),
2799
- workdir: currentSession.workdir,
2800
- customInstructions: instructions || void 0,
2801
- skills
2802
- }).then(async (result) => {
2803
- if (result.success && result.summary) {
2804
- sessionManager.setSummary(sessionId, result.summary);
2805
- }
2806
- }).catch((error) => {
2807
- logger.warn("Session summary generation failed", { sessionId, error: error instanceof Error ? error.message : error });
2808
- });
2809
- }
2810
- }
2811
- ;
2812
- (async () => {
2813
- let controller = null;
2814
- try {
2815
- sessionManager.setMode(sessionId, "builder");
2816
- sessionManager.setPhase(sessionId, "build");
2817
- eventStore.append(sessionId, { type: "mode.changed", data: { mode: "builder", auto: false, reason: "Criteria accepted" } });
2818
- eventStore.append(sessionId, { type: "phase.changed", data: { phase: "build" } });
2819
- controller = new AbortController();
2820
- const existingController = activeAgents.get(sessionId);
2821
- if (existingController) {
2822
- logger.warn("Aborting existing agent before starting new one", { sessionId });
2823
- existingController.abort();
2824
- }
2825
- activeAgents.set(sessionId, controller);
2826
- const acceptPayload2 = message.payload;
2827
- const acceptAttachments = acceptPayload2?.attachments;
2828
- const hasAcceptContent = acceptPayload2?.content && typeof acceptPayload2.content === "string" && acceptPayload2.content.trim();
2829
- const hasAcceptAttachments = acceptAttachments && acceptAttachments.length > 0;
2830
- const hasAcceptMessage = hasAcceptContent || hasAcceptAttachments;
2831
- await runOrchestrator({
2832
- sessionManager,
2833
- sessionId,
2834
- llmClient: llmForSession(sessionId),
2835
- statsIdentity: statsForSession(sessionId),
2836
- injectBuilderKickoff: !hasAcceptMessage,
2837
- ...acceptPayload2?.workflowId ? { workflowId: acceptPayload2.workflowId } : {},
2838
- ...hasAcceptMessage ? { userMessage: { content: hasAcceptContent ? acceptPayload2.content : "", ...hasAcceptAttachments ? { attachments: acceptAttachments } : {} } } : {},
2839
- signal: controller.signal,
2840
- onMessage: (msg) => sendForSession(sessionId, msg)
2841
- // For path confirmation dialogs
2842
- });
2843
- } catch (error) {
2844
- if (error instanceof Error && error.message === "Aborted") {
2845
- return;
2846
- }
2847
- logger.error("mode.accept error", { error });
2848
- eventStore.append(sessionId, {
2849
- type: "chat.error",
2850
- data: {
2851
- error: error instanceof Error ? error.message : "Unknown error",
2852
- recoverable: false
2853
- }
2854
- });
2855
- const errorMsgId = crypto.randomUUID();
2856
- eventStore.append(sessionId, createMessageStartEvent(errorMsgId, "user", `Error: ${error instanceof Error ? error.message : "Unknown error"}`, {
2857
- ...getCurrentWindowMessageOptions2(sessionId) ?? {},
2858
- isSystemGenerated: true,
2859
- messageKind: "correction"
2860
- }));
2861
- eventStore.append(sessionId, { type: "message.done", data: { messageId: errorMsgId } });
2862
- eventStore.append(sessionId, createChatDoneEvent(errorMsgId, "error"));
2863
- } finally {
2864
- if (!controller || activeAgents.get(sessionId) !== controller) {
2865
- return;
2866
- }
2867
- activeAgents.delete(sessionId);
2868
- const completionMsgs = sessionManager.drainCompletionMessages(sessionId);
2869
- const nextCompletion = completionMsgs[0];
2870
- if (nextCompletion) {
2871
- for (const remaining of completionMsgs.slice(1)) {
2872
- sessionManager.queueMessage(sessionId, "completion", remaining.content, remaining.attachments);
2873
- }
2874
- sendForSession(sessionId, createQueueStateMessage(sessionManager.getQueueState(sessionId)));
2875
- const userMessage = sessionManager.addMessage(sessionId, {
2876
- role: "user",
2877
- content: nextCompletion.content,
2878
- ...nextCompletion.attachments ? { attachments: nextCompletion.attachments } : {}
2879
- });
2880
- sendForSession(sessionId, createChatMessageMessage(userMessage));
2881
- const newController = new AbortController();
2882
- activeAgents.set(sessionId, newController);
2883
- startTurnWithCompletionChain(sessionId, newController);
2884
- return;
2885
- }
2886
- const asapMsgs = sessionManager.drainAsapMessages(sessionId);
2887
- const nextAsap = asapMsgs[0];
2888
- if (nextAsap) {
2889
- for (const remaining of asapMsgs.slice(1)) {
2890
- sessionManager.queueMessage(sessionId, "asap", remaining.content, remaining.attachments, remaining.messageKind);
2891
- }
2892
- sendForSession(sessionId, createQueueStateMessage(sessionManager.getQueueState(sessionId)));
2893
- const userMessage = sessionManager.addMessage(sessionId, {
2894
- role: "user",
2895
- content: nextAsap.content,
2896
- ...nextAsap.attachments ? { attachments: nextAsap.attachments } : {}
2897
- });
2898
- sendForSession(sessionId, createChatMessageMessage(userMessage));
2899
- const newerController = new AbortController();
2900
- activeAgents.set(sessionId, newerController);
2901
- startTurnWithCompletionChain(sessionId, newerController);
2902
- return;
2903
- }
2904
- sessionManager.clearMessageQueue(sessionId);
2905
- sessionManager.setRunning(sessionId, false);
2906
- eventStore.append(sessionId, { type: "running.changed", data: { isRunning: false } });
2907
- const contextState = sessionManager.getContextState(sessionId);
2908
- sendForSession(sessionId, createContextStateMessage(contextState));
2909
- }
2910
- })();
2911
- break;
2912
- }
2913
- // =========================================================================
2914
- // Criteria Editing
2915
- // =========================================================================
2916
- case "criteria.edit": {
2917
- send(createErrorMessage("DEPRECATED", "criteria.edit removed. Use REST API: PUT /api/sessions/:id/criteria", message.id));
2918
- break;
2919
- }
2920
- // =========================================================================
2921
2533
  // Context Management
2922
2534
  // =========================================================================
2923
2535
  case "context.compact": {
@@ -3041,48 +2653,7 @@ ${content}` : workflowInfo;
3041
2653
  }
3042
2654
  logger.error("Runner error", { error, sessionId });
3043
2655
  }).finally(() => {
3044
- if (activeAgents.get(sessionId) !== controller) {
3045
- return;
3046
- }
3047
- activeAgents.delete(sessionId);
3048
- const asapMsgs = sessionManager.drainAsapMessages(sessionId);
3049
- const nextAsap = asapMsgs[0];
3050
- if (nextAsap) {
3051
- for (const remaining of asapMsgs.slice(1)) {
3052
- sessionManager.queueMessage(sessionId, "asap", remaining.content, remaining.attachments, remaining.messageKind);
3053
- }
3054
- sendForSession(sessionId, createQueueStateMessage(sessionManager.getQueueState(sessionId)));
3055
- const userMessage = sessionManager.addMessage(sessionId, {
3056
- role: "user",
3057
- content: nextAsap.content,
3058
- ...nextAsap.attachments ? { attachments: nextAsap.attachments } : {}
3059
- });
3060
- sendForSession(sessionId, createChatMessageMessage(userMessage));
3061
- const newerController = new AbortController();
3062
- activeAgents.set(sessionId, newerController);
3063
- startTurnWithCompletionChain(sessionId, newerController);
3064
- return;
3065
- }
3066
- const completionMsgs = sessionManager.drainCompletionMessages(sessionId);
3067
- const nextCompletion = completionMsgs[0];
3068
- if (nextCompletion) {
3069
- for (const remaining of completionMsgs.slice(1)) {
3070
- sessionManager.queueMessage(sessionId, "completion", remaining.content, remaining.attachments);
3071
- }
3072
- sendForSession(sessionId, createQueueStateMessage(sessionManager.getQueueState(sessionId)));
3073
- const userMessage = sessionManager.addMessage(sessionId, {
3074
- role: "user",
3075
- content: nextCompletion.content,
3076
- ...nextCompletion.attachments ? { attachments: nextCompletion.attachments } : {}
3077
- });
3078
- sendForSession(sessionId, createChatMessageMessage(userMessage));
3079
- const newController = new AbortController();
3080
- activeAgents.set(sessionId, newController);
3081
- startTurnWithCompletionChain(sessionId, newController);
3082
- return;
3083
- }
3084
- sessionManager.clearMessageQueue(sessionId);
3085
- sessionManager.setRunning(sessionId, false);
2656
+ cleanupAfterTurn(sessionId, controller, sendForSession, true);
3086
2657
  });
3087
2658
  break;
3088
2659
  }
@@ -5487,7 +5058,7 @@ function createTerminalRoutes() {
5487
5058
  }
5488
5059
 
5489
5060
  // src/constants.ts
5490
- var VERSION = "1.6.51";
5061
+ var VERSION = "1.6.53";
5491
5062
 
5492
5063
  // src/server/index.ts
5493
5064
  var __dirname2 = dirname5(fileURLToPath4(import.meta.url));
@@ -5648,7 +5219,7 @@ async function createServerHandle(config) {
5648
5219
  res.json({ success: true });
5649
5220
  });
5650
5221
  app.get("/api/sessions", async (req, res) => {
5651
- const { getRecentUserPromptsForSession } = await import("./events-RXX52D3D.js");
5222
+ const { getRecentUserPromptsForSession } = await import("./events-UCHHTT6X.js");
5652
5223
  const projectId = req.query["projectId"];
5653
5224
  const limit = Math.min(parseInt(req.query["limit"]) || 20, 100);
5654
5225
  const offset = parseInt(req.query["offset"]) || 0;
@@ -5681,7 +5252,7 @@ async function createServerHandle(config) {
5681
5252
  res.status(201).json({ session });
5682
5253
  });
5683
5254
  app.get("/api/sessions/:id", async (req, res) => {
5684
- const { getEventStore: getEventStore2 } = await import("./events-RXX52D3D.js");
5255
+ const { getEventStore: getEventStore2 } = await import("./events-UCHHTT6X.js");
5685
5256
  const { buildMessagesFromStoredEvents: buildMessagesFromStoredEvents2 } = await import("./folding-NEZWWL7K.js");
5686
5257
  const session = sessionManager.getSession(req.params.id);
5687
5258
  if (!session) {
@@ -5712,7 +5283,7 @@ async function createServerHandle(config) {
5712
5283
  res.json({ success: true });
5713
5284
  });
5714
5285
  app.post("/api/sessions/:id/provider", async (req, res) => {
5715
- const { getEventStore: getEventStore2 } = await import("./events-RXX52D3D.js");
5286
+ const { getEventStore: getEventStore2 } = await import("./events-UCHHTT6X.js");
5716
5287
  const { buildMessagesFromStoredEvents: buildMessagesFromStoredEvents2 } = await import("./folding-NEZWWL7K.js");
5717
5288
  const sessionId = req.params.id;
5718
5289
  const session = sessionManager.getSession(sessionId);
@@ -5750,7 +5321,7 @@ async function createServerHandle(config) {
5750
5321
  res.json({ success: true });
5751
5322
  });
5752
5323
  app.put("/api/sessions/:id/mode", async (req, res) => {
5753
- const { getEventStore: getEventStore2 } = await import("./events-RXX52D3D.js");
5324
+ const { getEventStore: getEventStore2 } = await import("./events-UCHHTT6X.js");
5754
5325
  const { buildMessagesFromStoredEvents: buildMessagesFromStoredEvents2 } = await import("./folding-NEZWWL7K.js");
5755
5326
  const sessionId = req.params.id;
5756
5327
  const session = sessionManager.getSession(sessionId);
@@ -5789,14 +5360,14 @@ async function createServerHandle(config) {
5789
5360
  if (!callId || approved === void 0) {
5790
5361
  return res.status(400).json({ error: "callId and approved are required" });
5791
5362
  }
5792
- const { providePathConfirmation: providePathConfirmation2 } = await import("./tools-SBBC6TWC.js");
5363
+ const { providePathConfirmation: providePathConfirmation2 } = await import("./tools-SJN7IGVF.js");
5793
5364
  const result = providePathConfirmation2(callId, approved, alwaysAllow);
5794
5365
  if (!result.found) {
5795
5366
  return res.status(404).json({ error: "No pending path confirmation with that ID" });
5796
5367
  }
5797
- const { getEventStore: getEventStore2 } = await import("./events-RXX52D3D.js");
5368
+ const { getEventStore: getEventStore2 } = await import("./events-UCHHTT6X.js");
5798
5369
  const { buildMessagesFromStoredEvents: buildMessagesFromStoredEvents2, foldPendingConfirmations: foldPendingConfirmations2 } = await import("./folding-NEZWWL7K.js");
5799
- const { createSessionStateMessage: createSessionStateMessage2 } = await import("./protocol-4RE3E3H3.js");
5370
+ const { createSessionStateMessage: createSessionStateMessage2 } = await import("./protocol-WHHYESPI.js");
5800
5371
  const eventStore = getEventStore2();
5801
5372
  const events = eventStore.getEvents(sessionId);
5802
5373
  const messages = buildMessagesFromStoredEvents2(events);
@@ -5814,7 +5385,7 @@ async function createServerHandle(config) {
5814
5385
  if (!callId || !answer) {
5815
5386
  return res.status(400).json({ error: "callId and answer are required" });
5816
5387
  }
5817
- const { provideAnswer: provideAnswer2 } = await import("./tools-SBBC6TWC.js");
5388
+ const { provideAnswer: provideAnswer2 } = await import("./tools-SJN7IGVF.js");
5818
5389
  const found = provideAnswer2(callId, answer);
5819
5390
  if (!found) {
5820
5391
  return res.status(404).json({ error: "No pending question with that ID" });
@@ -5850,14 +5421,14 @@ async function createServerHandle(config) {
5850
5421
  if (!session) {
5851
5422
  return res.status(404).json({ error: "Session not found" });
5852
5423
  }
5853
- const { stopSessionExecution } = await import("./chat-handler-AQNAQSBE.js");
5854
- const { cancelQuestionsForSession: cancelQuestionsForSession2, cancelPathConfirmationsForSession: cancelPathConfirmationsForSession2 } = await import("./tools-SBBC6TWC.js");
5424
+ const { stopSessionExecution } = await import("./chat-handler-DERM2S6L.js");
5425
+ const { cancelQuestionsForSession: cancelQuestionsForSession2, cancelPathConfirmationsForSession: cancelPathConfirmationsForSession2 } = await import("./tools-SJN7IGVF.js");
5855
5426
  stopSessionExecution(sessionId, sessionManager);
5856
5427
  abortSession(sessionId);
5857
5428
  cancelQuestionsForSession2(sessionId, "Session stopped by user");
5858
5429
  cancelPathConfirmationsForSession2(sessionId, "Session stopped by user");
5859
5430
  sessionManager.clearMessageQueue(sessionId);
5860
- const eventStore = (await import("./events-RXX52D3D.js")).getEventStore();
5431
+ const eventStore = (await import("./events-UCHHTT6X.js")).getEventStore();
5861
5432
  eventStore.append(sessionId, { type: "running.changed", data: { isRunning: false } });
5862
5433
  res.json({ success: true });
5863
5434
  });
@@ -6310,7 +5881,7 @@ async function createServerHandle(config) {
6310
5881
  providerManager
6311
5882
  );
6312
5883
  const wss = wssExports.wss;
6313
- const { QueueProcessor } = await import("./processor-AJ6F6SA6.js");
5884
+ const { QueueProcessor } = await import("./processor-AS6JXF4U.js");
6314
5885
  const queueProcessor = new QueueProcessor({
6315
5886
  sessionManager,
6316
5887
  providerManager,
@@ -6383,4 +5954,4 @@ export {
6383
5954
  createServerHandle,
6384
5955
  createServer
6385
5956
  };
6386
- //# sourceMappingURL=chunk-6ZIAD3UH.js.map
5957
+ //# sourceMappingURL=chunk-JLMCJLTK.js.map