@theoremjs/web 0.3.4 → 0.3.5-next.1000.g569f044

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 (59) hide show
  1. package/README.md +330 -13
  2. package/client/chat.d.ts +14 -2
  3. package/client/chat.js +302 -34
  4. package/client/composer-hints.d.ts +18 -10
  5. package/client/composer-hints.js +23 -6
  6. package/client/host-transport.d.ts +7 -2
  7. package/client/host-transport.js +9 -3
  8. package/client/index.d.ts +4 -4
  9. package/client/index.js +3 -3
  10. package/client/page-dispatch.js +5 -0
  11. package/client/run-session.d.ts +27 -2
  12. package/client/run-session.js +34 -4
  13. package/client/schema-fields.d.ts +28 -1
  14. package/client/schema-fields.js +172 -13
  15. package/client/tool-result.d.ts +9 -5
  16. package/client/tool-result.js +23 -42
  17. package/client/transcript-schema.d.ts +4 -0
  18. package/client/transcript-schema.js +25 -6
  19. package/client/transport.d.ts +90 -9
  20. package/client/transport.js +56 -11
  21. package/client/turn-client.d.ts +8 -2
  22. package/client/turn-client.js +9 -0
  23. package/package.json +2 -2
  24. package/server/conversation-core.d.ts +273 -0
  25. package/server/conversation-core.js +797 -0
  26. package/server/conversation-inbox.d.ts +45 -0
  27. package/server/conversation-inbox.js +240 -0
  28. package/server/conversation-store.d.ts +43 -2
  29. package/server/conversation-store.js +15 -2
  30. package/server/conversation.d.ts +82 -2
  31. package/server/conversation.js +357 -60
  32. package/server/create-conversation-core.d.ts +28 -0
  33. package/server/create-conversation-core.js +46 -0
  34. package/server/embedding-handler.js +2 -0
  35. package/server/handler.d.ts +84 -20
  36. package/server/handler.js +279 -659
  37. package/server/mcp-handler.js +25 -11
  38. package/server/mod.d.ts +11 -4
  39. package/server/mod.js +6 -2
  40. package/server/notifier.d.ts +3 -2
  41. package/server/notifier.js +3 -2
  42. package/server/session-authority.d.ts +3 -1
  43. package/server/session-authority.js +26 -1
  44. package/server/session-boundary.d.ts +5 -3
  45. package/server/session-boundary.js +2 -2
  46. package/server/session-calls.d.ts +122 -0
  47. package/server/session-calls.js +512 -0
  48. package/server/session-store.d.ts +33 -0
  49. package/server/session-store.js +37 -2
  50. package/server/steer-inbox.d.ts +3 -4
  51. package/server/steer-inbox.js +6 -5
  52. package/server/tell-every-result.d.ts +11 -0
  53. package/server/tell-every-result.js +17 -0
  54. package/server/tool-operations.d.ts +8 -0
  55. package/server/tool-operations.js +71 -0
  56. package/server/turn-input.d.ts +4 -2
  57. package/server/turn-input.js +5 -2
  58. package/server/turn-wiring.d.ts +31 -6
  59. package/server/turn-wiring.js +59 -5
package/client/chat.js CHANGED
@@ -1,5 +1,5 @@
1
- import { TheoremError, } from '@theoremjs/agents';
2
- import { branchInterfaceTurnSession, consumeNextComposerQueue, convertSteersToFrontQueued, createComposerPendingMessage, defaultInterfaceEffort, emptyInterfaceTurnSession, moveComposerPendingWithinKind, orderComposerPendingMessages, promoteComposerPendingKind, removeComposerPendingMessage, removeLandedSteers, userDraftHasPayload, userDraftToSteerInject, } from '@theoremjs/agents/interface';
1
+ import { attachmentsRefused, TheoremError, } from '@theoremjs/agents';
2
+ import { branchInterfaceTurnSession, consumeNextComposerQueue, convertSteersToFrontQueued, createComposerPendingMessage, defaultInterfaceEffort, emptyInterfaceTurnSession, moveComposerPendingWithinKind, orderComposerPendingMessages, prepareUserTurn, promoteComposerPendingKind, removeComposerPendingMessage, removeLandedSteers, saveComposerPendingMessage, takeSavedComposerPending, userDraftHasPayload, userDraftToSteerInject, } from '@theoremjs/agents/interface';
3
3
  import { composerHasPayload } from "./composer-primary.js";
4
4
  import { composerFieldsFromDraft } from "./decode-composer-draft.js";
5
5
  import { encodeComposerDraft } from "./encode-composer-draft.js";
@@ -8,12 +8,20 @@ import { followGenerationDefaults } from "./generation-selection.js";
8
8
  import { warnPageToolMismatch } from "./live/live-page-tool.js";
9
9
  import { withPageToolDispatch } from "./page-dispatch.js";
10
10
  import { sessionAfter, stampWorked, stoppedReply } from "./run-commit.js";
11
- import { keepsConversation, resumeInterfaceTool, streamInterfaceDraftTurn, streamInterfaceTurn, } from "./run-session.js";
12
- import { isUnknownConversation, } from "./transport.js";
11
+ import { extractInlineEncodedAttachments, keepsConversation, resumeInterfaceTool, streamInterfaceDraftTurn, streamInterfaceTurn, streamInterfaceWake, } from "./run-session.js";
12
+ import { isTurnEnded, isUnknownConversation, } from "./transport.js";
13
13
  import { foldAssistantTurn, issuedOperationId } from "./turn-client.js";
14
14
  const DELIVERY_ORDER = ['sending', 'sent', 'delivered', 'read'];
15
15
  /** The server's own reports (bookkeeping, a failure, the end), which say nothing of the model having the message. */
16
- const SERVER_EVENTS = new Set(['stage', 'guardrail', 'late_results', 'session', 'error', 'done']);
16
+ const SERVER_EVENTS = new Set([
17
+ 'stage',
18
+ 'guardrail',
19
+ 'late_results',
20
+ 'session',
21
+ 'hook_failed',
22
+ 'error',
23
+ 'done',
24
+ ]);
17
25
  /** The reply itself (its thinking and tool calls come before it). */
18
26
  const REPLY_EVENTS = new Set(['text', 'structured', 'media']);
19
27
  /**
@@ -79,9 +87,19 @@ function nextFrame(run) {
79
87
  const id = setTimeout(run, 16);
80
88
  return () => clearTimeout(id);
81
89
  }
82
- function newTurnId() {
90
+ function newId() {
83
91
  return crypto.randomUUID();
84
92
  }
93
+ /** A pending message's draft as the input a steer sends. */
94
+ function steerInput(draft) {
95
+ const attachments = extractInlineEncodedAttachments(draft.attachments);
96
+ const voice = extractInlineEncodedAttachments(draft.voice);
97
+ return {
98
+ ...(draft.text?.trim() ? { text: draft.text } : {}),
99
+ ...(attachments ? { attachments } : {}),
100
+ ...(voice ? { voice } : {}),
101
+ };
102
+ }
85
103
  class Chat {
86
104
  #options;
87
105
  #state;
@@ -115,8 +133,20 @@ class Chat {
115
133
  /** What the last view said about the host's push; unset, nothing is listened for. */
116
134
  #notify;
117
135
  #listening = null;
136
+ /** The last view said results wait that no reply has read: the chat wakes once it is idle. */
137
+ #wakeDue = false;
138
+ /** The ids a reply names the run's message by, once the host said it saved the message itself. */
139
+ #savedAs = null;
140
+ /** How many blocks, at the end of the transcript, are the message the run posted. */
141
+ #ownPosted = 0;
142
+ /** The run in flight has streamed an event of its reply. */
143
+ #streamed = false;
118
144
  #reading = null;
119
145
  #readAgain = false;
146
+ /** Reads the conversation again once the hold of the reply that runs elsewhere lapses. */
147
+ #holdTimer = null;
148
+ /** The `heldUntil` of the last read made when a hold lapsed. */
149
+ #heldUntilRead = null;
120
150
  constructor(options) {
121
151
  this.#options = options;
122
152
  this.#conversation = options.conversation;
@@ -133,9 +163,11 @@ class Chat {
133
163
  failure: null,
134
164
  answering: null,
135
165
  phase: 'idle',
166
+ waitingGate: null,
136
167
  session: emptyInterfaceTurnSession(),
137
168
  delivery: null,
138
169
  streaming: false,
170
+ runningElsewhere: null,
139
171
  options: picksOf(options.iface, options.options, {}).options,
140
172
  };
141
173
  this.#notified = this.#state;
@@ -150,9 +182,11 @@ class Chat {
150
182
  this.#settle();
151
183
  }
152
184
  this.#followPush();
185
+ this.#followHold();
153
186
  return () => {
154
187
  this.#listeners.delete(listener);
155
188
  this.#followPush();
189
+ this.#followHold();
156
190
  };
157
191
  };
158
192
  refresh = () => {
@@ -215,6 +249,28 @@ class Chat {
215
249
  this.#listening = listening;
216
250
  void this.#listen(listening);
217
251
  }
252
+ /**
253
+ * Reads the conversation again when the hold of the reply that runs elsewhere lapses, while
254
+ * someone is here to see it. The app says when that reply ends; this covers a server that died
255
+ * holding it, which says nothing.
256
+ */
257
+ #followHold() {
258
+ if (this.#holdTimer)
259
+ clearTimeout(this.#holdTimer);
260
+ this.#holdTimer = null;
261
+ const running = this.#state.runningElsewhere;
262
+ if (!running || this.#listeners.size === 0)
263
+ return;
264
+ // why: A read that still shows a hold already followed lapsed waits for the app's publish; the
265
+ // server's clock and this one differ, so one read per hold, not one per draw.
266
+ if (running.heldUntil === this.#heldUntilRead)
267
+ return;
268
+ this.#holdTimer = setTimeout(() => {
269
+ this.#holdTimer = null;
270
+ this.#heldUntilRead = running.heldUntil;
271
+ void this.refresh();
272
+ }, Math.max(0, running.heldUntil - Date.now()));
273
+ }
218
274
  async #listen(listening) {
219
275
  const { signal } = listening;
220
276
  while (!signal.aborted) {
@@ -250,7 +306,19 @@ class Chat {
250
306
  if (Object.keys(patch).length > 0)
251
307
  this.#set(patch);
252
308
  };
253
- setDraftText = (value) => this.#apply('draftText', value);
309
+ setDraftText = (value) => {
310
+ const next = typeof value === 'function' ? value(this.#state.draftText) : value;
311
+ if (next === this.#state.draftText)
312
+ return;
313
+ const { failure } = this.#state;
314
+ const issues = this.#state.issues.filter((issue) => issue.code !== 'text_too_long');
315
+ // why: Editing the text answers a refusal for its length; a refusal for the files stays until they change.
316
+ this.#set({
317
+ draftText: next,
318
+ issues,
319
+ ...(failure?.errorKind === 'input' && issues.length === 0 ? { failure: null } : {}),
320
+ });
321
+ };
254
322
  setPendingFiles = (value) => this.#apply('pendingFiles', value);
255
323
  setPendingVoice = (value) => this.#apply('pendingVoice', value);
256
324
  setPendingMessages = (value) => this.#apply('pendingMessages', value);
@@ -267,12 +335,18 @@ class Chat {
267
335
  stop = () => {
268
336
  void this.#stop();
269
337
  };
270
- /** Asks the host to stop the turn, so the reply it leaves comes back; a host that can't drops the stream. */
338
+ /**
339
+ * Asks the host to stop the reply, so what it leaves comes back; a host that can't drops the
340
+ * stream. A reply that runs elsewhere is stopped by the conversation, and the read after it
341
+ * draws what it left.
342
+ */
271
343
  async #stop() {
272
344
  const abort = this.#abort;
273
345
  const turnId = this.#turnId;
274
- if (!abort)
346
+ if (!abort) {
347
+ await this.#stopElsewhere();
275
348
  return;
349
+ }
276
350
  this.#stopped = true;
277
351
  if (!turnId) {
278
352
  abort.abort();
@@ -286,6 +360,27 @@ class Chat {
286
360
  abort.abort();
287
361
  }
288
362
  }
363
+ /** Stops the reply that runs elsewhere. False when it may still run: the stop was refused or failed. */
364
+ async #stopElsewhere() {
365
+ const conversation = this.#conversation;
366
+ if (!this.#state.runningElsewhere || conversation === undefined)
367
+ return true;
368
+ this.#stopped = true;
369
+ let stopped = true;
370
+ try {
371
+ await this.#options.transport.stop({ conversation });
372
+ }
373
+ catch (err) {
374
+ // why: A reply that ended first is not running; the read below shows what it left.
375
+ if (!isTurnEnded(err)) {
376
+ stopped = false;
377
+ this.#stopped = false;
378
+ this.#set({ failure: clientFailure(err, this.#options.iface?.labels) });
379
+ }
380
+ }
381
+ await this.refresh();
382
+ return stopped;
383
+ }
289
384
  enqueue = async (kind) => {
290
385
  const { draftText, pendingFiles, pendingVoice } = this.#state;
291
386
  if (!composerHasPayload(draftText, pendingFiles, pendingVoice))
@@ -295,6 +390,16 @@ class Chat {
295
390
  try {
296
391
  const draft = await encodeComposerDraft({ text: draftText, pendingFiles, pendingVoice });
297
392
  message = createComposerPendingMessage({ kind, draft });
393
+ const { iface } = this.#options;
394
+ const checked = kind !== 'stash' && iface ? prepareUserTurn(iface.inputs, draft, iface.guardrails) : null;
395
+ if (checked && !checked.ok) {
396
+ // why: A message the profile refuses is never queued or steered; it stays in the composer as typed.
397
+ this.#set({
398
+ issues: checked.issues,
399
+ failure: clientFailure(attachmentsRefused(checked.issues), iface?.labels),
400
+ });
401
+ return;
402
+ }
298
403
  }
299
404
  catch (err) {
300
405
  this.#set({ failure: clientFailure(err, this.#options.iface?.labels) });
@@ -311,23 +416,42 @@ class Chat {
311
416
  this.#drainArmed = true;
312
417
  if (message.kind !== 'steer')
313
418
  return;
314
- const turnId = this.#turnId;
315
- if (!turnId) {
419
+ const target = this.#steerTarget();
420
+ if (!target) {
316
421
  this.#steerAfterTurnEnded();
317
422
  return;
318
423
  }
319
- const inject = userDraftToSteerInject(message.draft);
320
- if (inject.length === 0)
424
+ const input = steerInput(message.draft);
425
+ if (Object.keys(input).length === 0)
321
426
  return;
322
427
  try {
323
- await this.#options.transport.steer({ turnId, id: message.id, inject });
428
+ const { saved } = await this.#options.transport.steer({ ...target, id: message.id, input });
429
+ if (!saved)
430
+ return;
431
+ this.#set({
432
+ pendingMessages: saveComposerPendingMessage(this.#state.pendingMessages, message.id, saved.landsAs),
433
+ });
434
+ this.#adopt(saved.conversation);
435
+ // why: A run in flight reads the conversation once it ends, after this save. With none, the chat reads now, and wakes for the message.
436
+ if (!this.#busy)
437
+ await this.refresh();
324
438
  }
325
439
  catch (err) {
326
440
  this.#set({ failure: clientFailure(err, this.#options.iface?.labels) });
327
441
  }
328
442
  };
443
+ /** Where a steer goes: the turn this page runs, or the reply that runs elsewhere. */
444
+ #steerTarget() {
445
+ const conversation = this.#conversation;
446
+ const turnId = this.#turnId;
447
+ if (turnId)
448
+ return { turnId, ...(conversation === undefined ? {} : { conversation }) };
449
+ if (this.#state.runningElsewhere && conversation !== undefined)
450
+ return { conversation };
451
+ return null;
452
+ }
329
453
  sendNow = async (source) => {
330
- if (!this.#options.iface)
454
+ if (!this.#options.iface || source?.saved)
331
455
  return;
332
456
  const draft = source ? source.draft : await this.#composerDraft();
333
457
  if (!draft)
@@ -336,10 +460,15 @@ class Chat {
336
460
  await this.#stop();
337
461
  await this.#run;
338
462
  }
463
+ else if (!(await this.#stopElsewhere())) {
464
+ // why: A reply that may still run is not sent into; the message stays where it was.
465
+ return;
466
+ }
339
467
  this.#set({ pendingMessages: convertSteersToFrontQueued(this.#state.pendingMessages) });
340
468
  this.#drainArmed = false;
341
469
  // why: Sent while the reply waits on gates, the message walks away from them in its own request.
342
470
  await this.#sendDraft(draft, {
471
+ id: source?.id ?? newId(),
343
472
  walkAway: this.#state.session.gatedTool !== null,
344
473
  // why: The sent message leaves the queue, or the composer it came from.
345
474
  onPosted: () => this.#set(source
@@ -359,7 +488,7 @@ class Chat {
359
488
  };
360
489
  restorePending = async (id) => {
361
490
  const message = this.#state.pendingMessages.find((m) => m.id === id);
362
- if (!message)
491
+ if (!message || message.saved)
363
492
  return;
364
493
  try {
365
494
  await this.#restore(composerFieldsFromDraft(message.draft));
@@ -390,7 +519,7 @@ class Chat {
390
519
  authenticate = (secret) => this.#answerGate({ action: 'auth', ...(secret === undefined ? {} : { secret }) });
391
520
  branch = async (index) => {
392
521
  const { iface } = this.#options;
393
- if (!iface || this.#busy)
522
+ if (!iface || this.#busy || this.#state.runningElsewhere)
394
523
  return;
395
524
  const ref = this.#conversation;
396
525
  if (!keepsConversation(iface) || ref === undefined) {
@@ -451,7 +580,10 @@ class Chat {
451
580
  };
452
581
  #set(patch) {
453
582
  const next = { ...this.#state, ...patch };
454
- next.phase = this.#busy ? 'streaming' : next.session.gatedTool ? 'gated' : 'idle';
583
+ const running = this.#busy || next.runningElsewhere !== null;
584
+ next.phase = running ? 'streaming' : next.session.gatedTool ? 'gated' : 'idle';
585
+ const gate = next.session.gatedTool;
586
+ next.waitingGate = next.phase === 'gated' && gate && gate.gateKind !== 'page' ? gate : null;
455
587
  this.#state = next;
456
588
  if (this.#flushQueued)
457
589
  return;
@@ -487,6 +619,28 @@ class Chat {
487
619
  this.#resume(iface);
488
620
  this.#answerPageGate();
489
621
  this.#drain();
622
+ this.#wake();
623
+ }
624
+ /**
625
+ * Wakes the conversation when the host said results wait. A message the queue sends goes first:
626
+ * its reply reads them. The host takes each result once, so a wake is never run twice for it.
627
+ */
628
+ #wake() {
629
+ const ref = this.#conversation;
630
+ if (!this.#wakeDue || ref === undefined || this.#busy || this.#draining)
631
+ return;
632
+ if (this.#state.phase !== 'idle' || !this.#options.transport.wake)
633
+ return;
634
+ this.#wakeDue = false;
635
+ void this.#runTurn(({ iface, view, transport, scope, signal }) => streamInterfaceWake({
636
+ iface,
637
+ transport,
638
+ session: this.#state.session,
639
+ scope: { ...scope, conversation: ref },
640
+ view,
641
+ signal,
642
+ began: () => this.#set({ failure: null, streaming: true }),
643
+ }), { turn: true, wake: true });
490
644
  }
491
645
  #clearedComposer() {
492
646
  return { draftText: '', pendingFiles: [], pendingVoice: [] };
@@ -522,14 +676,27 @@ class Chat {
522
676
  #draw(view, session, events) {
523
677
  const shown = [...this.#state.blocks, ...this.#state.streamBlocks];
524
678
  const blocks = keepIds(shown, view.transcript);
679
+ const after = view.paused?.blocks ?? view.running?.prompt ?? [];
680
+ const drawn = [...view.transcript, ...after].map((block) => block.id);
681
+ const ended = this.#state.runningElsewhere !== null && view.running === undefined;
525
682
  this.#set({
683
+ // why: A saved message the conversation now shows is no longer waiting.
684
+ pendingMessages: takeSavedComposerPending(this.#state.pendingMessages, drawn).remaining,
526
685
  blocks,
527
- streamBlocks: keepIds(shown.slice(blocks.length), view.paused?.blocks ?? []),
686
+ streamBlocks: keepIds(shown.slice(blocks.length), after),
528
687
  // why: A reply at rest leaves the run's own events (tokens, an ask); a paused one, the host's.
529
688
  session: this.#sessionAfter(session, view.paused?.events ?? events),
530
- chatStarted: view.transcript.length > 0 || view.paused !== undefined,
689
+ chatStarted: view.transcript.length > 0 || after.length > 0 || view.running !== undefined,
690
+ runningElsewhere: view.running ?? null,
531
691
  });
692
+ this.#wakeDue = view.wake === true;
532
693
  this.#setPush(view.notify);
694
+ this.#followHold();
695
+ // why: The reply that ran elsewhere ended as a reply here ends: the queue sends on, unless it was stopped.
696
+ if (ended && !this.#busy) {
697
+ this.#runEnded(!this.#stopped);
698
+ this.#stopped = false;
699
+ }
533
700
  }
534
701
  /**
535
702
  * Keeps the model and effort valid as the interface changes: a pick still on the old defaults
@@ -606,6 +773,7 @@ class Chat {
606
773
  this.#draining = true;
607
774
  // why: The message leaves the queue once it posts; one that never starts stays queued.
608
775
  void this.#sendDraft(message.draft, {
776
+ id: message.id,
609
777
  onPosted: () => this.#set({
610
778
  pendingMessages: removeComposerPendingMessage(this.#state.pendingMessages, message.id),
611
779
  }),
@@ -662,7 +830,8 @@ class Chat {
662
830
  });
663
831
  }
664
832
  /** The message posted: it joins the transcript, and the reply starts streaming. */
665
- #posted(blocks, patch) {
833
+ #posted(blocks, own, patch) {
834
+ this.#ownPosted = own;
666
835
  this.#setDelivery({ status: 'sending' });
667
836
  this.#set({
668
837
  blocks: [...this.#state.blocks, ...blocks],
@@ -683,8 +852,19 @@ class Chat {
683
852
  scope,
684
853
  view,
685
854
  transcript: this.#state.blocks,
686
- onUserBlocks: (blocks) => this.#posted(blocks, this.#clearedComposer()),
687
- }), { turn: true, message: { restore: () => this.#restore(fields) } });
855
+ onUserBlocks: (blocks, own) => this.#posted(blocks, own, this.#clearedComposer()),
856
+ }), {
857
+ turn: true,
858
+ message: {
859
+ id: newId(),
860
+ draft: () => encodeComposerDraft({
861
+ text: fields.text,
862
+ pendingFiles: fields.files,
863
+ pendingVoice: fields.voice,
864
+ }),
865
+ restore: () => this.#restore(fields),
866
+ },
867
+ });
688
868
  }
689
869
  #sendDraft(draft, options) {
690
870
  return this.#runTurn(({ iface, view, transport, scope, signal }) => streamInterfaceDraftTurn({
@@ -697,11 +877,18 @@ class Chat {
697
877
  view,
698
878
  transcript: this.#state.blocks,
699
879
  walkAway: options.walkAway === true,
700
- onUserBlocks: (blocks) => {
701
- this.#posted(blocks, { streamBlocks: [] });
880
+ onUserBlocks: (blocks, own) => {
881
+ this.#posted(blocks, own, { streamBlocks: [] });
702
882
  options.onPosted();
703
883
  },
704
- }), { turn: true, message: { restore: () => this.#restore(composerFieldsFromDraft(draft)) } });
884
+ }), {
885
+ turn: true,
886
+ message: {
887
+ id: options.id,
888
+ draft: () => Promise.resolve(draft),
889
+ restore: () => this.#restore(composerFieldsFromDraft(draft)),
890
+ },
891
+ });
705
892
  }
706
893
  /** The gate on the reply still running that no answer is on its way to. */
707
894
  #drawnGate() {
@@ -766,12 +953,33 @@ class Chat {
766
953
  const base = withPageToolDispatch(transport, pageTools);
767
954
  const tap = (onLine) => (line) => {
768
955
  this.#took(line);
956
+ if (line.type === 'conversation' && line.opened)
957
+ this.#opened(line.opened, onLine);
769
958
  onLine(line);
770
959
  };
771
960
  return {
772
961
  ...base,
773
962
  turn: (request, onLine, signal) => base.turn(this.#withValues(request), tap(onLine), signal),
774
963
  invoke: (request, onLine, signal) => base.invoke(request, tap(onLine), signal),
964
+ ...(base.wake
965
+ ? {
966
+ wake: (request, onLine, signal) => base.wake?.(this.#wakeValues(request), tap(onLine), signal) ?? Promise.resolve(),
967
+ }
968
+ : {}),
969
+ };
970
+ }
971
+ /** A wake carries the option picks and context a message would. */
972
+ #wakeValues(request) {
973
+ const { iface, options: fixed, context } = this.#options;
974
+ const options = picksOf(iface, fixed, this.#picked).values;
975
+ if (options === undefined && context === undefined)
976
+ return request;
977
+ return {
978
+ ...request,
979
+ input: {
980
+ ...(options === undefined ? {} : { options }),
981
+ ...(context === undefined ? {} : { context }),
982
+ },
775
983
  };
776
984
  }
777
985
  #withValues(request) {
@@ -801,10 +1009,43 @@ class Chat {
801
1009
  DELIVERY_ORDER.indexOf(reached) > DELIVERY_ORDER.indexOf(delivery.status)) {
802
1010
  this.#setDelivery({ status: reached });
803
1011
  }
804
- if (line.type === 'conversation')
1012
+ if (line.type === 'conversation') {
805
1013
  this.#adopt(line.ref);
806
- else
807
- this.#options.onTurnEvent?.(line);
1014
+ if (line.landsAs)
1015
+ this.#savedAs = line.landsAs;
1016
+ return;
1017
+ }
1018
+ this.#streamed = true;
1019
+ this.#options.onTurnEvent?.(line);
1020
+ }
1021
+ /**
1022
+ * A reply opened with messages the host saved before: they leave the pending list and join the
1023
+ * transcript where the reply reads them. That is before the message this run posted, when the
1024
+ * reply has streamed nothing.
1025
+ */
1026
+ #opened(ids, onLine) {
1027
+ const { iface } = this.#options;
1028
+ const { landed, remaining } = takeSavedComposerPending(this.#state.pendingMessages, ids);
1029
+ if (!iface || landed.length === 0)
1030
+ return;
1031
+ this.#set({ pendingMessages: remaining });
1032
+ const read = {
1033
+ type: 'stage',
1034
+ stage: 'pre_turn',
1035
+ injected: landed.map((m) => ({ id: m.id, messages: userDraftToSteerInject(m.draft) })),
1036
+ };
1037
+ if (this.#streamed || this.#ownPosted === 0) {
1038
+ onLine(read);
1039
+ return;
1040
+ }
1041
+ const at = this.#state.blocks.length - this.#ownPosted;
1042
+ this.#set({
1043
+ blocks: [
1044
+ ...this.#state.blocks.slice(0, at),
1045
+ ...foldAssistantTurn(iface, [read]),
1046
+ ...this.#state.blocks.slice(at),
1047
+ ],
1048
+ });
808
1049
  }
809
1050
  #streamFrame(partial) {
810
1051
  this.#frameBlocks = partial;
@@ -831,14 +1072,19 @@ class Chat {
831
1072
  const { message } = options;
832
1073
  const priorDelivery = this.#delivery;
833
1074
  const abort = options.turn ? new AbortController() : null;
834
- const turnId = options.turn ? newTurnId() : undefined;
1075
+ const turnId = options.turn ? newId() : undefined;
835
1076
  this.#busy = true;
836
1077
  this.#abort = abort;
837
1078
  this.#turnId = turnId ?? null;
838
1079
  this.#stopped = false;
839
1080
  this.#drainArmed = false;
1081
+ this.#savedAs = null;
1082
+ this.#ownPosted = 0;
1083
+ this.#streamed = false;
840
1084
  // why: A message streams once it posts, so the previous reply never shows as streaming before it.
841
- this.#set({ failure: null, ...(message ? {} : { streaming: true }) });
1085
+ // A wake shows only once the host's reply begins; one with nothing to wake for shows nothing.
1086
+ if (!options.wake)
1087
+ this.#set({ failure: null, ...(message ? {} : { streaming: true }) });
842
1088
  const start = { blocks: this.#state.blocks, streamBlocks: this.#state.streamBlocks };
843
1089
  // why: A run that answers a gate continues its reply; any other starts one.
844
1090
  if (!this.#state.session.gatedTool)
@@ -849,7 +1095,7 @@ class Chat {
849
1095
  const outcome = await run({
850
1096
  iface,
851
1097
  transport: this.#runTransport(),
852
- scope: { conversation: this.#conversation, turnId },
1098
+ scope: { conversation: this.#conversation, turnId, id: message?.id },
853
1099
  signal: abort?.signal,
854
1100
  view: {
855
1101
  blocks: (partial) => this.#streamFrame(partial),
@@ -866,7 +1112,7 @@ class Chat {
866
1112
  await this.#takeBack(start, message);
867
1113
  let waits;
868
1114
  if (keepsConversation(iface)) {
869
- waits = await this.#settleHosted(outcome, start);
1115
+ waits = await this.#settleHosted(outcome, start, options);
870
1116
  }
871
1117
  else if (unposted) {
872
1118
  this.#showFailure(outcome.failure);
@@ -922,7 +1168,7 @@ class Chat {
922
1168
  * in the composer unless the host's transcript closed on it. Returns whether the reply waits
923
1169
  * on gates.
924
1170
  */
925
- async #settleHosted(outcome, start) {
1171
+ async #settleHosted(outcome, start, { message, wake }) {
926
1172
  const { failure } = outcome;
927
1173
  if (failure)
928
1174
  this.#setDelivery(null);
@@ -933,12 +1179,34 @@ class Chat {
933
1179
  return this.#state.session.gatedTool !== null;
934
1180
  }
935
1181
  const view = await this.#options.transport.conversation({ conversation: ref });
1182
+ const savedAs = this.#savedAs;
1183
+ if (message && savedAs && !view.transcript.some((block) => savedAs.includes(block.id))) {
1184
+ await this.#keepSaved(message, savedAs);
1185
+ }
936
1186
  this.#draw(view, outcome.session, outcome.events);
1187
+ // why: The page does not repeat a run that failed or was stopped, or a wake the host ran nothing for (another reply holds the conversation). The next read can wake.
1188
+ if (failure || (wake && !this.#streamed))
1189
+ this.#wakeDue = false;
937
1190
  if (!view.transcript.slice(start.blocks.length).some((b) => b.kind === 'error')) {
938
1191
  this.#showFailure(failure);
939
1192
  }
940
1193
  return view.paused !== undefined;
941
1194
  }
1195
+ /** The host saved the message and no reply has read it: it waits with the pending messages. */
1196
+ async #keepSaved(message, landsAs) {
1197
+ this.#setDelivery(null);
1198
+ const waiting = createComposerPendingMessage({
1199
+ kind: 'steer',
1200
+ draft: await message.draft(),
1201
+ id: message.id,
1202
+ });
1203
+ this.#set({
1204
+ pendingMessages: orderComposerPendingMessages([
1205
+ ...this.#state.pendingMessages,
1206
+ { ...waiting, saved: { landsAs } },
1207
+ ]),
1208
+ });
1209
+ }
942
1210
  /**
943
1211
  * A stateless chat keeps the reply as the run streamed it: in the transcript once it ends
944
1212
  * (closed by its failure, or by the visitor's stop), or beside it while it waits on a gate.
@@ -1,22 +1,30 @@
1
+ import type { ComposerMenuAction } from '@theoremjs/agents/interface';
1
2
  /**
2
3
  * Composer hints — ephemeral guidance about the current composer interaction
3
4
  * (not pending-message state). Mirrors seance's `stash-selected-draft` hint.
4
5
  */
5
- /** Stash shortcut in Astryx `Kbd` notation (`mod` is ⌘ on macOS, Ctrl elsewhere). */
6
- export declare const STASH_SHORTCUT = "mod+shift+s";
7
- /** Which hint applies, and its shortcut; the UI words it. */
8
- export type ComposerHint = {
9
- id: 'stash-selected-draft';
10
- shortcut: string;
11
- };
12
- /** Whether a keydown is the stash shortcut (⌘⇧S / Ctrl+Shift+S). */
13
- export declare function isStashShortcut(event: {
6
+ /**
7
+ * Each send-menu action's key, in Astryx `Kbd` notation (`mod` is ⌘ on macOS, Ctrl elsewhere).
8
+ * `queue` is Enter: the composer's primary action while a reply runs.
9
+ */
10
+ export declare const COMPOSER_SHORTCUTS: Readonly<Record<ComposerMenuAction, string>>;
11
+ /**
12
+ * The send-menu action a keydown asks for: ⌘↵ steers, ⌘⇧↵ sends now, ⌘⇧S stashes (Ctrl
13
+ * elsewhere). `null` for any other key, plain Enter included: the field sends or queues that.
14
+ */
15
+ export declare function composerShortcut(event: {
14
16
  code: string;
17
+ key: string;
15
18
  metaKey: boolean;
16
19
  ctrlKey: boolean;
17
20
  shiftKey: boolean;
18
21
  altKey: boolean;
19
- }): boolean;
22
+ }): Exclude<ComposerMenuAction, 'queue'> | null;
23
+ /** Which hint applies, and its shortcut; the UI words it. */
24
+ export type ComposerHint = {
25
+ id: 'stash-selected-draft';
26
+ shortcut: string;
27
+ };
20
28
  /** The stash hint — shown while the whole draft is selected in the focused input and it can be stashed. */
21
29
  export declare function resolveComposerHint(args: {
22
30
  draftText: string;
@@ -2,11 +2,28 @@
2
2
  * Composer hints — ephemeral guidance about the current composer interaction
3
3
  * (not pending-message state). Mirrors seance's `stash-selected-draft` hint.
4
4
  */
5
- /** Stash shortcut in Astryx `Kbd` notation (`mod` is ⌘ on macOS, Ctrl elsewhere). */
6
- export const STASH_SHORTCUT = 'mod+shift+s';
7
- /** Whether a keydown is the stash shortcut (⌘⇧S / Ctrl+Shift+S). */
8
- export function isStashShortcut(event) {
9
- return (event.code === 'KeyS' && event.shiftKey && !event.altKey && (event.metaKey || event.ctrlKey));
5
+ /**
6
+ * Each send-menu action's key, in Astryx `Kbd` notation (`mod` is ⌘ on macOS, Ctrl elsewhere).
7
+ * `queue` is Enter: the composer's primary action while a reply runs.
8
+ */
9
+ export const COMPOSER_SHORTCUTS = {
10
+ queue: 'enter',
11
+ steer: 'mod+enter',
12
+ send_now: 'mod+shift+enter',
13
+ stash: 'mod+shift+s',
14
+ };
15
+ /**
16
+ * The send-menu action a keydown asks for: ⌘↵ steers, ⌘⇧↵ sends now, ⌘⇧S stashes (Ctrl
17
+ * elsewhere). `null` for any other key, plain Enter included: the field sends or queues that.
18
+ */
19
+ export function composerShortcut(event) {
20
+ if (event.altKey || !(event.metaKey || event.ctrlKey))
21
+ return null;
22
+ if (event.key === 'Enter')
23
+ return event.shiftKey ? 'send_now' : 'steer';
24
+ if (event.code === 'KeyS' && event.shiftKey)
25
+ return 'stash';
26
+ return null;
10
27
  }
11
28
  /** The stash hint — shown while the whole draft is selected in the focused input and it can be stashed. */
12
29
  export function resolveComposerHint(args) {
@@ -15,6 +32,6 @@ export function resolveComposerHint(args) {
15
32
  return null;
16
33
  return {
17
34
  id: 'stash-selected-draft',
18
- shortcut: STASH_SHORTCUT,
35
+ shortcut: COMPOSER_SHORTCUTS.stash,
19
36
  };
20
37
  }