@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.
@@ -0,0 +1,175 @@
1
+ /**
2
+ * Theorem's own conversation inbox, for the replies that hold no app `inbox`. A message the person
3
+ * sends while a reply runs is an item in it, beside the session's ended background calls. The
4
+ * reply takes one message at each `pre_turn`, `post_tool` and `before_end`, and a save of the
5
+ * reply that landed it tells it once. A stop reaches the reply that holds the conversation.
6
+ *
7
+ * The inbox is named by the chat's conversation. A chat that keeps no conversation (`'stateless'`)
8
+ * is named by its run: the `turnId` the page sent. Both live in process memory, so a steer and the
9
+ * reply it joins must reach the same process.
10
+ *
11
+ * @module
12
+ */
13
+ import { isTurnInjectStage, TheoremError, } from '@theoremjs/agents';
14
+ import { createMemoryInbox, } from '@theoremjs/agents/conversation';
15
+ import { appendUserDraftToHistory } from '@theoremjs/agents/interface';
16
+ /** Whether `item` is a person's message. */
17
+ function isPersonMessage(item) {
18
+ return item.kind === 'person_message';
19
+ }
20
+ /**
21
+ * A steer as a client posts it (a checked `TheoremSteerRequest`) as an inbox item: its id is the
22
+ * client's, and a reply names it in `stage.injected` once it lands. A message with no text and no
23
+ * file is refused.
24
+ */
25
+ export function personMessageOf(steer) {
26
+ const { text, attachments, voice } = steer.input;
27
+ const messages = appendUserDraftToHistory([], { ...(text === undefined ? {} : { text }) }, { ...(attachments ? { attachments } : {}), ...(voice ? { voice } : {}) });
28
+ // labels-exempt: internal diagnostic; the user reads the error kind's (or copy key's) wording
29
+ if (!messages.length)
30
+ throw new TheoremError('request', 'a steer needs text or a file');
31
+ return { id: steer.id, kind: 'person_message', handovers: [], messages };
32
+ }
33
+ /** Creates the memory stop. A stop asked reaches every model run of the conversation under way. */
34
+ function createMemoryHoldStop() {
35
+ const holds = new Map();
36
+ const holdOf = (conversation, hold) => {
37
+ const byHold = holds.get(conversation) ?? new Map();
38
+ holds.set(conversation, byHold);
39
+ const running = byHold.get(hold) ?? { stopped: false, settle: new Set() };
40
+ byHold.set(hold, running);
41
+ return running;
42
+ };
43
+ const drop = (conversation, hold) => {
44
+ const byHold = holds.get(conversation);
45
+ byHold?.delete(hold);
46
+ if (byHold?.size === 0)
47
+ holds.delete(conversation);
48
+ };
49
+ return {
50
+ running: (conversation) => (holds.get(conversation)?.size ?? 0) > 0,
51
+ ask(conversation) {
52
+ const byHold = holds.get(conversation);
53
+ if (!byHold?.size)
54
+ return Promise.resolve(false);
55
+ for (const running of byHold.values()) {
56
+ running.stopped = true;
57
+ for (const settle of running.settle)
58
+ settle(true);
59
+ running.settle.clear();
60
+ }
61
+ return Promise.resolve(true);
62
+ },
63
+ stopped(conversation, hold, over) {
64
+ const running = holdOf(conversation, hold);
65
+ if (running.stopped)
66
+ return Promise.resolve(true);
67
+ return new Promise((resolve) => {
68
+ running.settle.add(resolve);
69
+ over.addEventListener('abort', () => {
70
+ running.settle.delete(resolve);
71
+ resolve(false);
72
+ }, { once: true });
73
+ });
74
+ },
75
+ clear(conversation, hold) {
76
+ const running = holds.get(conversation)?.get(hold);
77
+ for (const settle of running?.settle ?? [])
78
+ settle(false);
79
+ drop(conversation, hold);
80
+ return Promise.resolve();
81
+ },
82
+ };
83
+ }
84
+ /** Creates the memory one handler's replies share. */
85
+ export function createOwnInbox() {
86
+ return { shelf: new Map(), runs: new Map(), turns: new Map(), stop: createMemoryHoldStop() };
87
+ }
88
+ /** A stop whose names are scoped, so no scope reaches another's reply. */
89
+ export function scopedStop(stop, scope) {
90
+ return {
91
+ ask: (name) => stop.ask(ownKey(scope, name)),
92
+ stopped: (name, hold, over) => stop.stopped(ownKey(scope, name), hold, over),
93
+ clear: (name, hold) => stop.clear(ownKey(scope, name), hold),
94
+ };
95
+ }
96
+ /**
97
+ * Opens the inbox of the run `name` in `scope`. A person's message reaches it with `steerRun`,
98
+ * and a reply under a hold of it (`namedRun`) takes it. `close` ends it; a message still waiting is lost.
99
+ */
100
+ export function openRun(own, scope, name, leaseMs) {
101
+ const key = ownKey(scope, name);
102
+ const memory = createMemoryInbox({ leaseMs });
103
+ own.runs.set(key, memory);
104
+ return { memory, close: () => own.runs.delete(key) };
105
+ }
106
+ /** Puts a person's message into the run `name` in `scope`. False when no such run is open. */
107
+ export function steerRun(own, scope, name, message) {
108
+ const memory = own.runs.get(ownKey(scope, name));
109
+ if (!memory)
110
+ return false;
111
+ memory.arrive(name, message);
112
+ return true;
113
+ }
114
+ /** The inbox's name for a conversation or a run in one session: no session reaches another's. */
115
+ export function ownKey(sessionId, name) {
116
+ return `${sessionId}\u0000${name}`;
117
+ }
118
+ /**
119
+ * The rule for what a reply takes: the first waiting message, one at each moment, and the
120
+ * decider's choice among the late results.
121
+ */
122
+ export function ownPolicy(options) {
123
+ const { decider } = options;
124
+ return async (items, moment) => {
125
+ const message = items.find(isPersonMessage);
126
+ const late = items.filter((item) => item.kind === 'late_result');
127
+ const choice = decider
128
+ ? await decider.policy(late, { ...moment, host: await options.host() })
129
+ : { tell: [] };
130
+ return {
131
+ tell: [...(message ? [message.id] : []), ...choice.tell],
132
+ ...(choice.giveUp ? { giveUp: choice.giveUp } : {}),
133
+ };
134
+ };
135
+ }
136
+ /**
137
+ * One take of the hold at each moment, shared by the two readers: the kernel asks for late results,
138
+ * and the stage handler for a message. Each reader reads a moment once.
139
+ */
140
+ export function ownReads(run) {
141
+ const moments = new Map();
142
+ let opening = true;
143
+ const handed = new Set();
144
+ const items = (who, at) => {
145
+ const key = `${at.stage}:${at.step}`;
146
+ let moment = moments.get(key);
147
+ if (!moment || moment.read.has(who)) {
148
+ const first = opening && at.stage === 'pre_turn';
149
+ opening &&= !first;
150
+ moment = {
151
+ items: first ? Promise.resolve(run.opened) : run.take(at),
152
+ read: new Set(),
153
+ };
154
+ moments.set(key, moment);
155
+ }
156
+ moment.read.add(who);
157
+ return moment.items;
158
+ };
159
+ return {
160
+ late: async ({ stage, step }) => (await items('late', { stage, step }))
161
+ .filter((item) => item.kind === 'late_result')
162
+ .map((item) => item.outcome),
163
+ stage: async ({ stage, step }) => {
164
+ if (!isTurnInjectStage(stage))
165
+ return undefined;
166
+ const taken = await items('stage', { stage, step });
167
+ const message = taken.find(isPersonMessage);
168
+ if (!message)
169
+ return undefined;
170
+ handed.add(message.id);
171
+ return { inject: message.messages, injectId: message.id };
172
+ },
173
+ mine: (ids) => ids.filter((id) => handed.has(id)),
174
+ };
175
+ }
@@ -1,41 +0,0 @@
1
- /**
2
- * Mid-turn steer inbox — the client posts user messages while a turn streams;
3
- * the turn's stage handler drains one unit per inject-capable stage. The
4
- * client's stop reaches the turn through it too.
5
- *
6
- * @module
7
- */
8
- import { type StageHandler, type TurnHistoryMessage } from '@theoremjs/agents';
9
- import type { TheoremSteerRequest } from '../client/transport.ts';
10
- /** One steer: the client's id for it, reported back in `stage.injected` once it lands. */
11
- export type SteerUnit = {
12
- id: string;
13
- messages: TurnHistoryMessage[];
14
- };
15
- /**
16
- * A steer as a client posts it (a checked `TheoremSteerRequest`): its message as the one user
17
- * message the model reads. A steer with no text and no file is refused.
18
- */
19
- export declare function steerUnitOf(steer: Pick<TheoremSteerRequest, 'id' | 'input'>): SteerUnit;
20
- /** Lands the inbox's next steer, one per steerable stage, named by its id. */
21
- export declare function steerStage(inbox: SteerInbox, key: string): StageHandler;
22
- /**
23
- * Keyed by client turn id. The default lives in process memory, which is only
24
- * correct when steer and stop POSTs reach the same process as the turn — swap
25
- * in a shared store (KV, Redis, Durable Object) for multi-instance hosts.
26
- */
27
- export interface SteerInbox {
28
- open(turnId: string): void | Promise<void>;
29
- /** Returns `false` when no turn with this id is open. */
30
- enqueue(turnId: string, unit: SteerUnit): boolean | Promise<boolean>;
31
- /** Next unit, FIFO, or `undefined`. */
32
- consume(turnId: string): SteerUnit | undefined | Promise<SteerUnit | undefined>;
33
- /** Stops the turn. Returns `false` when no turn with this id is open. */
34
- stop(turnId: string): boolean | Promise<boolean>;
35
- /** Settles `true` once the turn is stopped (at once if it already is), `false` once it closes. */
36
- stopped(turnId: string): Promise<boolean>;
37
- close(turnId: string): void | Promise<void>;
38
- }
39
- export declare function createMemorySteerInbox(): SteerInbox;
40
- /** Aborts `stop` once the inbox's turn is stopped. */
41
- export declare function stopOnRequest(inbox: SteerInbox, turnId: string, stop: AbortController): void;
@@ -1,84 +0,0 @@
1
- /**
2
- * Mid-turn steer inbox — the client posts user messages while a turn streams;
3
- * the turn's stage handler drains one unit per inject-capable stage. The
4
- * client's stop reaches the turn through it too.
5
- *
6
- * @module
7
- */
8
- import { TheoremError } from '@theoremjs/agents';
9
- import { appendUserDraftToHistory } from '@theoremjs/agents/interface';
10
- /** The stages a steer can land at. */
11
- const STEER_STAGES = new Set(['pre_turn', 'post_tool', 'before_end']);
12
- /**
13
- * A steer as a client posts it (a checked `TheoremSteerRequest`): its message as the one user
14
- * message the model reads. A steer with no text and no file is refused.
15
- */
16
- export function steerUnitOf(steer) {
17
- const { text, attachments, voice } = steer.input;
18
- const messages = appendUserDraftToHistory([], { ...(text === undefined ? {} : { text }) }, { ...(attachments ? { attachments } : {}), ...(voice ? { voice } : {}) });
19
- // labels-exempt: internal diagnostic; the user reads the error kind's (or copy key's) wording
20
- if (!messages.length)
21
- throw new TheoremError('request', 'a steer needs text or a file');
22
- return { id: steer.id, messages };
23
- }
24
- /** Lands the inbox's next steer, one per steerable stage, named by its id. */
25
- export function steerStage(inbox, key) {
26
- return async ({ stage }) => {
27
- if (!STEER_STAGES.has(stage))
28
- return;
29
- const unit = await inbox.consume(key);
30
- return unit ? { inject: unit.messages, injectId: unit.id } : undefined;
31
- };
32
- }
33
- export function createMemorySteerInbox() {
34
- const turns = new Map();
35
- return {
36
- open(turnId) {
37
- if (!turns.has(turnId))
38
- turns.set(turnId, { queue: [], stopped: false, settle: new Set() });
39
- },
40
- enqueue(turnId, unit) {
41
- const turn = turns.get(turnId);
42
- if (!turn)
43
- return false;
44
- turn.queue.push(structuredClone(unit));
45
- return true;
46
- },
47
- consume(turnId) {
48
- return turns.get(turnId)?.queue.shift();
49
- },
50
- stop(turnId) {
51
- const turn = turns.get(turnId);
52
- if (!turn)
53
- return false;
54
- turn.stopped = true;
55
- for (const settle of turn.settle)
56
- settle(true);
57
- turn.settle.clear();
58
- return true;
59
- },
60
- stopped(turnId) {
61
- const turn = turns.get(turnId);
62
- if (!turn)
63
- return Promise.resolve(false);
64
- if (turn.stopped)
65
- return Promise.resolve(true);
66
- return new Promise((resolve) => turn.settle.add(resolve));
67
- },
68
- close(turnId) {
69
- const turn = turns.get(turnId);
70
- for (const settle of turn?.settle ?? [])
71
- settle(false);
72
- turns.delete(turnId);
73
- },
74
- };
75
- }
76
- /** Aborts `stop` once the inbox's turn is stopped. */
77
- export function stopOnRequest(inbox, turnId, stop) {
78
- inbox.stopped(turnId).then((stopped) => {
79
- if (stopped)
80
- stop.abort();
81
- },
82
- // why: An inbox that can't say leaves the turn to run; the browser's fallback drops the stream.
83
- () => { });
84
- }