@theoremjs/web 0.3.5-next.1013.g9b838d0 → 0.3.5-next.1016.gc4ded01

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.
@@ -9,11 +9,11 @@ import { compactHistory, defaultKernelScope, defineProfile, labelText, runTurn,
9
9
  import { runConversation, } from '@theoremjs/agents/conversation';
10
10
  import { interfaceFromProfile, refuseInterfacePick, } from '@theoremjs/agents/interface';
11
11
  import { answerReply, conversationView, messageReply, openConversation, postedMessage, readerConversationHost, rewindConversation, statelessRefusal, waitingCalls, wakeReply, } from "./conversation.js";
12
- import { detachedAt, detachedEnd, readerEnding, readerOf, sessionConversationInbox, } from "./conversation-inbox.js";
12
+ import { arrivePersonMessage, detachedEnd, readerEnding, readerOf, sessionConversationInbox, } from "./conversation-inbox.js";
13
13
  import { endedBlock, unknownConversation, } from "./conversation-store.js";
14
+ import { openRun, ownKey, ownPolicy, ownReads, personMessageOf, scopedStop, steerRun, } from "./own-inbox.js";
14
15
  import { sessionPageDispatch } from "./page-dispatch.js";
15
16
  import { announced, backgroundWiring, pausedWaits, recorded, replayAllowed, saveEnded, sessionCredentials, settlingOf, takeLapsed, takeWalkedAway, withAuthorizationUrls, } from "./session-calls.js";
16
- import { steerStage, steerUnitOf, stopOnRequest } from "./steer-inbox.js";
17
17
  import { sessionToolCoordinator } from "./tool-operations.js";
18
18
  import { isRefusal, preparedTurn, stagesInOrder } from "./turn-wiring.js";
19
19
  /**
@@ -77,20 +77,23 @@ async function* unheld(lines) {
77
77
  yield* lines;
78
78
  return { outcome: 'released' };
79
79
  }
80
- /** Steer inboxes are scoped to the session, so a turn id alone can't reach another user's turn. */
80
+ /** Aborts `target` when the stop asks for the reply; `over` ends the wait. */
81
+ function abortOnStop(stop, over, target, onError) {
82
+ stop.stopped(over).then((stopped) => {
83
+ if (stopped)
84
+ target.abort();
85
+ }, onError);
86
+ }
81
87
  /**
82
- * The refusal of a stop or steer by conversation on a host that can't reach a reply it does not
83
- * run: no app stop, or no intake for a steer. Not `turn_ended`: the reply may still be running.
88
+ * The refusal of a stop or steer by conversation for a reply the store says runs, which this
89
+ * process does not hold. Not `turn_ended`: the reply may still be running.
84
90
  */
85
- export function replyUnreachable() {
91
+ function replyUnreachable() {
86
92
  // labels-exempt: internal diagnostic; the user reads session.reply_unreachable
87
93
  return new TheoremError('request', 'this host cannot reach a reply that runs elsewhere', {
88
94
  copy: { key: 'session.reply_unreachable' },
89
95
  });
90
96
  }
91
- function inboxKey(sessionId, turnId) {
92
- return `${sessionId}\u0000${turnId}`;
93
- }
94
97
  const DEFAULT_CONVERSATION_LEASE_MS = 60_000;
95
98
  /**
96
99
  * The session's inbox for the chat: the chat as this context last wrote it, and the results this
@@ -111,36 +114,50 @@ function chatInbox(ctx, at, host, opened, ref) {
111
114
  },
112
115
  readable: (operation) => replayAllowed(ctx, at, operation),
113
116
  labels: ctx.profile.labels,
117
+ shelf: ctx.own.shelf,
114
118
  });
115
119
  return { inbox, key: opened.conversation.id, leaseMs };
116
120
  }
117
- /** The values `produce` sends, as it sends them, then its end or what it threw. */
121
+ /**
122
+ * The values `produce` sends, as it sends them, then its end or what it threw. `send` settles once
123
+ * the consumer has taken the value and gone on past it, so the producer never runs ahead of what
124
+ * the consumer has handled. A producer awaits each `send`. When the consumer stops early, each
125
+ * `send` still waiting settles.
126
+ */
118
127
  async function* sent(produce) {
119
128
  const queue = [];
120
129
  let ended;
121
130
  let wake = () => { };
122
- produce((value) => {
123
- queue.push(value);
131
+ produce((value) => new Promise((handled) => {
132
+ queue.push({ value, handled });
124
133
  wake();
125
- }).then((value) => {
134
+ })).then((value) => {
126
135
  ended = { failed: false, value };
127
136
  wake();
128
137
  }, (failure) => {
129
138
  ended = { failed: true, failure };
130
139
  wake();
131
140
  });
132
- for (;;) {
133
- if (queue.length > 0) {
134
- yield queue.splice(0, 1)[0];
135
- continue;
141
+ try {
142
+ for (;;) {
143
+ const next = queue.shift();
144
+ if (next) {
145
+ yield next.value;
146
+ next.handled();
147
+ continue;
148
+ }
149
+ if (ended?.failed)
150
+ throw ended.failure;
151
+ if (ended)
152
+ return ended.value;
153
+ await new Promise((resolve) => {
154
+ wake = resolve;
155
+ });
136
156
  }
137
- if (ended?.failed)
138
- throw ended.failure;
139
- if (ended)
140
- return ended.value;
141
- await new Promise((resolve) => {
142
- wake = resolve;
143
- });
157
+ }
158
+ finally {
159
+ for (const waiting of queue.splice(0))
160
+ waiting.handled();
144
161
  }
145
162
  }
146
163
  function holdingOver(kept, chat) {
@@ -171,23 +188,19 @@ function holdingOver(kept, chat) {
171
188
  for (const id of ids)
172
189
  told.add(id);
173
190
  },
174
- ...(stop
175
- ? {
176
- stop: {
177
- stopped: (over) => stop.stopped(key, run.hold, over),
178
- clear: () => stop.clear(key, run.hold),
179
- },
180
- }
181
- : {}),
191
+ stop: {
192
+ stopped: (over) => stop.stopped(key, run.hold, over),
193
+ clear: () => stop.clear(key, run.hold),
194
+ },
182
195
  };
183
196
  const ref = chat.ref();
184
197
  // why: The page moves a message it shows as waiting into the reply that reads it, as the reply starts.
185
198
  if (run.opened.length > 0 && ref !== null) {
186
- send({ type: 'conversation', ref, opened: run.opened.map((item) => item.id) });
199
+ await send({ type: 'conversation', ref, opened: run.opened.map((item) => item.id) });
187
200
  }
188
201
  for await (const line of lines(held)) {
189
202
  chat.seen(line);
190
- send(line);
203
+ await send(line);
191
204
  }
192
205
  },
193
206
  gaveUp: kept.gaveUp,
@@ -252,30 +265,54 @@ function appHolding(ctx, at, ref) {
252
265
  policy: app.policy,
253
266
  reads: (run) => ({ from: 'app', run }),
254
267
  gaveUp: gaveUp(ctx, at, 'inbox_items_given_up'),
255
- ...(app.stop ? { stop: app.stop } : {}),
268
+ stop: app.stop ?? scopedStop(ctx.own.stop, at.sessionId),
256
269
  }, chatRef(ref));
257
270
  }
258
271
  /**
259
- * The inbox this context's replies hold: the app's when it passes one, the session's when a
260
- * decider tells its late results, and none otherwise.
272
+ * The inbox a reply holds when the app passes none: Theorem's own, named `key`. It holds the
273
+ * person's messages beside the late results the decider tells.
261
274
  */
275
+ function ownHolding(own, chat) {
276
+ const { decider } = own;
277
+ return holdingOver({
278
+ inbox: own.inbox,
279
+ key: own.key,
280
+ leaseMs: own.leaseMs,
281
+ policy: ownPolicy({ ...(decider ? { decider } : {}), host: own.host }),
282
+ reads: (run) => {
283
+ const reads = ownReads(run);
284
+ return {
285
+ from: 'own',
286
+ ...(decider ? { late: reads.late } : {}),
287
+ stage: reads.stage,
288
+ settle: (ids) => own.settle(run, reads.mine(ids)),
289
+ settles: own.settles,
290
+ };
291
+ },
292
+ gaveUp: own.gaveUp,
293
+ stop: scopedStop(own.stop, own.scope),
294
+ }, chat);
295
+ }
296
+ /** The inbox this context's replies hold: the app's when it passes one, Theorem's own otherwise. */
262
297
  function holdingOf(ctx, at, host, opened) {
263
298
  const app = appHolding(ctx, at, opened.ref);
264
299
  if (app)
265
300
  return app;
266
301
  const chat = chatRef(opened.ref);
302
+ const { inbox, key, leaseMs } = chatInbox(ctx, at, host, opened, chat.ref);
267
303
  const decider = ctx.options.lateResultsDecider;
268
- if (!decider)
269
- return undefined;
270
304
  let whose;
271
- return holdingOver({
272
- ...chatInbox(ctx, at, host, opened, chat.ref),
273
- policy: async (items, moment) => {
274
- whose ??= Promise.resolve(at.host);
275
- return decider.policy(items, { ...moment, host: await whose });
276
- },
277
- reads: (run) => ({ from: 'session', late: lateSource(run) }),
305
+ return ownHolding({
306
+ scope: at.sessionId,
307
+ stop: ctx.own.stop,
308
+ inbox,
309
+ key,
310
+ leaseMs,
311
+ ...(decider ? { decider } : {}),
312
+ host: () => (whose ??= Promise.resolve(at.host)),
278
313
  gaveUp: gaveUp(ctx, at, 'late_results_given_up'),
314
+ settle: (_run, ids) => inbox.settle(key, ids),
315
+ settles: 'save',
279
316
  }, chat);
280
317
  }
281
318
  /**
@@ -288,8 +325,6 @@ function holdingOf(ctx, at, host, opened) {
288
325
  function heldLines(ctx, at, host, opened, start, reply) {
289
326
  const holding = holdingOf(ctx, at, host, opened);
290
327
  const feed = (lines) => fed(ctx, at, opened.conversation.id, lines);
291
- if (!holding)
292
- return feed(unheld(reply(undefined, () => opened.ref)));
293
328
  return feed(sent(async (send) => {
294
329
  const run = await holding.run(start, (held) => reply(held, holding.ref), send);
295
330
  if (run.outcome === 'held')
@@ -442,45 +477,25 @@ async function isPaused(host, ref, fallback) {
442
477
  const conversation = ref === null ? fallback : (await host.store.read(host.sessionId, ref))?.conversation;
443
478
  return conversation?.paused !== undefined;
444
479
  }
445
- /** The late results a reply's model reads: what it opened with, then what each later moment hands it. */
446
- function lateSource(run) {
447
- let opening = true;
448
- return async ({ stage, step }) => {
449
- if (opening && stage === 'pre_turn') {
450
- opening = false;
451
- return run.opened.map((item) => item.outcome);
452
- }
453
- return (await run.take({ stage, step })).map((item) => item.outcome);
454
- };
455
- }
456
480
  /** One model run of a chat's reply, its gates recorded in the session as they pause. */
457
- async function* chatTurn(ctx, at, turn, key, signal, stop, held, refused) {
481
+ async function* chatTurn(ctx, at, turn, signal, stop, held, refused) {
458
482
  const state = await ctx.sessions.read(at.sessionId);
459
483
  const provider = await ctx.options.provider(at, turn.model);
460
484
  const host = await at.host;
461
485
  const over = new AbortController();
462
- if (key)
463
- await ctx.steer.open(key);
464
- if (held?.stop) {
465
- held.stop.stopped(over.signal).then((stopped) => {
466
- if (stopped)
467
- stop.abort();
468
- }, (err) => ctx.options.onError?.(err, at));
469
- }
470
- else if (key) {
471
- stopOnRequest(ctx.steer, key, stop);
472
- }
486
+ abortOnStop(held.stop, over.signal, stop, (err) => ctx.options.onError?.(err, at));
487
+ const landed = [];
473
488
  try {
474
- const onStage = stagesInOrder(ctx.options.onStage, key ? steerStage(ctx.steer, key) : undefined);
489
+ const onStage = stagesInOrder(ctx.options.onStage, held.reads.from === 'own' ? held.reads.stage : undefined);
475
490
  const { prepare } = ctx.options;
476
- const run = held?.reads.from === 'app' ? held.reads.run : undefined;
491
+ const run = held.reads.from === 'app' ? held.reads.run : undefined;
477
492
  const prepared = await preparedTurn(prepare && ((request) => prepare(request, run)), {
478
493
  profile: ctx.profile.id,
479
494
  execution: sessionToolCoordinator(ctx.sessions, at.sessionId),
480
495
  ...backgroundWiring(ctx, at),
481
496
  pageExecution: sessionPageDispatch(ctx.sessions, at.sessionId, ctx.pageToolBroker, ctx.options.pageToolTimeoutMs).execution,
482
497
  input: turn.input,
483
- ...(held?.reads.from === 'session' ? { lateResults: held.reads.late } : {}),
498
+ ...(held.reads.from === 'own' && held.reads.late ? { lateResults: held.reads.late } : {}),
484
499
  ...(turn.conversationId ? { conversationId: turn.conversationId } : {}),
485
500
  ...(turn.providerState ? { providerState: turn.providerState } : {}),
486
501
  sessionPermissions: state.permissions,
@@ -502,18 +517,20 @@ async function* chatTurn(ctx, at, turn, key, signal, stop, held, refused) {
502
517
  return;
503
518
  }
504
519
  const events = runTurn(prepared, provider);
505
- yield* recorded(ctx.sessions, at.sessionId, withAuthorizationUrls(ctx, at, events), {
506
- profileId: ctx.profile.id,
507
- turnInput: turn.input,
508
- model: turn.model,
509
- });
520
+ for await (const event of recorded(ctx.sessions, at.sessionId, withAuthorizationUrls(ctx, at, events), { profileId: ctx.profile.id, turnInput: turn.input, model: turn.model })) {
521
+ if (event.type === 'stage')
522
+ landed.push(...(event.injected ?? []).map((inject) => inject.id));
523
+ yield event;
524
+ }
510
525
  }
511
526
  finally {
512
527
  over.abort();
513
528
  // why: A stop that stays set would stop the follow-up, which keeps this hold.
514
- await held?.stop?.clear().catch((err) => ctx.options.onError?.(err, at));
515
- if (key)
516
- await ctx.steer.close(key);
529
+ await held.stop.clear().catch((err) => ctx.options.onError?.(err, at));
530
+ // why: A chat that keeps no conversation saves no reply, so its turn tells the message it landed.
531
+ if (held.reads.from === 'own' && held.reads.settles === 'turn') {
532
+ await held.reads.settle(landed).catch((err) => ctx.options.onError?.(err, at));
533
+ }
517
534
  }
518
535
  }
519
536
  /**
@@ -523,12 +540,11 @@ async function* chatTurn(ctx, at, turn, key, signal, stop, held, refused) {
523
540
  function chatRunner(ctx, at, generation, held) {
524
541
  // invariant: The page's pick is checked here, before prepare; a model prepare sets is the host's own.
525
542
  refuseInterfacePick(ctx.profile, generation);
526
- const key = generation.turnId ? inboxKey(at.sessionId, generation.turnId) : undefined;
527
543
  const stop = new AbortController();
528
- const signal = AbortSignal.any([at.signal, stop.signal, ...(held ? [held.run.signal] : [])]);
544
+ const signal = AbortSignal.any([at.signal, stop.signal, held.run.signal]);
529
545
  let refusal;
530
546
  return {
531
- run: (turn) => chatTurn(ctx, at, turn, key, signal, stop, held, (refused) => {
547
+ run: (turn) => chatTurn(ctx, at, turn, signal, stop, held, (refused) => {
532
548
  refusal = refused;
533
549
  }),
534
550
  refused: () => refusal,
@@ -547,7 +563,9 @@ function chatRunner(ctx, at, generation, held) {
547
563
  ...(generation.effort ? { effort: generation.effort } : {}),
548
564
  ...(generation.stated ? { stated: generation.stated } : {}),
549
565
  signal,
550
- ...(held ? { reply: held.run.reply, hold: held.run.hold, held: held.renew } : {}),
566
+ reply: held.run.reply,
567
+ hold: held.run.hold,
568
+ held: held.renew,
551
569
  saving: replySaving(ctx, at, held),
552
570
  };
553
571
  }
@@ -559,14 +577,18 @@ function replySaving(ctx, at, held) {
559
577
  ? {
560
578
  before: (reply) => beforeSave(at, {
561
579
  ...reply,
562
- ...(held?.reads.from === 'app' ? { held: held.reads.run } : {}),
580
+ ...(held.reads.from === 'app' ? { held: held.reads.run } : {}),
563
581
  }),
564
582
  }
565
583
  : {}),
566
584
  written: (appended) => saveEnded(ctx, at, appended),
567
- after: async (saved) => {
568
- held?.told(saved.told);
569
- await afterSave?.(at, saved);
585
+ after: async ({ ended, told, landed }) => {
586
+ held.told(told);
587
+ // invariant: A reply whose hold lost the chat tells nothing, and its messages wait for the hold that has it.
588
+ if (held.reads.from === 'own' && held.reads.settles === 'save' && ended !== 'lost') {
589
+ await held.reads.settle(landed);
590
+ }
591
+ await afterSave?.(at, { ended, told });
570
592
  },
571
593
  ...(compact ? { compact: (signal) => compact(at, signal) } : {}),
572
594
  report: (err) => onError?.(err, at),
@@ -591,8 +613,6 @@ function conversationHost(ctx, at) {
591
613
  */
592
614
  async function wakeLines(ctx, at, host, ref, generation, input) {
593
615
  const opened = await openConversation(host, ref, { kind: 'read' });
594
- if (!holds(ctx))
595
- return unheld(noLines());
596
616
  const waits = await pausedWaits(ctx, at, opened.conversation);
597
617
  if (waits)
598
618
  return waiting(waits);
@@ -643,9 +663,7 @@ async function currentView(ctx, at, host, ref, opened) {
643
663
  const view = { ...conversationView(host, conversation), ...(running ? { running } : {}) };
644
664
  const { replyFeed, inbox } = ctx.options;
645
665
  const following = replyFeed ? { follow: true } : {};
646
- // why: a session's late results come from detached calls only, ended or not; an app's items come from anywhere
647
- if (!view.transcript.some(wasDetached) && !inbox && !replyFeed)
648
- return view;
666
+ // why: a person's message can wait in any chat, so every view asks whether the chat wakes
649
667
  const wake = (await wakeDue(ctx, at, host, ref, conversation)) ? { wake: true } : {};
650
668
  if (!view.transcript.some(isDetachedBlock)) {
651
669
  return {
@@ -675,20 +693,11 @@ function notifyOffer(ctx) {
675
693
  async function wakeDue(ctx, at, host, ref, conversation) {
676
694
  if (await pausedWaits(ctx, at, conversation))
677
695
  return false;
678
- const holding = holdingOf(ctx, at, host, { ref, conversation });
679
- return holding ? holding.due() : false;
680
- }
681
- /** Whether a reply runs under a hold of the chat: the app passes an inbox, or a decider tells late results. */
682
- function holds(ctx) {
683
- return ctx.options.inbox !== undefined || ctx.options.lateResultsDecider !== undefined;
696
+ return holdingOf(ctx, at, host, { ref, conversation }).due();
684
697
  }
685
698
  function isDetachedBlock(block) {
686
699
  return block.kind === 'tool' && block.tool.state?.phase === 'background';
687
700
  }
688
- /** A detached call's block, whether its end is saved on it or not. */
689
- function wasDetached(block) {
690
- return block.kind === 'tool' && detachedAt(block.tool) !== undefined;
691
- }
692
701
  /**
693
702
  * A detached call's block as its operation stands, for a block whose end no save put on it. One
694
703
  * the session no longer holds has no known end.
@@ -723,7 +732,7 @@ async function lateBlock(ctx, at, block, operations, host) {
723
732
  }
724
733
  /** The answer's reply, handed first what the paused reply read, so it tells them as it goes on. */
725
734
  async function* answered(held, paused, reply) {
726
- if (held && paused)
735
+ if (paused)
727
736
  await held.run.resume(paused);
728
737
  yield* reply();
729
738
  }
@@ -749,6 +758,90 @@ async function messageOpened(ctx, at, args) {
749
758
  });
750
759
  return { posted, kept: { host, opened } };
751
760
  }
761
+ /**
762
+ * Runs `lines` under a hold of the run's own inbox, opened with `openRun`. The reply takes each
763
+ * message `steerRun` puts in, one at each step, and a stop asked of the run's name (the stop of
764
+ * `own`) aborts `NamedHold.signal`. A message that waits when the run ends is not told.
765
+ */
766
+ export function namedRun(args, lines) {
767
+ return namedHolding(args, (held) => {
768
+ const stop = new AbortController();
769
+ const over = new AbortController();
770
+ abortOnStop(held.stop, over.signal, stop, (err) => args.onError?.(err));
771
+ const signal = AbortSignal.any([args.signal, stop.signal, held.run.signal]);
772
+ return (async function* () {
773
+ const landed = [];
774
+ try {
775
+ for await (const line of lines({
776
+ stage: held.reads.from === 'own' ? held.reads.stage : () => undefined,
777
+ signal,
778
+ })) {
779
+ if (line.type === 'stage') {
780
+ landed.push(...(line.injected ?? []).map((inject) => inject.id));
781
+ }
782
+ yield line;
783
+ }
784
+ }
785
+ finally {
786
+ over.abort();
787
+ // why: A stop that stays set would stop the next run under this hold.
788
+ await held.stop.clear().catch((err) => args.onError?.(err));
789
+ if (held.reads.from === 'own' && held.reads.settles === 'turn') {
790
+ await held.reads.settle(landed).catch((err) => args.onError?.(err));
791
+ }
792
+ }
793
+ })();
794
+ });
795
+ }
796
+ /** The reply of a run, as `namedRun` and a chat that keeps no conversation run it. */
797
+ function namedHolding(args, lines, report) {
798
+ const { memory } = args.run;
799
+ const holding = ownHolding({
800
+ scope: args.scope,
801
+ stop: args.own.stop,
802
+ inbox: memory,
803
+ key: args.name,
804
+ leaseMs: args.leaseMs,
805
+ host: () => Promise.resolve(undefined),
806
+ gaveUp: report ?? (() => undefined),
807
+ settle: (run, ids) => {
808
+ memory.settle(args.name, run.hold, run.reply, ids);
809
+ return Promise.resolve();
810
+ },
811
+ settles: 'turn',
812
+ }, chatRef(null));
813
+ return sent(async (send) => {
814
+ const run = await holding.run({ opening: 'message', takeOver: true }, lines, send);
815
+ if (run.outcome === 'held')
816
+ return { outcome: 'held', leasedUntil: run.leasedUntil };
817
+ if (run.outcome === 'continue')
818
+ await holding.letGo(run.hold);
819
+ if (run.failure !== undefined)
820
+ throw run.failure;
821
+ return { outcome: run.outcome === 'lost' ? 'lost' : 'released' };
822
+ });
823
+ }
824
+ /**
825
+ * The reply of a chat that keeps no conversation. Its inbox is its run's: Theorem's own, in
826
+ * memory, named by the `turnId` the page sent (a random one when it sent none), for as long as the
827
+ * run lasts. A message that waits when the run ends is not told; the page sends it again.
828
+ */
829
+ async function* runLines(ctx, at, generation, posted) {
830
+ const name = generation.turnId ?? crypto.randomUUID();
831
+ const leaseMs = ctx.options.conversationLeaseMs ?? DEFAULT_CONVERSATION_LEASE_MS;
832
+ const run = openRun(ctx.own, at.sessionId, name, leaseMs);
833
+ try {
834
+ return yield* namedHolding({ own: ctx.own, scope: at.sessionId, name, run, leaseMs }, (held) => chatRunner(ctx, at, generation, held).run({
835
+ input: posted.input,
836
+ model: generation.model,
837
+ effort: generation.effort,
838
+ ...(generation.stated ? { stated: generation.stated } : {}),
839
+ }), gaveUp(ctx, at, 'inbox_items_given_up'));
840
+ }
841
+ finally {
842
+ run.close();
843
+ }
844
+ }
752
845
  /** The person's message: a new reply, run against the conversation the app keeps. */
753
846
  async function message(ctx, at, args) {
754
847
  const { generation = {}, saved } = args;
@@ -757,15 +850,8 @@ async function message(ctx, at, args) {
757
850
  throw new TheoremError('config', "a `saved` message needs `inbox`: its hold is in the app's inbox");
758
851
  }
759
852
  const { posted, kept } = await messageOpened(ctx, at, args);
760
- if (!kept) {
761
- const runner = chatRunner(ctx, at, generation);
762
- return unheld(runner.run({
763
- input: posted.input,
764
- model: generation.model,
765
- effort: generation.effort,
766
- ...(generation.stated ? { stated: generation.stated } : {}),
767
- }));
768
- }
853
+ if (!kept)
854
+ return runLines(ctx, at, generation, posted);
769
855
  const { host, opened } = kept;
770
856
  // why: Take the walked-away calls before streaming, so a stale one is a reply status, not a stream error.
771
857
  const walkAway = args.abandon
@@ -774,7 +860,7 @@ async function message(ctx, at, args) {
774
860
  const start = saved
775
861
  ? { opening: 'message', hold: saved.hold }
776
862
  : { opening: 'message', takeOver: true };
777
- return heldLines(ctx, at, host, opened, start, (held) => messageReply({
863
+ const lines = heldLines(ctx, at, host, opened, start, (held) => messageReply({
778
864
  host,
779
865
  opened,
780
866
  message: posted,
@@ -782,6 +868,24 @@ async function message(ctx, at, args) {
782
868
  ...(saved ? { saved: saved.blocks } : {}),
783
869
  runner: chatRunner(ctx, at, generation, held),
784
870
  }));
871
+ return generation.turnId === undefined
872
+ ? lines
873
+ : namedTurn(ctx.own, at.sessionId, generation.turnId, opened.conversation.id, lines);
874
+ }
875
+ /**
876
+ * A reply of a stored chat, known by the page's `turnId` for as long as it runs, so a steer or stop
877
+ * that names the turn reaches the conversation's inbox and hold.
878
+ */
879
+ async function* namedTurn(own, scope, turnId, conversation, lines) {
880
+ const key = ownKey(scope, turnId);
881
+ own.turns.set(key, conversation);
882
+ try {
883
+ return yield* lines;
884
+ }
885
+ finally {
886
+ if (own.turns.get(key) === conversation)
887
+ own.turns.delete(key);
888
+ }
785
889
  }
786
890
  /** The answered call's events, for a session that keeps no conversation. */
787
891
  export async function unconversedAnswer(ctx, at, body) {
@@ -830,15 +934,13 @@ async function followUp(ctx, at, args) {
830
934
  const host = conversationHost(ctx, at);
831
935
  if (!host)
832
936
  throw statelessRefusal('wake');
833
- if (!holds(ctx))
834
- return unheld(noLines());
835
937
  const opened = await openConversation(host, args.ref, { kind: 'read' }).catch(async (err) => {
836
938
  // why: a follow-up that cannot open its chat runs nothing, so the hold is let go at once
837
939
  await appHolding(ctx, at, args.ref)?.letGo(args.hold);
838
940
  throw err;
839
941
  });
840
942
  if (await pausedWaits(ctx, at, opened.conversation)) {
841
- await holdingOf(ctx, at, host, opened)?.letGo(args.hold);
943
+ await holdingOf(ctx, at, host, opened).letGo(args.hold);
842
944
  return unheld(noLines());
843
945
  }
844
946
  const start = { opening: 'follow_up', hold: args.hold };
@@ -856,7 +958,7 @@ async function release(ctx, at, args) {
856
958
  if (!host)
857
959
  throw statelessRefusal('wake');
858
960
  const opened = await openConversation(host, args.ref, { kind: 'read' });
859
- await holdingOf(ctx, at, host, opened)?.letGo(args.hold);
961
+ await holdingOf(ctx, at, host, opened).letGo(args.hold);
860
962
  }
861
963
  /** The conversation as a page draws it. */
862
964
  async function read(ctx, at, args) {
@@ -904,18 +1006,65 @@ export function createConversationCore(state) {
904
1006
  read: (at, args) => read(state, at, args),
905
1007
  rewind: (at, args) => rewind(state, at, args),
906
1008
  follow: (at, args) => follow(state, at, args),
907
- steer: async (at, { turnId, ...steer }) => {
908
- postedMessage(chatInterface(state.chat), steer.input);
909
- return await state.steer.enqueue(inboxKey(at.sessionId, turnId), steerUnitOf(steer));
1009
+ steer: async (at, args) => {
1010
+ if (state.options.inbox) {
1011
+ // labels-exempt: builder config error; the user reads error.config
1012
+ throw new TheoremError('config', "a steer goes through `intake`: the app's inbox holds the message");
1013
+ }
1014
+ postedMessage(chatInterface(state.chat), args.input);
1015
+ const message = personMessageOf(args);
1016
+ const arrive = async (conversation) => {
1017
+ if (!state.own.stop.running(ownKey(at.sessionId, conversation)))
1018
+ return false;
1019
+ await arrivePersonMessage({ sessions: state.sessions, sessionId: at.sessionId, shelf: state.own.shelf }, conversation, message);
1020
+ return true;
1021
+ };
1022
+ if ('turnId' in args) {
1023
+ const held = state.own.turns.get(ownKey(at.sessionId, args.turnId));
1024
+ return held === undefined
1025
+ ? steerRun(state.own, at.sessionId, args.turnId, message)
1026
+ : arrive(held);
1027
+ }
1028
+ const host = conversationHost(state, at);
1029
+ if (!host)
1030
+ throw statelessRefusal('steer');
1031
+ const { conversation, running } = await openConversation(host, args.ref, { kind: 'read' });
1032
+ if (await arrive(conversation.id))
1033
+ return true;
1034
+ if (running)
1035
+ throw replyUnreachable();
1036
+ return false;
910
1037
  },
911
- stop: (at, args) => {
1038
+ stop: async (at, args) => {
912
1039
  const app = state.options.inbox?.(at);
913
- if (app?.stop)
914
- return app.stop.ask(app.conversation);
915
- // why: without the app's stop, only this server's turns are known, each by its id
916
- if (!('turnId' in args))
1040
+ const own = scopedStop(state.own.stop, at.sessionId);
1041
+ if (app) {
1042
+ if (await (app.stop ?? own).ask(app.conversation))
1043
+ return true;
1044
+ if (app.stop || 'turnId' in args)
1045
+ return false;
1046
+ const host = conversationHost(state, at);
1047
+ if (!host)
1048
+ return false;
1049
+ const { running } = await openConversation(host, args.conversation, { kind: 'read' });
1050
+ if (running)
1051
+ throw replyUnreachable();
1052
+ return false;
1053
+ }
1054
+ if ('turnId' in args) {
1055
+ return own.ask(state.own.turns.get(ownKey(at.sessionId, args.turnId)) ?? args.turnId);
1056
+ }
1057
+ const host = conversationHost(state, at);
1058
+ if (!host)
1059
+ throw statelessRefusal('stop');
1060
+ const { conversation, running } = await openConversation(host, args.conversation, {
1061
+ kind: 'read',
1062
+ });
1063
+ if (await own.ask(conversation.id))
1064
+ return true;
1065
+ if (running)
917
1066
  throw replyUnreachable();
918
- return Promise.resolve(state.steer.stop(inboxKey(at.sessionId, args.turnId)));
1067
+ return false;
919
1068
  },
920
1069
  };
921
1070
  }