@tianshu-ai/tianshu 0.106.1 → 0.107.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tianshu-ai/tianshu",
3
- "version": "0.106.1",
3
+ "version": "0.107.0",
4
4
  "description": "An open AI agent platform with a sidecar browser. Built in public.",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://github.com/tianshu-ai/tianshu",
@@ -1 +1 @@
1
- {"version":3,"file":"handler.d.ts","sourceRoot":"","sources":["../../src/chat/handler.ts"],"names":[],"mappings":"AAwDA,OAAO,EACL,mBAAmB,EACnB,cAAc,EAGd,KAAK,mBAAmB,EACxB,KAAK,wBAAwB,EAC9B,MAAM,uBAAuB,CAAC;AAI/B,OAAO,EACL,mBAAmB,EACnB,cAAc,EACd,KAAK,mBAAmB,EACxB,KAAK,wBAAwB,GAC9B,CAAC;AAGF,OAAO,EACL,mBAAmB,EACnB,0BAA0B,EAC1B,8BAA8B,EAC9B,wBAAwB,EACxB,2BAA2B,EAC3B,wBAAwB,EACxB,2BAA2B,EAC3B,yBAAyB,EACzB,6BAA6B,EAC7B,2BAA2B,EAC3B,4BAA4B,EAC5B,KAAK,oBAAoB,GAC1B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,IAAI,CAAC;AACpC,OAAO,EAQL,KAAK,aAAa,EACnB,MAAM,kBAAkB,CAAC;AAsC1B,OAAO,EAGL,KAAK,WAAW,EACjB,MAAM,2BAA2B,CAAC;AAGnC,OAAO,EAWL,KAAK,WAAW,EAGjB,MAAM,eAAe,CAAC;AAgBvB,OAAO,EAGL,KAAK,SAAS,EAEd,KAAK,cAAc,EAEpB,MAAM,kBAAkB,CAAC;AA6B1B,MAAM,WAAW,eAAe;IAC9B,GAAG,EAAE,aAAa,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,MAA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AAW,EAAE,CAkC9C;AAGD,YAAY,EAAE,WAAW,EAAE,CAAC"}
@@ -42,7 +42,7 @@ import { pruneOldToolResults } from "./tool-result-truncation.js";
42
42
  import { dumpSystemPrompt } from "./dump-system-prompt.js";
43
43
  import { SqliteSessionRepo } from "./sqlite-session-repo.js";
44
44
  import { drainPending as drainInbox, renderForPrompt as renderInboxForPrompt, extractEvents, enqueue as enqueueInbox, markDeliveredFromMessage, } from "./session-inbox.js";
45
- import { getActiveHarness, registerActiveHarness, registerUserSendChannel, } from "./active-harnesses.js";
45
+ import { getActiveHarness, registerActiveHarness, registerUserSendChannel, broadcastToUser, } from "./active-harnesses.js";
46
46
  import { SqliteSessionStorage } from "./sqlite-session-storage.js";
47
47
  import { SqliteStorage } from "./sqlite-storage.js";
48
48
  import { createLogger, elapsedMs, summarizeToolArgs, estimateToolResultBytes, } from "../setup/logger.js";
@@ -61,7 +61,7 @@ import { progressiveHistoryTransform } from "./progressive-history.js";
61
61
  import { installStructuredCompactionHook } from "./structured-compaction.js";
62
62
  import { randomUUID } from "node:crypto";
63
63
  import { repairStaleLaneOperations } from "./repair-lane-state.js";
64
- import { abortSession } from "./session-abort.js";
64
+ import { abortSession, registerSessionAbort, unregisterSessionAbort } from "./session-abort.js";
65
65
  import { toWire, } from "./ws-protocol.js";
66
66
  import { cacheGet, cachePut, fitToLimit, imageFitCacheKey, } from "./image-fit.js";
67
67
  const MAX_TURNS = 9999;
@@ -84,6 +84,16 @@ const PRUNE_SLOW_MS = 50;
84
84
  const PRUNE_LARGE_MSGS = 500;
85
85
  /** Max auto-continuations when the model hits maxTokens (stopReason=length). */
86
86
  const MAX_CONTINUATIONS = 3;
87
+ const userQueues = new Map();
88
+ function getUserQueue(tenantId, userId) {
89
+ const key = `${tenantId}:${userId}`;
90
+ let q = userQueues.get(key);
91
+ if (!q) {
92
+ q = { entries: [], draining: false };
93
+ userQueues.set(key, q);
94
+ }
95
+ return q;
96
+ }
87
97
  export function attachChatHandler(opts) {
88
98
  const { ctx, userId, socket, pluginRegistry, homeDir } = opts;
89
99
  // Stamp the resolved identity on the socket so plugin WS handlers
@@ -92,19 +102,33 @@ export function attachChatHandler(opts) {
92
102
  // `(socket as { userId?: string }).userId`.
93
103
  socket.userId = userId;
94
104
  socket.tenantId = ctx.tenantId;
95
- const send = (msg) => {
105
+ // sendDirect: only this socket (request-response: connected, history, search, etc.)
106
+ // send: broadcast to ALL sockets for this tenant+user so every tab
107
+ // sees stream_delta / message_added / stream_end in real time.
108
+ // Closing one tab and opening another picks up the stream.
109
+ const sendDirect = (msg) => {
96
110
  if (socket.readyState !== socket.OPEN)
97
111
  return;
98
112
  socket.send(JSON.stringify(msg));
99
113
  };
114
+ const send = (msg) => {
115
+ broadcastToUser(ctx.tenantId, userId, msg);
116
+ };
100
117
  // Collect tool display hints from all active plugins for this tenant.
101
118
  const toolDisplay = collectToolDisplay(pluginRegistry, ctx.tenantId);
102
- send({ type: "connected", tenantId: ctx.tenantId, userId, serverVersion: getPackageVersion() ?? undefined, ...(toolDisplay.length > 0 ? { toolDisplay } : {}) });
119
+ sendDirect({ type: "connected", tenantId: ctx.tenantId, userId, serverVersion: getPackageVersion() ?? undefined, ...(toolDisplay.length > 0 ? { toolDisplay } : {}) });
120
+ // Re-push pending message queue so a page refresh restores the queue UI.
121
+ {
122
+ const uqInit = getUserQueue(ctx.tenantId, userId);
123
+ if (uqInit.entries.length > 0) {
124
+ sendDirect({ type: "queue_update", queue: uqInit.entries.map(e => ({ id: e.id, content: e.content, createdAt: e.createdAt })) });
125
+ }
126
+ }
103
127
  // Re-push any pending ask_user interactions so a page
104
128
  // refresh (or reconnect) restores the option buttons.
105
129
  import("./pending-interactions.js").then(({ getAllPending }) => {
106
130
  for (const req of getAllPending()) {
107
- send({ type: "interaction_request", ...req });
131
+ sendDirect({ type: "interaction_request", ...req });
108
132
  }
109
133
  });
110
134
  // Surface any host-version drift since this user's last active
@@ -123,7 +147,7 @@ export function attachChatHandler(opts) {
123
147
  pluginRegistry,
124
148
  });
125
149
  if (drift) {
126
- send({
150
+ sendDirect({
127
151
  type: "tool_catalog_changed",
128
152
  fromVersion: drift.fromVersion,
129
153
  toVersion: drift.toVersion,
@@ -142,7 +166,7 @@ export function attachChatHandler(opts) {
142
166
  try {
143
167
  const session = ensureActiveSession(ctx, userId);
144
168
  if (getActiveHarness(session.id)) {
145
- send({ type: "stream_start" });
169
+ sendDirect({ type: "stream_start" });
146
170
  }
147
171
  }
148
172
  catch {
@@ -151,8 +175,95 @@ export function attachChatHandler(opts) {
151
175
  // Register this socket's send thunk so the session-inbox idle
152
176
  // runner can broadcast a background turn's stream to every
153
177
  // tab the user has open. unregister fires on `close` below.
154
- const unregisterUserChannel = registerUserSendChannel(ctx.tenantId, userId, send);
178
+ const unregisterUserChannel = registerUserSendChannel(ctx.tenantId, userId, sendDirect);
155
179
  let aborter = null;
180
+ let currentRunPromise = null;
181
+ // ── Pending message queue (module-level, survives reconnect) ───
182
+ const uq = getUserQueue(ctx.tenantId, userId);
183
+ const pendingQueue = uq.entries;
184
+ function broadcastQueue() {
185
+ const msg = { type: "queue_update", queue: pendingQueue.map(e => ({ id: e.id, content: e.content, createdAt: e.createdAt })) };
186
+ broadcastToUser(ctx.tenantId, userId, msg);
187
+ }
188
+ function enqueueMessage(content) {
189
+ const entry = {
190
+ id: `q_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
191
+ content,
192
+ createdAt: Date.now(),
193
+ };
194
+ pendingQueue.push(entry);
195
+ broadcastQueue();
196
+ sendDirect({ type: "follow_up_ack", status: "queued" });
197
+ log.info(`queue_add id=${entry.id} depth=${pendingQueue.length}`);
198
+ }
199
+ /** Drain queued messages after the current turn completes.
200
+ * Called automatically by trackRun. */
201
+ async function drainQueue() {
202
+ if (uq.draining)
203
+ return;
204
+ uq.draining = true;
205
+ try {
206
+ while (pendingQueue.length > 0) {
207
+ const entry = pendingQueue.shift();
208
+ broadcastQueue();
209
+ log.info(`queue_drain id=${entry.id} remaining=${pendingQueue.length}`);
210
+ aborter = new AbortController();
211
+ const drainSignal = aborter.signal;
212
+ currentRunPromise = runPrompt({
213
+ ctx,
214
+ userId,
215
+ session: ensureActiveSession(ctx, userId),
216
+ content: entry.content,
217
+ send,
218
+ signal: drainSignal,
219
+ pluginRegistry,
220
+ homeDir,
221
+ });
222
+ try {
223
+ await currentRunPromise;
224
+ }
225
+ catch (err) {
226
+ log.error(`runPrompt (queue_drain) FAILED`, err instanceof Error ? err.stack : String(err));
227
+ }
228
+ currentRunPromise = null;
229
+ }
230
+ }
231
+ finally {
232
+ uq.draining = false;
233
+ }
234
+ }
235
+ /**
236
+ * Register the current aborter in the session-level abort registry
237
+ * so ANY tab (not just the one that started the prompt) can stop it.
238
+ */
239
+ function registerAborterForSession(ab) {
240
+ try {
241
+ const session = ensureActiveSession(ctx, userId);
242
+ registerSessionAbort(session.id, ab);
243
+ }
244
+ catch { /* no active session yet */ }
245
+ }
246
+ /** Wrap a runPrompt promise: when it settles, drain the queue. */
247
+ function trackRun(p) {
248
+ currentRunPromise = p;
249
+ if (aborter)
250
+ registerAborterForSession(aborter);
251
+ p.finally(() => {
252
+ // Only drain if this is still the active run (not superseded).
253
+ if (currentRunPromise === p) {
254
+ currentRunPromise = null;
255
+ // Clean up session-level abort registration
256
+ try {
257
+ const session = ensureActiveSession(ctx, userId);
258
+ unregisterSessionAbort(session.id);
259
+ }
260
+ catch { /* ignore */ }
261
+ if (pendingQueue.length > 0)
262
+ drainQueue().catch(() => { });
263
+ }
264
+ });
265
+ return p;
266
+ }
156
267
  socket.on("message", (raw) => {
157
268
  let parsed;
158
269
  try {
@@ -163,7 +274,7 @@ export function attachChatHandler(opts) {
163
274
  }
164
275
  switch (parsed.type) {
165
276
  case "hello":
166
- send({ type: "connected", tenantId: ctx.tenantId, userId, serverVersion: getPackageVersion() ?? undefined, ...(toolDisplay.length > 0 ? { toolDisplay } : {}) });
277
+ sendDirect({ type: "connected", tenantId: ctx.tenantId, userId, serverVersion: getPackageVersion() ?? undefined, ...(toolDisplay.length > 0 ? { toolDisplay } : {}) });
167
278
  return;
168
279
  case "history": {
169
280
  const opts = makeWireOpts(ctx);
@@ -177,7 +288,7 @@ export function attachChatHandler(opts) {
177
288
  : listMessagesForUserPage(ctx, userId, {
178
289
  limit: parsed.limit,
179
290
  });
180
- send({
291
+ sendDirect({
181
292
  type: "history",
182
293
  messages: page.messages.map((m) => toWire(m, opts)),
183
294
  hasMore: page.hasMore,
@@ -196,7 +307,7 @@ export function attachChatHandler(opts) {
196
307
  limit: parsed.limit,
197
308
  before: parsed.before,
198
309
  });
199
- send({
310
+ sendDirect({
200
311
  type: "history_page",
201
312
  messages: page.messages.map((m) => toWire(m, opts)),
202
313
  hasMore: page.hasMore,
@@ -210,10 +321,10 @@ export function attachChatHandler(opts) {
210
321
  const result = getMessagesAroundId(ctx, userId, parsed.messageId, contextSize);
211
322
  if (!result) {
212
323
  // Message not found — send empty
213
- send({ type: "history_around", messageId: parsed.messageId, messages: [], hasMoreBefore: false, hasMoreAfter: false });
324
+ sendDirect({ type: "history_around", messageId: parsed.messageId, messages: [], hasMoreBefore: false, hasMoreAfter: false });
214
325
  return;
215
326
  }
216
- send({
327
+ sendDirect({
217
328
  type: "history_around",
218
329
  messageId: parsed.messageId,
219
330
  messages: result.messages.map((m) => toWire(m, opts)),
@@ -228,7 +339,7 @@ export function attachChatHandler(opts) {
228
339
  limit: parsed.limit,
229
340
  after: parsed.after,
230
341
  });
231
- send({
342
+ sendDirect({
232
343
  type: "history_page_after",
233
344
  messages: page.messages.map((m) => toWire(m, opts)),
234
345
  hasMore: page.hasMore,
@@ -239,11 +350,11 @@ export function attachChatHandler(opts) {
239
350
  case "search": {
240
351
  const q = (parsed.query ?? "").trim();
241
352
  if (!q) {
242
- send({ type: "search_result", query: "", hits: [] });
353
+ sendDirect({ type: "search_result", query: "", hits: [] });
243
354
  return;
244
355
  }
245
356
  const hits = searchMessages(ctx, userId, q, { limit: parsed.limit });
246
- send({
357
+ sendDirect({
247
358
  type: "search_result",
248
359
  query: q,
249
360
  hits: hits.map((h) => ({
@@ -257,33 +368,90 @@ export function attachChatHandler(opts) {
257
368
  return;
258
369
  }
259
370
  case "follow_up": {
260
- // Follow-up message while the agent is mid-turn.
261
- //
262
- // Strategy: abort the current turn immediately, then start a
263
- // new turn with the follow-up as a fresh prompt. The agent
264
- // sees the full context (including partial tool results from
265
- // the aborted turn) plus the user's new message, and decides
266
- // how to proceed.
267
- //
268
- // This is better than lane.followUp() which only gets consumed
269
- // after the entire tool batch finishes — if the LLM planned
270
- // 10 tool calls, the user has to wait for all 10 before their
271
- // message is seen.
272
- const fuSession = ensureActiveSession(ctx, userId);
273
- log.info(`follow_up: aborting current turn and re-sending as prompt`);
274
- send({ type: "follow_up_ack", status: "upgraded" });
371
+ // Message while the agent is mid-turn → queue by default.
372
+ // The queue drains automatically when the current turn ends.
373
+ // The user can force-send via queue_send_now if they want
374
+ // to interrupt the current turn (old follow_up behavior).
375
+ enqueueMessage(parsed.content);
376
+ return;
377
+ }
378
+ case "queue_remove": {
379
+ const idx = pendingQueue.findIndex(e => e.id === parsed.queueId);
380
+ if (idx >= 0) {
381
+ const removed = pendingQueue.splice(idx, 1)[0];
382
+ log.info(`queue_remove id=${removed.id} remaining=${pendingQueue.length}`);
383
+ broadcastQueue();
384
+ }
385
+ return;
386
+ }
387
+ case "queue_edit": {
388
+ const editParsed = parsed;
389
+ const editIdx = pendingQueue.findIndex(e => e.id === editParsed.queueId);
390
+ if (editIdx >= 0 && editParsed.content?.trim()) {
391
+ pendingQueue[editIdx].content = editParsed.content.trim();
392
+ log.info(`queue_edit id=${editParsed.queueId}`);
393
+ broadcastQueue();
394
+ }
395
+ return;
396
+ }
397
+ case "queue_reorder": {
398
+ const ids = parsed.order;
399
+ if (!Array.isArray(ids))
400
+ return;
401
+ // Rebuild queue in the requested order, dropping any unknown ids.
402
+ const byId = new Map(pendingQueue.map(e => [e.id, e]));
403
+ const reordered = [];
404
+ for (const id of ids) {
405
+ const e = byId.get(id);
406
+ if (e) {
407
+ reordered.push(e);
408
+ byId.delete(id);
409
+ }
410
+ }
411
+ // Append any entries not in the order list (shouldn't happen, but safe).
412
+ for (const e of byId.values())
413
+ reordered.push(e);
414
+ pendingQueue.length = 0;
415
+ pendingQueue.push(...reordered);
416
+ log.info(`queue_reorder new_order=[${ids.join(',')}]`);
417
+ broadcastQueue();
418
+ return;
419
+ }
420
+ case "queue_send_now": {
421
+ // Force-send a queued message as an immediate follow_up,
422
+ // aborting the current turn.
423
+ const qid = parsed.queueId;
424
+ const qIdx = pendingQueue.findIndex(e => e.id === qid);
425
+ if (qIdx < 0)
426
+ return;
427
+ const entry = pendingQueue.splice(qIdx, 1)[0];
428
+ broadcastQueue();
429
+ log.info(`queue_send_now id=${entry.id} — aborting current turn`);
430
+ sendDirect({ type: "follow_up_ack", status: "upgraded" });
275
431
  if (aborter)
276
432
  aborter.abort();
433
+ const prevRun = currentRunPromise;
277
434
  aborter = new AbortController();
278
- runPrompt({
279
- ctx,
280
- userId,
281
- session: fuSession,
282
- content: parsed.content,
283
- send,
284
- signal: aborter.signal,
285
- }).catch((err) => {
286
- log.error(`runPrompt (follow_up) FAILED`, err?.stack ?? err);
435
+ const fuSignal = aborter.signal;
436
+ trackRun((async () => {
437
+ if (prevRun) {
438
+ try {
439
+ await prevRun;
440
+ }
441
+ catch { /* aborted turn — ignore */ }
442
+ }
443
+ await runPrompt({
444
+ ctx,
445
+ userId,
446
+ session: ensureActiveSession(ctx, userId),
447
+ content: entry.content,
448
+ send,
449
+ signal: fuSignal,
450
+ pluginRegistry,
451
+ homeDir,
452
+ });
453
+ })()).catch((err) => {
454
+ log.error(`runPrompt (queue_send_now) FAILED`, err?.stack ?? err);
287
455
  });
288
456
  return;
289
457
  }
@@ -320,20 +488,30 @@ export function attachChatHandler(opts) {
320
488
  const explicitSession = parsed.sessionId
321
489
  ? findSessionById(ctx, userId, parsed.sessionId)
322
490
  : undefined;
323
- runPrompt({
324
- ctx,
325
- userId,
326
- send,
327
- content: parsed.content,
328
- modelId: parsed.modelId,
329
- attachments: parsed.attachments,
330
- signal: aborter.signal,
331
- pluginRegistry,
332
- homeDir,
333
- session: explicitSession,
334
- voiceMode: parsed.voiceMode === true,
335
- taskMode: parsed.taskMode === true,
336
- }).catch((err) => {
491
+ const prevRunP = currentRunPromise;
492
+ const promptSignal = aborter.signal;
493
+ trackRun((async () => {
494
+ if (prevRunP) {
495
+ try {
496
+ await prevRunP;
497
+ }
498
+ catch { /* previous turn settled */ }
499
+ }
500
+ await runPrompt({
501
+ ctx,
502
+ userId,
503
+ send,
504
+ content: parsed.content,
505
+ modelId: parsed.modelId,
506
+ attachments: parsed.attachments,
507
+ signal: promptSignal,
508
+ pluginRegistry,
509
+ homeDir,
510
+ session: explicitSession,
511
+ voiceMode: parsed.voiceMode === true,
512
+ taskMode: parsed.taskMode === true,
513
+ });
514
+ })()).catch((err) => {
337
515
  log.error(`runPrompt(explicit) FAILED`, err?.stack ?? err);
338
516
  send({
339
517
  type: "stream_error",
@@ -351,17 +529,27 @@ export function attachChatHandler(opts) {
351
529
  aborter.abort();
352
530
  }
353
531
  aborter = new AbortController();
354
- runPrompt({
355
- ctx,
356
- userId,
357
- send,
358
- content: "",
359
- retryLastTurn: true,
360
- modelId: parsed.modelId,
361
- signal: aborter.signal,
362
- pluginRegistry,
363
- homeDir,
364
- }).catch((err) => {
532
+ const prevRunR = currentRunPromise;
533
+ const retrySignal = aborter.signal;
534
+ trackRun((async () => {
535
+ if (prevRunR) {
536
+ try {
537
+ await prevRunR;
538
+ }
539
+ catch { /* previous turn settled */ }
540
+ }
541
+ await runPrompt({
542
+ ctx,
543
+ userId,
544
+ send,
545
+ content: "",
546
+ retryLastTurn: true,
547
+ modelId: parsed.modelId,
548
+ signal: retrySignal,
549
+ pluginRegistry,
550
+ homeDir,
551
+ });
552
+ })()).catch((err) => {
365
553
  log.error(`runPrompt(retry) FAILED`, err?.stack ?? err);
366
554
  send({
367
555
  type: "stream_error",
@@ -441,16 +629,26 @@ export function attachChatHandler(opts) {
441
629
  // If text is provided, run a new turn with it. If not, just
442
630
  // truncate (the user can type a new message manually).
443
631
  if (text !== undefined && text.trim() !== "") {
444
- runPrompt({
445
- ctx,
446
- userId,
447
- send,
448
- content: text,
449
- modelId: editModelId,
450
- signal: aborter.signal,
451
- pluginRegistry,
452
- homeDir,
453
- }).catch((err) => {
632
+ const prevRunE = currentRunPromise;
633
+ const editSignal = aborter.signal;
634
+ trackRun((async () => {
635
+ if (prevRunE) {
636
+ try {
637
+ await prevRunE;
638
+ }
639
+ catch { /* previous turn settled */ }
640
+ }
641
+ await runPrompt({
642
+ ctx,
643
+ userId,
644
+ send,
645
+ content: text,
646
+ modelId: editModelId,
647
+ signal: editSignal,
648
+ pluginRegistry,
649
+ homeDir,
650
+ });
651
+ })()).catch((err) => {
454
652
  log.error(`runPrompt(edit_resend) FAILED`, err?.stack ?? err);
455
653
  send({
456
654
  type: "stream_error",
@@ -496,7 +694,7 @@ export function attachChatHandler(opts) {
496
694
  if (pluginRegistry) {
497
695
  const unregHandler = pluginRegistry.resolveWsHandler(ctx.tenantId, "reverse_mcp_unregister");
498
696
  if (unregHandler) {
499
- Promise.resolve(unregHandler.handler({ type: "reverse_mcp_unregister" }, socket, unregHandler.entry.ctx)).catch(() => { });
697
+ Promise.resolve(unregHandler.handler({ type: "reverse_mcp_unregister", _socketClose: true }, socket, unregHandler.entry.ctx)).catch(() => { });
500
698
  }
501
699
  }
502
700
  });