@theoremjs/web 0.3.5-next.1004.gd674e6b → 0.3.5-next.1005.geaafb0b

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/README.md CHANGED
@@ -66,6 +66,7 @@ export const theorem = createTheoremHandler({
66
66
  profile: support,
67
67
  provider: { vault: { main: process.env.GEMINI_API_KEY } },
68
68
  conversationStore: createMemoryConversationStore(),
69
+ operationRetentionMs: 24 * 60 * 60 * 1000, // a day: how long a finished call's result is kept
69
70
  });
70
71
  ```
71
72
 
@@ -128,6 +129,7 @@ const boundary = await createTheoremSessionBoundary({
128
129
  request,
129
130
  session: authenticatedConversation,
130
131
  sessionStore: sharedSessionStore,
132
+ operationRetentionMs: 24 * 60 * 60 * 1000,
131
133
  });
132
134
  const open = parseLiveOpenMessage(firstFrame);
133
135
  const session = await runSession(
@@ -298,17 +300,16 @@ const transport = withPageToolDispatch(
298
300
  | `gateTtlMs` | How long a gate waits for an answer. A later answer fails with `session.gate_expired`, and the next message or the next wake cancels the call. Unset, a gate waits until it is answered. |
299
301
  | `maxRequestBytes` | The largest browser request body, in bytes. Unset, a body of any size is read. |
300
302
  | `pageToolTimeoutMs` | How long the page has to answer a tool call it runs. A call it has not answered by then settles as timed out. Unset, the call waits until the page answers or the turn stops. The browser clients answer every call they get, so only a page function that never returns holds a turn. |
301
- | `operationRetentionMs` | How long a settled tool result is kept. Default: 24 hours. |
303
+ | `operationRetentionMs` | Required. How long the session keeps a finished tool call's result, in milliseconds from when it finished. While it is kept, the same call asked for again gets that result and does not run again. Your app decides it: the handler has no default. |
302
304
  | `clientEvents` | Options for `forClient` and `clientError`, which prepare each event and each caught failure for the browser. `reader: 'builder'` sends the raw reason in place of the wording of the profile. Use it only in a development tool on your own machine. |
303
305
  | `onError` | Receives each error that the handler catches. A visitor sees the wording of the profile for that kind of error, never the error. |
304
306
 
305
307
  ### Defaults
306
308
 
307
- A limit that stops a turn or refuses a request is unset unless you set it: `gateTtlMs`, `maxRequestBytes`, `pageToolTimeoutMs`, and a session store's `capacity`. The memory stores expire and evict nothing unless you set `ttlMs` and `maxSessions`, so they grow until the process ends. Set both on a public server. These have a default:
309
+ A limit that stops a turn or refuses a request is unset unless you set it: `gateTtlMs`, `maxRequestBytes`, `pageToolTimeoutMs`, and a session store's `capacity`. `operationRetentionMs` has no default, so every handler sets it. The memory stores expire and evict nothing unless you set `ttlMs` and `maxSessions`, so they grow until the process ends. Set both on a public server. These have a default:
308
310
 
309
311
  | What | Default | Set it with |
310
312
  | --- | --- | --- |
311
- | A settled tool result | Kept 24 hours | `operationRetentionMs` |
312
313
  | The session cookie | Lasts 30 days | `session` |
313
314
 
314
315
  A model profile that leaves out `maxSteps` makes at most 20 model calls a turn.
@@ -360,12 +361,13 @@ The sealed store:
360
361
  - If the user stops a reply, or the browser leaves while a reply runs, the server saves the result under a new ref that the browser never receives. The browser keeps the ref from when its message reached the server. The reply, and any tool call it settled, is lost to the browser. With the memory store or your own store, the ref does not change, and the chat shows what the server saved.
361
362
  - The ref holds the whole conversation, including the bytes of each attachment. Every request sends it, so the conversation must stay under `maxRequestBytes`.
362
363
 
363
- To keep conversations in your own database, implement these two methods:
364
+ To keep conversations in your own database, implement these three methods:
364
365
 
365
366
  ```ts
366
367
  import type {
367
368
  ConversationSnapshot,
368
369
  ConversationWriteResult,
370
+ DetachedEnding,
369
371
  StoredConversation,
370
372
  } from '@theoremjs/web/server';
371
373
 
@@ -377,6 +379,7 @@ interface ConversationDatabase {
377
379
  expectedRevision: string | null,
378
380
  next: StoredConversation,
379
381
  ): Promise<ConversationWriteResult>;
382
+ end(sessionId: string, ending: DetachedEnding): Promise<void>;
380
383
  }
381
384
  ```
382
385
 
@@ -387,6 +390,7 @@ interface ConversationDatabase {
387
390
  - A store that keeps each block in its own place (a row, a column) checks one block with `transcriptBlockSchema`.
388
391
  - Keep `id` as the handler gives it. It names the conversation in each turn's trace as `gen_ai.conversation.id`, and stays the same through every save and rewind.
389
392
  - Set `running` on the snapshot while a reply runs on the conversation under a hold you keep. See [Show a reply that runs elsewhere](#show-a-reply-that-runs-elsewhere).
393
+ - `end` saves how a background call ended on the step of the reply that started it. The handler calls it when the call ends, and again after each save of a reply, for a call that ended before its reply was saved. Find the tool block whose `tool.operationId` is `ending.operationId`, in any of the session's conversations, and replace it with `endedBlock(block, ending)`. Change no revision, so a reply that runs meanwhile still saves. Keep the ended block when a later `write` still holds the block as it detached. With no such block, change nothing. A call whose end is saved shows its end and its done label after the session has dropped its record. A store that keeps nothing, such as the sealed store, does nothing in `end`: the conversation read shows the end from the session's record while the session keeps it. With `authorizeToolReplay`, the handler does not call `end`, because every request reads a saved end and that check runs on each read.
390
394
 
391
395
  ### Share session authority
392
396
 
@@ -443,7 +447,7 @@ Supply `authorizeToolReplay` for current role or resource access checks. This re
443
447
  If execution ends without a saved outcome, the claim remains running or becomes uncertain.
444
448
  The handler never restores that operation as an approval. The host must check the destination before any new action.
445
449
  Saved outcomes include guarded model read-back, media, provenance, and suspicious content signals.
446
- The handler retains settled operations for 24 hours from settlement by default. Set `operationRetentionMs` to change this window.
450
+ The handler retains settled operations for `operationRetentionMs` from settlement.
447
451
  Each saved outcome records its absolute retention deadline. Changing a handler's policy does not shorten that deadline.
448
452
  Each issued gate records its absolute expiry. Changing `gateTtlMs` does not extend an issued gate.
449
453
  Ready, running, background, and uncertain operations do not expire.
@@ -607,6 +611,7 @@ createTheoremHandler({
607
611
  profile,
608
612
  provider,
609
613
  conversationStore,
614
+ operationRetentionMs,
610
615
  inbox,
611
616
  intake: async (at, sent) => {
612
617
  const saved = await saveMessage(at.sessionId, sent.id, sent.ref, sent.message);
@@ -43,6 +43,7 @@ const toolCall = z.object({
43
43
  state: toolCallState.optional(),
44
44
  startedAt: z.number().optional(),
45
45
  endedAt: z.number().optional(),
46
+ detached: z.object({ at: z.number(), readBack: z.string().optional() }).optional(),
46
47
  get steps() {
47
48
  return z.array(toolCall).optional();
48
49
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theoremjs/web",
3
- "version": "0.3.5-next.1004.gd674e6b",
3
+ "version": "0.3.5-next.1005.geaafb0b",
4
4
  "description": "Theorem on the web platform, with no UI framework: Web-standard server handlers that serve a profile, and the browser client that talks to them.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -25,6 +25,6 @@
25
25
  },
26
26
  "peerDependencies": {
27
27
  "zod": "^4.6.5",
28
- "@theoremjs/agents": "^0.3.5-next.1004.gd674e6b"
28
+ "@theoremjs/agents": "^0.3.5-next.1005.geaafb0b"
29
29
  }
30
30
  }
@@ -7,7 +7,7 @@
7
7
  */
8
8
  import { type GateReference, type NormalizedTurnRequest, type Profile, type ProfileDefinition, type ProviderHostOptions, TheoremError, type TurnHistoryMessage, type TurnInput, type TurnRequest } from '@theoremjs/agents';
9
9
  import { type ConversationInbox, type InboxItem, type InboxPolicy, type ReplyRun } from '@theoremjs/agents/conversation';
10
- import type { ClientTurnOptions } from '@theoremjs/agents/host';
10
+ import { type ClientTurnOptions } from '@theoremjs/agents/host';
11
11
  import { type TranscriptBlock } from '@theoremjs/agents/interface';
12
12
  import type { ConversationView, StatedTurn, TheoremInvokeRequest, TheoremRewound, TheoremSteerRequest, TheoremStopRequest, TheoremTurnInput } from '../client/transport.ts';
13
13
  import { type ReplyLine, type ReplyToSave, type ShapedReply } from './conversation.ts';
@@ -24,6 +24,14 @@ export type ChatContext = {
24
24
  /** Undefined when the profile keeps no conversation (`'stateless'`). */
25
25
  conversations?: TheoremConversationStore;
26
26
  };
27
+ /**
28
+ * Where the chat saves a detached call's end: its conversation store, as `clientEvents` reads it.
29
+ * None with `authorizeToolReplay`: every request reads a saved end, and that host checks each read.
30
+ */
31
+ export declare function endingsOf(chat: ChatContext | undefined, options: {
32
+ clientEvents?: ClientTurnOptions;
33
+ authorizeToolReplay?: unknown;
34
+ }): Pick<CallsContext, 'endings'>;
27
35
  /**
28
36
  * The chat `definition` serves, with the store that keeps its conversation. `name` is the function
29
37
  * the app called, for the error a wrong profile throws.
@@ -7,15 +7,27 @@
7
7
  */
8
8
  import { compactHistory, defaultKernelScope, defineProfile, labelText, runTurn, TheoremError, } from '@theoremjs/agents';
9
9
  import { runConversation, } from '@theoremjs/agents/conversation';
10
- import { applyToolEvent, interfaceFromProfile, refuseInterfacePick, } from '@theoremjs/agents/interface';
10
+ import { forClient } from '@theoremjs/agents/host';
11
+ import { interfaceFromProfile, refuseInterfacePick, } from '@theoremjs/agents/interface';
11
12
  import { answerReply, conversationView, messageReply, openConversation, postedMessage, readerConversationHost, rewindConversation, statelessRefusal, waitingCalls, wakeReply, } from "./conversation.js";
12
- import { detachedEnd, sessionConversationInbox } from "./conversation-inbox.js";
13
- import { unknownConversation, } from "./conversation-store.js";
13
+ import { detachedAt, detachedEnd, readerEnding, sessionConversationInbox, } from "./conversation-inbox.js";
14
+ import { endedBlock, unknownConversation, } from "./conversation-store.js";
14
15
  import { sessionPageDispatch } from "./page-dispatch.js";
15
- import { announced, backgroundWiring, pausedWaits, recorded, replayAllowed, sessionCredentials, settlingOf, takeLapsed, takeWalkedAway, withAuthorizationUrls, } from "./session-calls.js";
16
+ import { announced, backgroundWiring, pausedWaits, recorded, replayAllowed, saveEnded, sessionCredentials, settlingOf, takeLapsed, takeWalkedAway, withAuthorizationUrls, } from "./session-calls.js";
16
17
  import { steerStage, steerUnitOf, stopOnRequest } from "./steer-inbox.js";
17
18
  import { sessionToolCoordinator } from "./tool-operations.js";
18
19
  import { isRefusal, preparedTurn, stagesInOrder } from "./turn-wiring.js";
20
+ /**
21
+ * Where the chat saves a detached call's end: its conversation store, as `clientEvents` reads it.
22
+ * None with `authorizeToolReplay`: every request reads a saved end, and that host checks each read.
23
+ */
24
+ export function endingsOf(chat, options) {
25
+ const store = chat?.conversations;
26
+ if (!store || options.authorizeToolReplay)
27
+ return {};
28
+ const { clientEvents } = options;
29
+ return { endings: { store, forReader: (event) => forClient(event, clientEvents) } };
30
+ }
19
31
  /**
20
32
  * The chat `definition` serves, with the store that keeps its conversation. `name` is the function
21
33
  * the app called, for the error a wrong profile throws.
@@ -444,6 +456,7 @@ function replySaving(ctx, at, held) {
444
456
  }),
445
457
  }
446
458
  : {}),
459
+ written: (appended) => saveEnded(ctx, at, appended),
447
460
  after: async (saved) => {
448
461
  held?.told(saved.told);
449
462
  await afterSave?.(at, saved);
@@ -521,13 +534,13 @@ async function* wakeReplyLines(ctx, at, host, ref, generation, held, input) {
521
534
  async function currentView(ctx, at, host, ref, opened) {
522
535
  const { conversation, running } = opened;
523
536
  const view = { ...conversationView(host, conversation), ...(running ? { running } : {}) };
524
- const detached = view.transcript.some(isDetachedBlock);
525
- // why: a session's late results come from detached calls only; an app's items come from anywhere
526
- if (!detached && !ctx.options.inbox)
537
+ // why: a session's late results come from detached calls only, ended or not; an app's items come from anywhere
538
+ if (!view.transcript.some(wasDetached) && !ctx.options.inbox)
527
539
  return view;
528
540
  const wake = (await wakeDue(ctx, at, host, ref, conversation)) ? { wake: true } : {};
529
- if (!detached)
530
- return { ...view, ...notifyOffer(ctx), ...wake };
541
+ if (!view.transcript.some(isDetachedBlock)) {
542
+ return { ...view, ...(ctx.options.inbox ? notifyOffer(ctx) : {}), ...wake };
543
+ }
531
544
  const { operations } = await ctx.sessions.read(at.sessionId);
532
545
  const transcript = await Promise.all(view.transcript.map((block) => isDetachedBlock(block) ? lateBlock(ctx, at, block, operations, host) : block));
533
546
  // why: an app's inbox saves replies the page did not ask for, so its page always listens
@@ -558,7 +571,14 @@ function holds(ctx) {
558
571
  function isDetachedBlock(block) {
559
572
  return block.kind === 'tool' && block.tool.state?.phase === 'background';
560
573
  }
561
- /** A detached call's block as its operation stands. One the session no longer holds has no known end. */
574
+ /** A detached call's block, whether its end is saved on it or not. */
575
+ function wasDetached(block) {
576
+ return block.kind === 'tool' && detachedAt(block.tool) !== undefined;
577
+ }
578
+ /**
579
+ * A detached call's block as its operation stands, for a block whose end no save put on it. One
580
+ * the session no longer holds has no known end.
581
+ */
562
582
  async function lateBlock(ctx, at, block, operations, host) {
563
583
  const { tool } = block;
564
584
  const id = tool.operationId;
@@ -582,21 +602,10 @@ async function lateBlock(ctx, at, block, operations, host) {
582
602
  },
583
603
  };
584
604
  }
585
- if (operation?.status === 'settled') {
586
- const settled = host.forReader(operation.outcome.event);
587
- if (settled.type !== 'tool')
588
- return block;
589
- const { tool: state } = settled;
590
- if (!('phase' in state) || (state.phase !== 'complete' && state.phase !== 'error'))
591
- return block;
592
- return { ...block, tool: { ...applyToolEvent(tool, state), endedAt: operation.settledAt } };
593
- }
594
605
  const { name, callId } = tool;
595
- const unresolved = detachedEnd({ operationId: id ?? '', callId, name, at: tool.state?.at ?? Date.now() }, operation, labels);
596
- if (!unresolved)
597
- return block;
598
- const { operationId: _id, ...state } = unresolved.event.tool;
599
- return { ...block, tool: applyToolEvent(tool, state) };
606
+ const outcome = detachedEnd({ operationId: id ?? '', callId, name, at: tool.state?.at ?? Date.now() }, operation, labels);
607
+ const ending = outcome && readerEnding(outcome, host.forReader);
608
+ return ending && id ? endedBlock(block, { operationId: id, tool: ending }) : block;
600
609
  }
601
610
  /** The answer's reply, handed first what the paused reply read, so it tells them as it goes on. */
602
611
  async function* answered(held, paused, reply) {
@@ -5,9 +5,10 @@
5
5
  *
6
6
  * @module
7
7
  */
8
- import { type LateResultItem, type Profile, type ToolOperationOutcome } from '@theoremjs/agents';
8
+ import { type LateResultItem, type Profile, type ToolOperationOutcome, type TurnEvent } from '@theoremjs/agents';
9
9
  import type { ConversationInbox } from '@theoremjs/agents/conversation';
10
- import type { StoredConversation } from './conversation-store.ts';
10
+ import type { TranscriptBlock } from '@theoremjs/agents/interface';
11
+ import type { DetachedEnding, StoredConversation } from './conversation-store.ts';
11
12
  import type { MutableStore } from './session-authority.ts';
12
13
  import type { SessionToolOperation, TheoremSessionState } from './session-store.ts';
13
14
  /** A background call that ended, as the session keeps it. */
@@ -27,6 +28,16 @@ export type DetachedCall = {
27
28
  * dropped). Undefined while it runs.
28
29
  */
29
30
  export declare function detachedEnd(call: DetachedCall, operation: SessionToolOperation | undefined, labels: Profile['labels']): ToolOperationOutcome | undefined;
31
+ /**
32
+ * When a call detached, epoch ms: kept after its end is saved on its block, so the end is told
33
+ * apart. A block saved before `detached` was kept has only its background phase. Undefined for a
34
+ * call that never detached.
35
+ */
36
+ export declare function detachedAt(tool: Extract<TranscriptBlock, {
37
+ kind: 'tool';
38
+ }>['tool']): number | undefined;
39
+ /** A detached call's end as `forReader` lets its reader read it: the event its block takes. */
40
+ export declare function readerEnding(outcome: ToolOperationOutcome, forReader: (event: TurnEvent) => TurnEvent): DetachedEnding['tool'] | undefined;
30
41
  /** Options for {@link sessionConversationInbox}. */
31
42
  export type SessionConversationInboxOptions = {
32
43
  sessions: MutableStore<TheoremSessionState>;
@@ -33,6 +33,22 @@ export function detachedEnd(call, operation, labels) {
33
33
  replay: { failure },
34
34
  };
35
35
  }
36
+ /**
37
+ * When a call detached, epoch ms: kept after its end is saved on its block, so the end is told
38
+ * apart. A block saved before `detached` was kept has only its background phase. Undefined for a
39
+ * call that never detached.
40
+ */
41
+ export function detachedAt(tool) {
42
+ return tool.detached?.at ?? (tool.state?.phase === 'background' ? tool.state.at : undefined);
43
+ }
44
+ /** A detached call's end as `forReader` lets its reader read it: the event its block takes. */
45
+ export function readerEnding(outcome, forReader) {
46
+ const event = forReader(outcome.event);
47
+ if (event.type !== 'tool')
48
+ return undefined;
49
+ const { tool } = event;
50
+ return tool.phase === 'complete' || tool.phase === 'error' ? tool : undefined;
51
+ }
36
52
  /** The operation ids a chat's saved replies told, those its paused reply holds, and its untold calls. */
37
53
  function transcriptState(conversation) {
38
54
  const told = new Set();
@@ -42,9 +58,10 @@ function transcriptState(conversation) {
42
58
  for (const id of block.operationIds)
43
59
  told.add(id);
44
60
  const { tool } = block.kind === 'tool' ? block : { tool: undefined };
45
- if (tool?.state?.phase === 'background' && tool.operationId) {
61
+ const at = tool && detachedAt(tool);
62
+ if (tool?.operationId && at !== undefined) {
46
63
  const { operationId, callId, name } = tool;
47
- detached.push({ operationId, callId, name, at: tool.state.at });
64
+ detached.push({ operationId, callId, name, at });
48
65
  }
49
66
  }
50
67
  const paused = new Set();
@@ -10,7 +10,7 @@
10
10
  * @module
11
11
  */
12
12
  import { type ProviderCheckpoint, TheoremError, type TurnEvent, type TurnHistoryMessage, z } from '@theoremjs/agents';
13
- import type { TranscriptBlock } from '@theoremjs/agents/interface';
13
+ import { type TranscriptBlock } from '@theoremjs/agents/interface';
14
14
  import { type RunningReply, type StatedTurn } from '../client/transport.ts';
15
15
  import { type MemorySessionStoreOptions } from './session-store.ts';
16
16
  /** A reply's base and the count of its events that base holds, as they stood before a compaction. */
@@ -97,6 +97,20 @@ export type WriteContext = {
97
97
  /** The blocks this write adds to the transcript the store holds, so a store need not compare. */
98
98
  appended: readonly TranscriptBlock[];
99
99
  };
100
+ /** A call a reply left running in the background, as it ended: the event its block takes. */
101
+ export type DetachedEnding = {
102
+ operationId: string;
103
+ tool: Extract<Extract<TurnEvent, {
104
+ type: 'tool';
105
+ }>['tool'], {
106
+ phase: 'complete' | 'error';
107
+ }>;
108
+ };
109
+ /**
110
+ * `block` with `ending` on it, when it is the block of that call as it detached; any other block
111
+ * as it is. A store's `end` writes each block through it.
112
+ */
113
+ export declare function endedBlock(block: TranscriptBlock, ending: DetachedEnding): TranscriptBlock;
100
114
  export type ConversationWriteResult = {
101
115
  written: true;
102
116
  ref: string;
@@ -118,6 +132,15 @@ export interface TheoremConversationStore {
118
132
  * stored revision is still `expectedRevision`.
119
133
  */
120
134
  write(sessionId: string, ref: string | null, expectedRevision: string | null, next: StoredConversation, context?: WriteContext): Promise<ConversationWriteResult>;
135
+ /**
136
+ * A call a reply left running in the background ended. The store puts the end on the call's
137
+ * block in whichever of the session's conversations holds it (`endedBlock`), and keeps it there
138
+ * when a later write still holds the block as it detached. It changes no revision, so a reply
139
+ * that runs meanwhile still saves. With no such block (it was rewound away) it changes nothing.
140
+ * A store that keeps nothing (`createSealedConversationStore`) does nothing: the page reads the
141
+ * end from the session's record while the session keeps it (`operationRetentionMs`).
142
+ */
143
+ end(sessionId: string, ending: DetachedEnding): Promise<void>;
121
144
  }
122
145
  /** Refuses a ref the store does not know or cannot open: the browser reads `session.conversation_unknown`. */
123
146
  export declare function unknownConversation(cause?: unknown): TheoremError;
@@ -10,6 +10,7 @@
10
10
  * @module
11
11
  */
12
12
  import { labelText, providerCheckpointSchema, TheoremError, turnEventSchema, turnHistoryMessageSchema, z, } from '@theoremjs/agents';
13
+ import { applyToolEvent } from '@theoremjs/agents/interface';
13
14
  import { openSecret, sealSecret } from '@theoremjs/agents/kernel';
14
15
  import { transcriptBlockSchema } from "../client/transcript-schema.js";
15
16
  import { statedTurnSchema } from "../client/transport.js";
@@ -49,6 +50,21 @@ export const storedConversationSchema = storedConversation;
49
50
  export function emptyConversation() {
50
51
  return { version: 2, id: crypto.randomUUID(), transcript: [], history: [] };
51
52
  }
53
+ /**
54
+ * `block` with `ending` on it, when it is the block of that call as it detached; any other block
55
+ * as it is. A store's `end` writes each block through it.
56
+ */
57
+ export function endedBlock(block, ending) {
58
+ if (block.kind !== 'tool' || block.tool.operationId !== ending.operationId)
59
+ return block;
60
+ const { tool } = block;
61
+ if (tool.state?.phase !== 'background')
62
+ return block;
63
+ // why: A block saved before `detached` was kept takes it from its background phase, so the call
64
+ // stays one that detached once it has ended.
65
+ const detached = tool.detached ? tool : applyToolEvent(tool, tool.state);
66
+ return { ...block, tool: applyToolEvent(detached, ending.tool) };
67
+ }
52
68
  /** Refuses a ref the store does not know or cannot open: the browser reads `session.conversation_unknown`. */
53
69
  export function unknownConversation(cause) {
54
70
  return new TheoremError('not_found', labelText('session.conversation_unknown'), {
@@ -80,7 +96,7 @@ export function createMemoryConversationStore(options = {}) {
80
96
  return { written: false };
81
97
  if ((snapshot?.revision ?? null) !== expectedRevision)
82
98
  return { written: false };
83
- const conversation = storedConversation.parse(next);
99
+ const conversation = keptEnds(storedConversation.parse(next), snapshot?.conversation);
84
100
  const key = ref ?? crypto.randomUUID();
85
101
  const revision = crypto.randomUUID();
86
102
  conversations.delete(key);
@@ -101,8 +117,37 @@ export function createMemoryConversationStore(options = {}) {
101
117
  read: (sessionId, ref) => Promise.resolve(structuredClone(current(sessionId, ref))),
102
118
  // why: A write that fails its check rejects, as any store's does, rather than throwing at the call.
103
119
  write: (...args) => new Promise((resolve) => resolve(written(...args))),
120
+ end: (sessionId, ending) => new Promise((resolve) => {
121
+ for (const entry of conversations.values()) {
122
+ if (entry.sessionId !== sessionId)
123
+ continue;
124
+ const { conversation } = entry.snapshot;
125
+ const transcript = conversation.transcript.map((block) => endedBlock(block, ending));
126
+ entry.snapshot = { ...entry.snapshot, conversation: { ...conversation, transcript } };
127
+ }
128
+ resolve();
129
+ }),
104
130
  };
105
131
  }
132
+ /** `next`, with each detached call's end that `stored` holds kept on the block `next` still holds as it detached. */
133
+ function keptEnds(next, stored) {
134
+ const ends = new Map();
135
+ for (const block of stored?.transcript ?? []) {
136
+ if (block.kind === 'tool' && block.tool.operationId && block.tool.detached) {
137
+ if (block.tool.state?.phase !== 'background')
138
+ ends.set(block.tool.operationId, block);
139
+ }
140
+ }
141
+ if (ends.size === 0)
142
+ return next;
143
+ const transcript = next.transcript.map((block) => {
144
+ if (block.kind !== 'tool' || block.tool.state?.phase !== 'background')
145
+ return block;
146
+ const ended = block.tool.operationId ? ends.get(block.tool.operationId) : undefined;
147
+ return ended ?? block;
148
+ });
149
+ return { ...next, transcript };
150
+ }
106
151
  /**
107
152
  * A store for a host that keeps nothing. The ref is the conversation sealed
108
153
  * with the host's key and bound to the session: the browser carries it and
@@ -128,6 +173,8 @@ export function createSealedConversationStore(options) {
128
173
  const conversation = storedConversation.parse(JSON.parse(plaintext));
129
174
  return { revision: ref, conversation };
130
175
  },
176
+ // why: The browser carries the conversation, so the server holds nothing to put an end on.
177
+ end: () => Promise.resolve(),
131
178
  async write(sessionId, ref, expectedRevision, next, context) {
132
179
  // invariant: This store keeps no holds, so a reply whose hold lost the conversation writes nothing here.
133
180
  if (context?.ended === 'lost')
@@ -190,6 +190,11 @@ export type ReplySaving = {
190
190
  ended: ReplyEnd;
191
191
  told: readonly string[];
192
192
  }) => Promise<void>;
193
+ /**
194
+ * Runs once any write of the reply lands, with the blocks it added: saves the end of each call
195
+ * among them that went on in the background and has ended already. What it throws is reported.
196
+ */
197
+ written?: (appended: readonly TranscriptBlock[]) => Promise<void>;
193
198
  /** The app's compaction, in place of the runner's. What it throws is reported. */
194
199
  compact?: (signal: {
195
200
  history: TurnHistoryMessage[];
@@ -213,11 +213,17 @@ async function saveReply(host, opened, runner, saving) {
213
213
  cause: CONFLICT,
214
214
  });
215
215
  }
216
+ // invariant: The save is written; a step after it cannot fail the reply.
217
+ try {
218
+ await runner.saving?.written?.(reply.context.appended);
219
+ }
220
+ catch (err) {
221
+ runner.saving?.report(err);
222
+ }
216
223
  try {
217
224
  await runner.saving?.after?.({ ended: saving.ended, told: reply.context.told });
218
225
  }
219
226
  catch (err) {
220
- // invariant: The save is written; a step after it cannot fail the reply.
221
227
  runner.saving?.report(err);
222
228
  }
223
229
  return { ref: result.ref, revision: result.revision, conversation: reply.next };
@@ -232,7 +238,9 @@ async function saveLost(host, opened, runner, saving) {
232
238
  return;
233
239
  try {
234
240
  const reply = await shaped(opened, runner, { ...saving, ended: 'lost' });
235
- await host.store.write(host.sessionId, opened.ref, opened.revision, reply.next, reply.context);
241
+ const result = await host.store.write(host.sessionId, opened.ref, opened.revision, reply.next, reply.context);
242
+ if (result.written)
243
+ await runner.saving.written?.(reply.context.appended);
236
244
  }
237
245
  catch (err) {
238
246
  runner.saving.report(err);
@@ -6,7 +6,7 @@
6
6
  * @module
7
7
  */
8
8
  import { TheoremError } from '@theoremjs/agents';
9
- import { chatOf, createConversationCore, } from "./conversation-core.js";
9
+ import { chatOf, createConversationCore, endingsOf, } from "./conversation-core.js";
10
10
  import { sessionParts } from "./session-calls.js";
11
11
  import { createMemorySteerInbox } from "./steer-inbox.js";
12
12
  /** Creates the conversation core for `options.profile`. */
@@ -20,6 +20,7 @@ export function createTheoremConversationCore(options) {
20
20
  }
21
21
  return createConversationCore({
22
22
  ...sessionParts(name, chat.profile, options),
23
+ ...endingsOf(chat, options),
23
24
  chat,
24
25
  steer: options.steerInbox ?? createMemorySteerInbox(),
25
26
  options: {
@@ -116,8 +116,12 @@ export type TheoremHandlerOptions<Item extends InboxItem = InboxItem> = ReplyWir
116
116
  * and the next message cancels the call. Unset, a gate waits until it is answered.
117
117
  */
118
118
  gateTtlMs?: number;
119
- /** Retain settled tool results in milliseconds. Default: 24 hours. */
120
- operationRetentionMs?: number;
119
+ /**
120
+ * How long the session keeps a finished tool call's result, in milliseconds from when it
121
+ * finished. While kept, the same call asked for again gets the kept result and does not run
122
+ * again, and a background call's end can still reach its saved reply. Your app decides it.
123
+ */
124
+ operationRetentionMs: number;
121
125
  /** Maximum UTF-8 request body bytes before JSON parsing. Unset, a body of any size is read. */
122
126
  maxRequestBytes?: number;
123
127
  pageToolBroker?: PageToolBroker;
package/server/handler.js CHANGED
@@ -45,7 +45,7 @@ import { blockWithoutToolData, clientProfileInterface, eventWithoutToolData, pro
45
45
  import { hostInterface, theoremHostCallRequestSchema } from "../client/host-transport.js";
46
46
  import { theoremConversationRequestSchema, theoremInvokeRequestSchema, theoremNotifyRequestSchema, theoremRewindRequestSchema, theoremSteerRequestSchema, theoremStopRequestSchema, theoremTurnRequestSchema, theoremWakeRequestSchema, } from "../client/transport.js";
47
47
  import { statelessRefusal } from "./conversation.js";
48
- import { chatOf, createConversationCore, followedUp, oneInbox, replyUnreachable, unconversedAnswer, } from "./conversation-core.js";
48
+ import { chatOf, createConversationCore, endingsOf, followedUp, oneInbox, replyUnreachable, unconversedAnswer, } from "./conversation-core.js";
49
49
  import { callEvents, sessionParts } from "./session-calls.js";
50
50
  import { theoremSession } from "./session-identity.js";
51
51
  import { kernelTurnInput } from "./turn-input.js";
@@ -209,6 +209,7 @@ function callsOf(ctx, request) {
209
209
  sessions: ctx.sessions,
210
210
  credentials: ctx.credentials,
211
211
  pageToolBroker: ctx.pageToolBroker,
212
+ ...endingsOf(ctx.chat, options),
212
213
  options: {
213
214
  prepare: options.prepare,
214
215
  onStage: options.onStage,
package/server/mod.d.ts CHANGED
@@ -12,7 +12,7 @@ export { type StatedTurn, theoremConversationRequestSchema, theoremInvokeRequest
12
12
  export { answerReply, type ConversationHost, type ConversationUse, conversationView, type IssuedWalkAway, messageReply, type OpenedConversation, openConversation, type PostedMessage, postedMessage, type ReplyLine, type ReplyRunner, type ReplySaving, type ReplyToSave, type ReplyTurn, readerConversationHost, rewindConversation, type ShapedReply, startConversation, statelessRefusal, type WalkedAwayCall, waitingCalls, wakeReply, } from './conversation.ts';
13
13
  export type { AppInbox, ContinueChoice, ConversationCore, FollowUpArgs, Generation, HoldStop, MessageArgs, Reply, ReplyPrepare, ReplyWiring, RunEnd, SaveHooks, WakeArgs, } from './conversation-core.ts';
14
14
  export { followedUp } from './conversation-core.ts';
15
- export { type ConversationSnapshot, type ConversationWriteResult, createMemoryConversationStore, createSealedConversationStore, emptyConversation, type PausedReply, type ReplyEnd, type SealedConversationStoreOptions, type StoredConversation, storedConversationSchema, type TheoremConversationStore, type UncompactedBase, unknownConversation, type WriteContext, } from './conversation-store.ts';
15
+ export { type ConversationSnapshot, type ConversationWriteResult, createMemoryConversationStore, createSealedConversationStore, type DetachedEnding, emptyConversation, endedBlock, type PausedReply, type ReplyEnd, type SealedConversationStoreOptions, type StoredConversation, storedConversationSchema, type TheoremConversationStore, type UncompactedBase, unknownConversation, type WriteContext, } from './conversation-store.ts';
16
16
  export { createTheoremConversationCore, type TheoremConversationCoreOptions, } from './create-conversation-core.ts';
17
17
  export { createMemoryCredentialStore, type TheoremCredentialStore, type TheoremCredentials, } from './credential-store.ts';
18
18
  export { createTheoremDecisionHandler, type DecisionQuestionsBuilder, isQuestionsBuilder, type TheoremDecisionHandlerOptions, } from './decision-handler.ts';
@@ -26,7 +26,7 @@ export { sessionStateStore } from './session-authority.ts';
26
26
  export { createTheoremSessionBoundary, type PreparedLiveOpen, type SessionBoundaryOptions, type TheoremSessionBoundary, } from './session-boundary.ts';
27
27
  export type { CoreContext } from './session-calls.ts';
28
28
  export type { TheoremSessionCapacity } from './session-limits.ts';
29
- export { createMemorySessionStore, DEFAULT_OPERATION_RETENTION_MS, type MemorySessionStoreOptions, type PendingToolGate, type SessionSnapshot, type SessionToolOperation, type SessionWriteResult, type TheoremSessionState, type TheoremSessionStore, theoremSessionStateSchema, } from './session-store.ts';
29
+ export { createMemorySessionStore, type MemorySessionStoreOptions, type PendingToolGate, type SessionSnapshot, type SessionToolOperation, type SessionWriteResult, type TheoremSessionState, type TheoremSessionStore, theoremSessionStateSchema, } from './session-store.ts';
30
30
  export { createMemorySteerInbox, type SteerInbox, type SteerUnit, steerStage, steerUnitOf, stopOnRequest, } from './steer-inbox.ts';
31
31
  export { tellEveryResult } from './tell-every-result.ts';
32
32
  export { sessionToolCoordinator } from './tool-operations.ts';
package/server/mod.js CHANGED
@@ -10,7 +10,7 @@ export { transcriptBlockSchema } from "../client/transcript-schema.js";
10
10
  export { theoremConversationRequestSchema, theoremInvokeRequestSchema, theoremNotifyRequestSchema, theoremReplaySchema, theoremRewindRequestSchema, theoremStartRequestSchema, theoremSteerRequestSchema, theoremStopRequestSchema, theoremTurnRequestSchema, theoremWakeRequestSchema, } from "../client/transport.js";
11
11
  export { answerReply, conversationView, messageReply, openConversation, postedMessage, readerConversationHost, rewindConversation, startConversation, statelessRefusal, waitingCalls, wakeReply, } from "./conversation.js";
12
12
  export { followedUp } from "./conversation-core.js";
13
- export { createMemoryConversationStore, createSealedConversationStore, emptyConversation, storedConversationSchema, unknownConversation, } from "./conversation-store.js";
13
+ export { createMemoryConversationStore, createSealedConversationStore, emptyConversation, endedBlock, storedConversationSchema, unknownConversation, } from "./conversation-store.js";
14
14
  export { createTheoremConversationCore, } from "./create-conversation-core.js";
15
15
  export { createMemoryCredentialStore, } from "./credential-store.js";
16
16
  export { createTheoremDecisionHandler, isQuestionsBuilder, } from "./decision-handler.js";
@@ -22,7 +22,7 @@ export { createMemoryPageToolBroker, pageToolResultSchema, sessionPageDispatch,
22
22
  export { checkRequest, parseLiveClientMessage, parseLiveOpenMessage } from "./request-check.js";
23
23
  export { sessionStateStore } from "./session-authority.js";
24
24
  export { createTheoremSessionBoundary, } from "./session-boundary.js";
25
- export { createMemorySessionStore, DEFAULT_OPERATION_RETENTION_MS, theoremSessionStateSchema, } from "./session-store.js";
25
+ export { createMemorySessionStore, theoremSessionStateSchema, } from "./session-store.js";
26
26
  export { createMemorySteerInbox, steerStage, steerUnitOf, stopOnRequest, } from "./steer-inbox.js";
27
27
  export { tellEveryResult } from "./tell-every-result.js";
28
28
  export { sessionToolCoordinator } from "./tool-operations.js";
@@ -8,7 +8,8 @@ export interface SessionBoundaryOptions {
8
8
  session?: (request: Request) => string | undefined | Promise<string | undefined>;
9
9
  sessionStore: TheoremSessionStore;
10
10
  gateTtlMs?: number;
11
- operationRetentionMs?: number;
11
+ /** As `TheoremHandlerOptions.operationRetentionMs`. */
12
+ operationRetentionMs: number;
12
13
  /** As `TheoremHandlerOptions.pageStatesTurn`: refuses a live call's `stated` unless set. */
13
14
  pageStatesTurn?: boolean;
14
15
  pageToolBroker?: PageToolBroker;
@@ -6,7 +6,7 @@ import { createMemoryPageToolBroker, sessionPageDispatch, } from "./page-dispatc
6
6
  import { checkRequest } from "./request-check.js";
7
7
  import { sessionStateStore } from "./session-authority.js";
8
8
  import { theoremSession } from "./session-identity.js";
9
- import { DEFAULT_OPERATION_RETENTION_MS, detachedReply, } from "./session-store.js";
9
+ import { detachedReply } from "./session-store.js";
10
10
  import { sessionToolCoordinator } from "./tool-operations.js";
11
11
  import { liveSessionOpen } from "./turn-input.js";
12
12
  export async function createTheoremSessionBoundary(options) {
@@ -16,7 +16,7 @@ export async function createTheoremSessionBoundary(options) {
16
16
  throw new TheoremError('auth', labelText('session.sign_in'), {
17
17
  copy: { key: 'session.sign_in' },
18
18
  });
19
- const retention = options.operationRetentionMs ?? DEFAULT_OPERATION_RETENTION_MS;
19
+ const retention = options.operationRetentionMs;
20
20
  if (!Number.isSafeInteger(retention) || retention <= 0)
21
21
  throw new TheoremError('config', labelText('error.config'));
22
22
  const store = sessionStateStore(options.sessionStore, resolveGateTtlMs('session boundary', options.gateTtlMs), retention);
@@ -6,12 +6,13 @@
6
6
  * @module
7
7
  */
8
8
  import { type GateReference, type Profile, type StageHandler, type ToolGate, type TurnEvent, type TurnInput, type TurnWiring } from '@theoremjs/agents';
9
+ import { type TranscriptBlock } from '@theoremjs/agents/interface';
9
10
  import { type ToolBackgroundService, type ToolCredentialSource } from '@theoremjs/agents/kernel';
10
11
  import type { TheoremHostCallRequest } from '../client/host-transport.ts';
11
12
  import type { TheoremInvokeRequest } from '../client/transport.ts';
12
13
  import { type IssuedWalkAway } from './conversation.ts';
13
14
  import { type SettledOperation } from './conversation-inbox.ts';
14
- import type { StoredConversation } from './conversation-store.ts';
15
+ import type { StoredConversation, TheoremConversationStore } from './conversation-store.ts';
15
16
  import { type TheoremCredentialStore, type TheoremCredentials } from './credential-store.ts';
16
17
  import type { TheoremNotifier } from './notifier.ts';
17
18
  import { type PageToolBroker } from './page-dispatch.ts';
@@ -29,11 +30,18 @@ export type CoreContext = {
29
30
  signal: AbortSignal;
30
31
  };
31
32
  /** What a session's tool calls read from whoever serves them. */
33
+ /** Where a detached call's end is saved: the chat's conversation store, as its pages read it. */
34
+ export type DetachedEndings = {
35
+ store: TheoremConversationStore;
36
+ forReader: (event: TurnEvent) => TurnEvent;
37
+ };
32
38
  export type CallsContext = {
33
39
  profile: Profile;
34
40
  sessions: SessionStateStore;
35
41
  credentials: MutableStore<TheoremCredentials>;
36
42
  pageToolBroker: PageToolBroker;
43
+ /** Unset when the profile keeps no conversation. */
44
+ endings?: DetachedEndings;
37
45
  options: {
38
46
  prepare?: AppPrepare;
39
47
  onStage?: StageHandler;
@@ -62,7 +70,7 @@ export type SessionOptions = {
62
70
  sessionStore?: TheoremSessionStore;
63
71
  credentialStore?: TheoremCredentialStore;
64
72
  gateTtlMs?: number;
65
- operationRetentionMs?: number;
73
+ operationRetentionMs: number;
66
74
  pageToolBroker?: PageToolBroker;
67
75
  pageToolTimeoutMs?: number;
68
76
  notifyRetryMs?: number;
@@ -108,8 +116,13 @@ export declare function backgroundWiring(ctx: CallsContext, at: CoreContext): {
108
116
  background?: ToolBackgroundService;
109
117
  };
110
118
  /**
111
- * `service`, telling the session's open pages when each of its calls ends, and the decider's
112
- * `ended`, with the wake and the notify it may use.
119
+ * Saves the end of each call in `blocks` that detached and has ended already: a call that ended
120
+ * before its reply was written had no block to take its end.
121
+ */
122
+ export declare function saveEnded(ctx: CallsContext, at: CoreContext, blocks: readonly TranscriptBlock[]): Promise<void>;
123
+ /**
124
+ * `service`, saving each of its calls' end on the call's block when it ends, then telling the
125
+ * session's open pages, then the decider's `ended`, with the wake and the notify it may use.
113
126
  */
114
127
  export declare function announced(ctx: CallsContext, at: CoreContext, service: ToolBackgroundService): ToolBackgroundService;
115
128
  /** Whether this request may read a settled call's result: the host's `authorizeToolReplay`. */
@@ -10,11 +10,11 @@ import { withPublicLabels } from '@theoremjs/agents/guardrails';
10
10
  import { gatedToolsFromEvents, promotedToolIdsFromEvents, toolSnapshotFromEvents, } from '@theoremjs/agents/interface';
11
11
  import { answerGatedCall, isSealedSource, resolveGateTtlMs, } from '@theoremjs/agents/kernel';
12
12
  import { requiredOperationId, waitingCalls } from "./conversation.js";
13
- import { detachedEnd } from "./conversation-inbox.js";
13
+ import { detachedEnd, readerEnding, } from "./conversation-inbox.js";
14
14
  import { createMemoryCredentialStore, } from "./credential-store.js";
15
15
  import { checkPageToolTimeout, createMemoryPageToolBroker, sessionPageDispatch, } from "./page-dispatch.js";
16
16
  import { lockedStore, sessionStateStore, } from "./session-authority.js";
17
- import { createMemorySessionStore, DEFAULT_OPERATION_RETENTION_MS, } from "./session-store.js";
17
+ import { createMemorySessionStore, } from "./session-store.js";
18
18
  import { sameAcceptedAnswer, sessionToolCoordinator } from "./tool-operations.js";
19
19
  import { isRefusal, preparedTurn } from "./turn-wiring.js";
20
20
  /**
@@ -23,7 +23,7 @@ import { isRefusal, preparedTurn } from "./turn-wiring.js";
23
23
  */
24
24
  export function sessionParts(name, profile, options) {
25
25
  const gateTtlMs = resolveGateTtlMs(name, options.gateTtlMs);
26
- const operationRetentionMs = options.operationRetentionMs ?? DEFAULT_OPERATION_RETENTION_MS;
26
+ const { operationRetentionMs } = options;
27
27
  if (!Number.isSafeInteger(operationRetentionMs) || operationRetentionMs <= 0) {
28
28
  throw new TheoremError('config', labelText('error.config'), {
29
29
  cause: { code: 'operation_retention' },
@@ -360,13 +360,56 @@ export function backgroundWiring(ctx, at) {
360
360
  return service ? { background: announced(ctx, at, service) } : {};
361
361
  }
362
362
  /**
363
- * `service`, telling the session's open pages when each of its calls ends, and the decider's
364
- * `ended`, with the wake and the notify it may use.
363
+ * What became of the detached call, once it has ended; undefined while it runs, and when the
364
+ * session holds no record of it, since an end it never saw is not one to save.
365
+ */
366
+ function endedOutcome(ctx, call, operations) {
367
+ const { operationId } = call;
368
+ if (!Object.hasOwn(operations, operationId))
369
+ return undefined;
370
+ return detachedEnd(call, operations[operationId], ctx.profile.labels);
371
+ }
372
+ /** Saves a detached call's end on its block. What the store throws is reported: the page then reads the end from the session. */
373
+ async function saveEnding(ctx, at, operationId, outcome) {
374
+ const { endings } = ctx;
375
+ const tool = endings && readerEnding(outcome, endings.forReader);
376
+ if (!endings || !tool)
377
+ return;
378
+ try {
379
+ await endings.store.end(at.sessionId, { operationId, tool });
380
+ }
381
+ catch (err) {
382
+ ctx.options.onError?.(err, at);
383
+ }
384
+ }
385
+ /**
386
+ * Saves the end of each call in `blocks` that detached and has ended already: a call that ended
387
+ * before its reply was written had no block to take its end.
388
+ */
389
+ export async function saveEnded(ctx, at, blocks) {
390
+ const calls = blocks.flatMap((block) => {
391
+ if (block.kind !== 'tool' || block.tool.state?.phase !== 'background')
392
+ return [];
393
+ const { operationId, callId, name, state } = block.tool;
394
+ return operationId ? [{ operationId, callId, name, at: state.at }] : [];
395
+ });
396
+ if (!ctx.endings || calls.length === 0)
397
+ return;
398
+ const { operations } = await ctx.sessions.read(at.sessionId);
399
+ for (const call of calls) {
400
+ const outcome = endedOutcome(ctx, call, operations);
401
+ if (outcome)
402
+ await saveEnding(ctx, at, call.operationId, outcome);
403
+ }
404
+ }
405
+ /**
406
+ * `service`, saving each of its calls' end on the call's block when it ends, then telling the
407
+ * session's open pages, then the decider's `ended`, with the wake and the notify it may use.
365
408
  */
366
409
  export function announced(ctx, at, service) {
367
410
  const { notifier, lateResultsDecider } = ctx.options;
368
411
  const ended = lateResultsDecider?.ended?.bind(lateResultsDecider);
369
- if (!notifier && !ended)
412
+ if (!notifier && !ended && !ctx.endings)
370
413
  return service;
371
414
  const notify = async () => {
372
415
  await notifier?.publish(at.sessionId);
@@ -376,16 +419,14 @@ export function announced(ctx, at, service) {
376
419
  service.detached(call);
377
420
  void call.done
378
421
  .then(async () => {
379
- await notify();
380
- if (!ended)
381
- return;
382
- const { operations } = await ctx.sessions.read(at.sessionId);
383
422
  const { operationId, callId, toolId } = call;
384
- const operation = Object.hasOwn(operations, operationId)
385
- ? operations[operationId]
423
+ const outcome = ctx.endings || ended
424
+ ? endedOutcome(ctx, { operationId, callId, name: toolId, at: Date.now() }, (await ctx.sessions.read(at.sessionId)).operations)
386
425
  : undefined;
387
- const outcome = detachedEnd({ operationId, callId, name: toolId, at: Date.now() }, operation, ctx.profile.labels);
388
- if (!outcome)
426
+ if (outcome)
427
+ await saveEnding(ctx, at, operationId, outcome);
428
+ await notify();
429
+ if (!ended || !outcome)
389
430
  return;
390
431
  await ended({
391
432
  host: await at.host,
@@ -72,7 +72,6 @@ export type SessionToolOperation = {
72
72
  });
73
73
  /** The reply the model read for a call that detached, whatever has happened to the call since. */
74
74
  export declare function detachedReply(operation: SessionToolOperation): ToolOperationReply | undefined;
75
- export declare const DEFAULT_OPERATION_RETENTION_MS: number;
76
75
  /** What the replies of one conversation did with one late result, until a saved reply tells it. */
77
76
  export type SessionInboxEntry = {
78
77
  /** The reply it is handed to now, while that reply's hold has the conversation. */
@@ -19,7 +19,6 @@ export function detachedReply(operation) {
19
19
  ? operation.reply
20
20
  : undefined;
21
21
  }
22
- export const DEFAULT_OPERATION_RETENTION_MS = 24 * 60 * 60 * 1000;
23
22
  const blobSchema = z.strictObject({
24
23
  data: z.string(),
25
24
  mimeType: z.string(),
@@ -278,8 +277,10 @@ export function createMemorySessionStore(options = {}) {
278
277
  const sessions = new Map();
279
278
  const held = (entry) => Object.values(entry.snapshot.state.gates).some((gate) => gate.expiresAt === undefined || Date.now() < gate.expiresAt) ||
280
279
  Object.values(entry.snapshot.state.operations).some((operation) => operation.status !== 'settled' ||
281
- Date.now() <
282
- (operation.retainUntil ?? operation.settledAt + DEFAULT_OPERATION_RETENTION_MS));
280
+ // why: the session's every write stamps `retainUntil` from the host's operationRetentionMs;
281
+ // a record written without it is kept, and the session drops it as it loads
282
+ operation.retainUntil === undefined ||
283
+ Date.now() < operation.retainUntil);
283
284
  const current = (sessionId) => {
284
285
  const entry = sessions.get(sessionId);
285
286
  if (entry && !held(entry) && Date.now() - entry.touched >= ttlMs) {