@niwa-labs/messages 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts ADDED
@@ -0,0 +1,237 @@
1
+ /**
2
+ * The messages module: a message is an envelope sent to an address.
3
+ *
4
+ * The module owns two facts: a message was sent, and a message was received. Both records
5
+ * carry the whole envelope, so the envelope is the message and the record says that it
6
+ * happened.
7
+ *
8
+ * The action "message.send" takes the envelope without its id and writes the record
9
+ * "message.sent". The action "message.receive" does the same for a message that came in from
10
+ * outside, and writes "message.received". The two differ only in the direction; the sender is
11
+ * the same in both.
12
+ *
13
+ * **Who sent it.** A message always carries who sent it. When the caller is known, the caller
14
+ * is the sender: the binding says what address that caller speaks as, and a payload that
15
+ * claims to come from somebody else does not change it. When the caller is not known, the
16
+ * sender must be given, and a message without a sender is refused.
17
+ *
18
+ * **Ids.** A message id is `msg-<hex>`, issued here when the message is written; the sender never
19
+ * chooses it. "message.list" shows the messages and "message.get" gives one by its id or any text
20
+ * that names it.
21
+ *
22
+ * One agent writes to another by address.
23
+ */
24
+
25
+ import type { z } from "zod";
26
+
27
+ import { NotSent, UnknownId, action, actionName } from "@niwa-labs/core";
28
+ import type { Action, ActionContext, ActionName, Address, Caller, IdIndex } from "@niwa-labs/core";
29
+ import { fileURLToPath } from "node:url";
30
+ import { COCKPIT_MODULE, bindingOf, plugin } from "@niwa-labs/plugin";
31
+ import type { CallerBinding, MessagesOptions, Plugin } from "@niwa-labs/plugin";
32
+ import { sessionSend } from "@niwa-labs/sessions/records";
33
+
34
+ import { messageGetRef, messageListRef, messageReceiveRef, messageSendRef } from "./actions.ts";
35
+ import { Message, MessageInput } from "./envelope.ts";
36
+ import { MessageDelivered, MessageReceived, MessageReceivedForSession, MessageSent, MessageToSession, birthOf, describeMessage, messageIds, messagesOf } from "./records.ts";
37
+ import { render } from "./render.ts";
38
+
39
+ export {
40
+ Assignment,
41
+ Answer,
42
+ Failure,
43
+ Message,
44
+ MessageBody,
45
+ MessageId,
46
+ MessageInput,
47
+ Question,
48
+ Result,
49
+ ReplyRoute,
50
+ ResultSchema,
51
+ Update,
52
+ } from "./envelope.ts";
53
+ export type { MessageBodyType } from "./envelope.ts";
54
+ export {
55
+ MessageDelivered,
56
+ MessageReceived,
57
+ MessageReceivedForSession,
58
+ MessageSent,
59
+ MessageToSession,
60
+ birthOf,
61
+ describeMessage,
62
+ issuedIds,
63
+ messageIds,
64
+ messagesOf,
65
+ } from "./records.ts";
66
+ export { contentText, render } from "./render.ts";
67
+ export { MessageKind, messageGetRef, messageListRef, messageReceiveRef, messageSendRef } from "./actions.ts";
68
+
69
+ /** The name of the action that sends a message. */
70
+ export const MESSAGE_SEND: ActionName = actionName("message.send");
71
+
72
+ /** The name of the action that receives a message from outside. */
73
+ export const MESSAGE_RECEIVE: ActionName = actionName("message.receive");
74
+
75
+ /**
76
+ * The sender of a message.
77
+ *
78
+ * A bound caller is the address it is bound to: a payload that claims another sender does not
79
+ * change that, and the returned envelope shows the address really used.
80
+ * A client the binding does not know is refused: it must not pick its own address. The host and
81
+ * handlers are in-process and must say who sends.
82
+ */
83
+ function senderOf(caller: Caller, given: Address | undefined, bind: CallerBinding): Address {
84
+ if (caller.kind === "client" && caller.principal?.kind === "run") return { kind: "client", id: `run:${caller.principal.id}` };
85
+ const bound = bind(caller);
86
+ if (bound !== undefined) return bound;
87
+ if (caller.kind === "client") {
88
+ throw new NotSent("the client is not bound to an address, so it cannot send a message");
89
+ }
90
+ if (given === undefined) {
91
+ throw new NotSent("the sender of the message is not known: the caller is not bound to an address");
92
+ }
93
+ return given;
94
+ }
95
+
96
+ /**
97
+ * The envelope of a message, from the input of the action and the sender that was resolved.
98
+ *
99
+ * The id is issued here and nowhere else, so a caller cannot say which id its message has. It is
100
+ * seeded by the record the call writes, and the operation of a step is stable across repeats: a
101
+ * call that was cut off and made again gets the same id and writes the same record once, not two
102
+ * messages.
103
+ */
104
+ function envelopeOf(input: MessageInput, from: Address, ctx: ActionContext, ids: IdIndex<"message">): Message {
105
+ if (input.replyTo !== undefined && (from.kind !== "owner" || input.to.kind !== "agent")) {
106
+ throw new NotSent("Only an owner message to an agent may carry a reply route");
107
+ }
108
+ return {
109
+ id: ids.issue(birthOf(ctx)),
110
+ from,
111
+ to: input.to,
112
+ ...(input.task === undefined ? {} : { task: input.task }),
113
+ ...(input.replyTo === undefined ? {} : { replyTo: input.replyTo }),
114
+ body: input.body,
115
+ };
116
+ }
117
+
118
+ /**
119
+ * The action that sends a message: the system sends it out.
120
+ *
121
+ * The input is the envelope without its id. The sender is the caller when the caller is
122
+ * known, and the payload's own sender when it is not.
123
+ */
124
+ export function messageSend(
125
+ opts?: MessagesOptions,
126
+ ids: IdIndex<"message"> = messageIds(() => undefined),
127
+ ): Action<MessageInput, Message, z.input<typeof MessageInput>> {
128
+ const bind = bindingOf(opts);
129
+ return action(messageSendRef, {
130
+ // The write is idempotent by the id of the message, so the call may be made again.
131
+ recovery: "repeat",
132
+ effect: "record",
133
+ world: "niwa",
134
+ async run(input, ctx): Promise<Message> {
135
+ const from = senderOf(ctx.caller, input.from, bind);
136
+ const envelope = envelopeOf(input, from, ctx, ids);
137
+ await ctx.emit(MessageSent, envelope);
138
+ return envelope;
139
+ },
140
+ });
141
+ }
142
+
143
+ /**
144
+ * The action that receives a message: a message came in from outside.
145
+ *
146
+ * The input is the envelope without its id, exactly as for sending. The sender is the caller
147
+ * when the caller is known — the outsider who sent it — and the payload's own sender when it
148
+ * is not.
149
+ */
150
+ export function messageReceive(
151
+ opts?: MessagesOptions,
152
+ ids: IdIndex<"message"> = messageIds(() => undefined),
153
+ ): Action<MessageInput, Message, z.input<typeof MessageInput>> {
154
+ const bind = bindingOf(opts);
155
+ return action(messageReceiveRef, {
156
+ recovery: "repeat",
157
+ effect: "record",
158
+ world: "niwa",
159
+ async run(input, ctx): Promise<Message> {
160
+ const from = senderOf(ctx.caller, input.from, bind);
161
+ const envelope = envelopeOf(input, from, ctx, ids);
162
+ await ctx.emit(MessageReceived, envelope);
163
+ return envelope;
164
+ },
165
+ });
166
+ }
167
+
168
+ /**
169
+ * The plugin of the messages module.
170
+ *
171
+ * It declares the three records of the module and registers the two actions. The binding says
172
+ * what address a caller speaks as; the same binding belongs to the actions a handler uses
173
+ * (`messageSend({ bind })`), so that a message sent from a handler carries the same sender as
174
+ * a message sent from outside.
175
+ *
176
+ * A message to a session is delivered as text: the envelope is unfolded into what an agent
177
+ * reads, and the sessions module is told to send it. A message to any other address is left where
178
+ * it is: the addressee of its kind reads it in its own way.
179
+ */
180
+ export function messages(opts?: MessagesOptions): Plugin {
181
+ return plugin("messages", (api) => {
182
+ api.offer(COCKPIT_MODULE, { id: "messages", entry: fileURLToPath(new URL("./cockpit/index.tsx", import.meta.url)) });
183
+ const ids = messageIds(() => api.journal?.());
184
+ api.declare(MessageSent, MessageReceived, MessageDelivered);
185
+ api.action(messageSend(opts, ids));
186
+ api.action(messageReceive(opts, ids));
187
+ api.action(
188
+ action(messageListRef, {
189
+ recovery: "repeat",
190
+ effect: "read",
191
+ world: "niwa",
192
+ run: async (input) => ({
193
+ items: messagesOf(api.journal?.())
194
+ .filter((message) => input.task === undefined || message.task === input.task)
195
+ .map((message) => ({
196
+ id: message.id,
197
+ description: describeMessage(message),
198
+ from: message.from,
199
+ to: message.to,
200
+ kind: message.body.type,
201
+ ...(message.task === undefined ? {} : { task: message.task }),
202
+ })),
203
+ }),
204
+ }),
205
+ );
206
+ api.action(
207
+ action(messageGetRef, {
208
+ recovery: "repeat",
209
+ effect: "read",
210
+ world: "niwa",
211
+ run: async (input) => {
212
+ const id = ids.require(input.id);
213
+ const found = messagesOf(api.journal?.()).find((message) => message.id === id);
214
+ if (found === undefined) throw new UnknownId(input.id, "message");
215
+ return found;
216
+ },
217
+ }),
218
+ );
219
+
220
+ // A message to a session goes into that session, once, as the text of the envelope, whether it was
221
+ // sent from inside or came in from outside. A session slow to take a message holds no message to
222
+ // another session.
223
+ for (const source of [MessageToSession, MessageReceivedForSession]) {
224
+ api.on(source, { concurrency: Number.POSITIVE_INFINITY }, async (message, step) => {
225
+ if (message.to.kind !== "session") return;
226
+ // The operation is the message: a delivery that was cut off is answered from what the sessions
227
+ // module recorded of it, and is never made twice.
228
+ const sent = await step(sessionSend, {
229
+ session: { harness: message.to.harness, native: message.to.id },
230
+ message: render(message),
231
+ operation: message.id,
232
+ });
233
+ await step.emit(MessageDelivered, { message, receipt: sent.receipt });
234
+ });
235
+ }
236
+ });
237
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * The records entry of the messages module: what another plugin may import from it. The envelope
3
+ * and its schemas, the records, the typed references of the actions and the pure helpers that read
4
+ * messages from the journal or turn them into text; no factory and nothing that runs. The actions
5
+ * import the records, so this file sits above both and neither imports it.
6
+ */
7
+
8
+ export {
9
+ Answer,
10
+ Assignment,
11
+ Failure,
12
+ Message,
13
+ MessageBody,
14
+ MessageId,
15
+ MessageInput,
16
+ Question,
17
+ Result,
18
+ ReplyRoute,
19
+ ResultSchema,
20
+ Update,
21
+ } from "./envelope.ts";
22
+ export type { MessageBodyType } from "./envelope.ts";
23
+ export {
24
+ MessageDelivered,
25
+ MessageReceived,
26
+ MessageReceivedForSession,
27
+ MessageSent,
28
+ MessageToSession,
29
+ birthOf,
30
+ describeMessage,
31
+ issuedIds,
32
+ messageIds,
33
+ messagesOf,
34
+ } from "./records.ts";
35
+ export { MessageKind, messageGetRef, messageListRef, messageReceiveRef, messageSendRef } from "./actions.ts";
36
+ export { contentText, render } from "./render.ts";
package/src/records.ts ADDED
@@ -0,0 +1,141 @@
1
+ /**
2
+ * The records of the messages module: a message sent, and a message received, and the helpers that
3
+ * read them: the ids of messages and the messages the journal holds.
4
+ *
5
+ * Both records carry the whole envelope. The envelope is the message; the record says that it
6
+ * happened, and who did it. The journal keeps the truth, so nothing about a message lives
7
+ * anywhere else.
8
+ */
9
+
10
+ import { z } from "zod";
11
+
12
+ import { EntityDescription, IdIndex, record, recordId, seq } from "@niwa-labs/core";
13
+ import type { ActionContext, IssuedId, JournalReader, RecordId, RecordType } from "@niwa-labs/core";
14
+ import { trigger } from "@niwa-labs/plugin";
15
+ import type { Trigger } from "@niwa-labs/plugin";
16
+ import { DeliveryReceiptSchema } from "@niwa-labs/sessions/records";
17
+
18
+ import { Message } from "./envelope.ts";
19
+ import type { Message as MessageType } from "./envelope.ts";
20
+ import { resultValue } from "./text.ts";
21
+
22
+ /**
23
+ * A message was sent.
24
+ *
25
+ * The envelope is inside the record as it was sent, so the record of a sent message is the
26
+ * message itself.
27
+ */
28
+ export const MessageSent = record("message.sent", Message, { providerOnly: "messages" });
29
+
30
+ /**
31
+ * A message was received.
32
+ *
33
+ * The same envelope, on the other side of the delivery.
34
+ */
35
+ export const MessageReceived = record("message.received", Message, { providerOnly: "messages" });
36
+
37
+ /**
38
+ * A message was delivered to a session.
39
+ *
40
+ * The receipt says what became of it: delivered into the running turn, queued after the current
41
+ * turn, or started a new turn. The message is inside the record, so the receipt belongs to the
42
+ * message it is about.
43
+ */
44
+ export const MessageDelivered = record(
45
+ "message.delivered",
46
+ z.object({
47
+ /** The message that was delivered. */
48
+ message: Message,
49
+ /** What became of it. */
50
+ receipt: DeliveryReceiptSchema,
51
+ }),
52
+ );
53
+
54
+ /**
55
+ * A trigger over the messages that are sent to a session.
56
+ *
57
+ * It is the type "message.sent" narrowed to the messages a session is to receive: a handler of
58
+ * it is woken by exactly those messages and by no others, so a message to another address
59
+ * costs nothing.
60
+ */
61
+ export const MessageToSession: Trigger<MessageType> = trigger(MessageSent, {
62
+ name: "message.sent:session",
63
+ filter: { "to.kind": "session" },
64
+ });
65
+
66
+ /**
67
+ * A trigger over the messages that came in for a session.
68
+ *
69
+ * The same narrowing of "message.received": a message from outside is delivered to a session as
70
+ * a message from inside is.
71
+ */
72
+ export const MessageReceivedForSession: Trigger<MessageType> = trigger(MessageReceived, {
73
+ name: "message.received:session",
74
+ filter: { "to.kind": "session" },
75
+ });
76
+
77
+ /*
78
+ * The helpers below are pure over the records above: the ids of messages, and of the modules that
79
+ * issue their ids the same way. An entity is born in the record its creating call writes first.
80
+ */
81
+
82
+ /** The record an action writes first: the one its entity is born in, and the seed of the entity's id. */
83
+ export function birthOf(ctx: ActionContext): RecordId {
84
+ return recordId(`${ctx.operationId}/emit/1`);
85
+ }
86
+
87
+ /**
88
+ * The ids the journal holds, each with the seed it was issued from.
89
+ *
90
+ * Every record of the types that parses carries one id (`idOf`), and its own record id is the seed.
91
+ */
92
+ export function issuedIds<T>(
93
+ journal: JournalReader | undefined,
94
+ types: readonly RecordType<T>[],
95
+ idOf: (data: T) => string,
96
+ ): IssuedId[] {
97
+ if (journal === undefined) return [];
98
+ const byName = new Map(types.map((type) => [type.name, type]));
99
+ const issued: IssuedId[] = [];
100
+ for (const stored of journal.since(seq(0), [...byName.keys()])) {
101
+ const parsed = byName.get(stored.type)?.schema.safeParse(stored.data);
102
+ if (parsed?.success === true) issued.push({ id: idOf(parsed.data), seed: stored.id });
103
+ }
104
+ return issued;
105
+ }
106
+
107
+ /** The ids of messages: a message is born when it is sent or received. */
108
+ export function messageIds(journal: () => JournalReader | undefined): IdIndex<"message"> {
109
+ return new IdIndex("message", () => issuedIds(journal(), [MessageSent, MessageReceived], (message) => message.id));
110
+ }
111
+
112
+ /** The messages the journal holds, sent and received, in the order they were written. */
113
+ export function messagesOf(journal: JournalReader | undefined): Message[] {
114
+ if (journal === undefined) return [];
115
+ const found: Message[] = [];
116
+ for (const stored of journal.since(seq(0), [MessageSent.name, MessageReceived.name])) {
117
+ const parsed = Message.safeParse(stored.data);
118
+ if (parsed.success) found.push(parsed.data);
119
+ }
120
+ return found;
121
+ }
122
+
123
+ /**
124
+ * A few words about a message, for a list: what kind it is and how its text begins.
125
+ *
126
+ * A message has no author-given description, so it is read off the body: the kind, then the first
127
+ * line of the text, cut to fit.
128
+ */
129
+ export function describeMessage(message: Message): EntityDescription {
130
+ const { body } = message;
131
+ const result = body.type === "result" ? resultValue(body.text) : undefined;
132
+ const preview = result === undefined
133
+ ? body.text
134
+ : Array.isArray(result) ? "" : ["summary", "outcome", "description", "text"].map((key) => result[key]).find(
135
+ (value): value is string => typeof value === "string" && value.trim() !== "" && resultValue(value) === undefined,
136
+ ) ?? "";
137
+ const first = preview.split(/[\r\n]/, 1)[0]?.trim() ?? "";
138
+ const line = `${message.body.type}: ${first}`.trim();
139
+ const cut = line.length <= 60 ? line : `${line.slice(0, 59).trimEnd()}…`;
140
+ return EntityDescription.parse(cut);
141
+ }
package/src/render.ts ADDED
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Unfolding an envelope into text.
3
+ *
4
+ * An agent is a language model, so what it receives is text: niwa unfolds the envelope into
5
+ * text on its edge. The text says who sent it, who it is for, what kind of message it is and
6
+ * what it carries: everything a reader needs to act on it, and nothing that the envelope does
7
+ * not say.
8
+ */
9
+
10
+ import { addressText } from "@niwa-labs/core";
11
+
12
+ import type { Message, MessageBody } from "./envelope.ts";
13
+
14
+ /**
15
+ * The text of one message, for an agent.
16
+ *
17
+ * The lines are in a fixed order: who sent it, who it is for, what kind of message it is, and
18
+ * what it carries. A reader that knows the shape of the text can tell the parts apart.
19
+ */
20
+ export function render(message: Message): string {
21
+ const lines: string[] = [
22
+ `From: ${addressText(message.from)}`,
23
+ `To: ${addressText(message.to)}`,
24
+ `Kind: ${message.body.type}`,
25
+ ];
26
+ lines.push(contentText(message));
27
+ return lines.join("\n");
28
+ }
29
+
30
+ /**
31
+ * The text of what a message carries, without who it is from and to: the task it belongs to, then
32
+ * the body with whatever else the body holds.
33
+ *
34
+ * A reader that is told the sender and the receiver some other way (a turn in an inbox says who it
35
+ * is from) reads this and no more. A message with no task and nothing but a text is that text.
36
+ */
37
+ export function contentText(message: Message): string {
38
+ const lines: string[] = [];
39
+ if (message.task !== undefined) lines.push(`Task: ${message.task}`);
40
+ lines.push(bodyText(message.body));
41
+ return lines.join("\n");
42
+ }
43
+
44
+ /**
45
+ * The text of one body: what it carries, plus whatever else it holds.
46
+ *
47
+ * The extra fields are only shown when they are there: an agent reads what was sent, not a
48
+ * field that was left empty.
49
+ */
50
+ function bodyText(body: MessageBody): string {
51
+ const lines = [body.text];
52
+ const question = "question" in body ? body.question : undefined;
53
+ if (question !== undefined) lines.push(`Question: ${question}`);
54
+ const reason = "reason" in body ? body.reason : undefined;
55
+ if (reason !== undefined) lines.push(`Reason: ${reason}`);
56
+ const kind = "kind" in body ? body.kind : undefined;
57
+ if (kind !== undefined) lines.push(`Kind of work: ${kind}`);
58
+ const result = "result" in body ? body.result : undefined;
59
+ if (result !== undefined) lines.push(`The result must fit this JSON Schema: ${JSON.stringify(result)}`);
60
+ const data = body.data;
61
+ if (data !== undefined) lines.push(`Data: ${JSON.stringify(data)}`);
62
+ return lines.join("\n");
63
+ }
package/src/text.ts ADDED
@@ -0,0 +1,10 @@
1
+ /** Task notifications can carry structured results as serialized text. */
2
+ export function resultValue(text: string): Record<string, unknown> | unknown[] | undefined {
3
+ const start = text.trimStart()[0];
4
+ if (start !== "{" && start !== "[") return undefined;
5
+ try {
6
+ return JSON.parse(text) as Record<string, unknown> | unknown[];
7
+ } catch {
8
+ return undefined;
9
+ }
10
+ }
@@ -0,0 +1,22 @@
1
+ import { expect, test } from "bun:test";
2
+
3
+ import { Message } from "../src/envelope.ts";
4
+ import { describeMessage } from "../src/records.ts";
5
+ import { resultValue } from "../src/text.ts";
6
+
7
+ test("a result preview uses the outcome instead of truncated JSON", () => {
8
+ const text = '{"checks":48,"outcome":"Проверено без ошибок"}';
9
+ const result = Message.parse({
10
+ id: "msg-123456",
11
+ from: { kind: "agent", id: "fixture" },
12
+ to: { kind: "owner" },
13
+ body: { type: "result", text },
14
+ });
15
+ expect(describeMessage(result)).toBe("result: Проверено без ошибок");
16
+ expect(resultValue(text)).toEqual({ checks: 48, outcome: "Проверено без ошибок" });
17
+ expect(describeMessage({ ...result, body: { type: "result", text: '{"checks":48}' } })).toBe("result:");
18
+ expect(resultValue('[{"checks":48}]')).toEqual([{ checks: 48 }]);
19
+ const plain = "{notes} Keep the original prose.";
20
+ expect(resultValue(plain)).toBeUndefined();
21
+ expect(describeMessage({ ...result, body: { type: "result", text: plain } })).toBe("result: " + plain);
22
+ });