@unieai/rabi-message-feedback 0.0.0-stage → 0.2.2-rc.5

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 DeepSeek
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,8 @@
1
- # Temporary Holding Version
1
+ # @unieai/rabi-message-feedback
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Canonical Session-log ratings and notes for finalized assistant messages
4
+
5
+ Part of Rabi, the agent harness UnieAI Code runs on. Installed as a dependency of `@unieai/rabi`;
6
+ not meant to be used on its own.
7
+
8
+ See LICENSE for the license and copyright of this package.
package/lib/index.js ADDED
@@ -0,0 +1,331 @@
1
+ import { Buffer } from "node:buffer";
2
+ import { randomUUID } from "node:crypto";
3
+ import { isDeepStrictEqual } from "node:util";
4
+ import { Service } from "@unieai/cordis";
5
+ import s from "@unieai/schemastery";
6
+ import { z } from "zod";
7
+ import { FEEDBACK_CATEGORIES } from "@unieai/rabi-command-feedback";
8
+ import { SessionSeq } from "@unieai/rabi-session/types";
9
+ import { deriveEventMessage, isAppendSurfaceEvent } from "@unieai/rabi-session/surface";
10
+ import { Remote, TypertRemoteService } from "@unieai/rabi-typert-protocol";
11
+ //#region lib/types/index.js
12
+ /**
13
+ * Canonical Session-log feedback for finalized assistant messages.
14
+ * @module @unieai/rabi-message-feedback
15
+ */
16
+ var __runInitializers = function(thisArg, initializers, value) {
17
+ var useValue = arguments.length > 2;
18
+ for (var i = 0; i < initializers.length; i++) value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
19
+ return useValue ? value : void 0;
20
+ };
21
+ var __esDecorate = function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
22
+ function accept(f) {
23
+ if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
24
+ return f;
25
+ }
26
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
27
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
28
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
29
+ var _, done = false;
30
+ for (var i = decorators.length - 1; i >= 0; i--) {
31
+ var context = {};
32
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
33
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
34
+ context.addInitializer = function(f) {
35
+ if (done) throw new TypeError("Cannot add initializers after decoration has completed");
36
+ extraInitializers.push(accept(f || null));
37
+ };
38
+ var result = (0, decorators[i])(kind === "accessor" ? {
39
+ get: descriptor.get,
40
+ set: descriptor.set
41
+ } : descriptor[key], context);
42
+ if (kind === "accessor") {
43
+ if (result === void 0) continue;
44
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
45
+ if (_ = accept(result.get)) descriptor.get = _;
46
+ if (_ = accept(result.set)) descriptor.set = _;
47
+ if (_ = accept(result.init)) initializers.unshift(_);
48
+ } else if (_ = accept(result)) if (kind === "field") initializers.unshift(_);
49
+ else descriptor[key] = _;
50
+ }
51
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
52
+ done = true;
53
+ };
54
+ const timestamp = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
55
+ const itemSchema = z.object({
56
+ messageId: z.string().min(1),
57
+ rating: z.enum(["positive", "negative"]),
58
+ note: z.string().refine((note) => note.trim().length > 0).optional(),
59
+ category: z.enum(FEEDBACK_CATEGORIES).optional(),
60
+ version: z.uuid(),
61
+ createdAt: timestamp,
62
+ updatedAt: timestamp
63
+ }).refine((item) => item.updatedAt >= item.createdAt);
64
+ const putSchema = z.object({
65
+ sessionId: z.string().min(1),
66
+ item: itemSchema
67
+ });
68
+ const deleteSchema = z.object({
69
+ sessionId: z.string().min(1),
70
+ messageId: z.string().min(1)
71
+ });
72
+ /** Return a caller-owned immutable value, detached from the log. */
73
+ function snapshotItem(item) {
74
+ return Object.freeze({ ...item });
75
+ }
76
+ function success(value) {
77
+ return Object.freeze({
78
+ ok: true,
79
+ value
80
+ });
81
+ }
82
+ function rejected(error) {
83
+ return Object.freeze({
84
+ ok: false,
85
+ error: Object.freeze(error)
86
+ });
87
+ }
88
+ /** Validate persisted payloads before deriving current, Session-owned feedback. */
89
+ function currentItems(sessionId, events) {
90
+ const items = /* @__PURE__ */ new Map();
91
+ for (const event of events) switch (event.type) {
92
+ case "feedback/message-put":
93
+ putSchema.parse(event.data);
94
+ if (event.data.sessionId === sessionId) items.set(event.data.item.messageId, event.data.item);
95
+ break;
96
+ case "feedback/message-delete":
97
+ deleteSchema.parse(event.data);
98
+ if (event.data.sessionId === sessionId) items.delete(event.data.messageId);
99
+ break;
100
+ default: break;
101
+ }
102
+ return [...items.values()];
103
+ }
104
+ /** Session-log service; cold operations never construct a Session or Agent. */
105
+ let MessageFeedbackService = (() => {
106
+ let _classSuper = TypertRemoteService;
107
+ let _instanceExtraInitializers = [];
108
+ let _list_decorators;
109
+ let _put_decorators;
110
+ let _delete_decorators;
111
+ return class MessageFeedbackService extends _classSuper {
112
+ static {
113
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
114
+ _list_decorators = [Remote("list")];
115
+ _put_decorators = [Remote("put")];
116
+ _delete_decorators = [Remote("delete")];
117
+ __esDecorate(this, null, _list_decorators, {
118
+ kind: "method",
119
+ name: "list",
120
+ static: false,
121
+ private: false,
122
+ access: {
123
+ has: (obj) => "list" in obj,
124
+ get: (obj) => obj.list
125
+ },
126
+ metadata: _metadata
127
+ }, null, _instanceExtraInitializers);
128
+ __esDecorate(this, null, _put_decorators, {
129
+ kind: "method",
130
+ name: "put",
131
+ static: false,
132
+ private: false,
133
+ access: {
134
+ has: (obj) => "put" in obj,
135
+ get: (obj) => obj.put
136
+ },
137
+ metadata: _metadata
138
+ }, null, _instanceExtraInitializers);
139
+ __esDecorate(this, null, _delete_decorators, {
140
+ kind: "method",
141
+ name: "delete",
142
+ static: false,
143
+ private: false,
144
+ access: {
145
+ has: (obj) => "delete" in obj,
146
+ get: (obj) => obj.delete
147
+ },
148
+ metadata: _metadata
149
+ }, null, _instanceExtraInitializers);
150
+ if (_metadata) Object.defineProperty(this, Symbol.metadata, {
151
+ enumerable: true,
152
+ configurable: true,
153
+ writable: true,
154
+ value: _metadata
155
+ });
156
+ }
157
+ static inject = ["sessionPersistence", "sessions"];
158
+ /** Loader validation for the required note-size policy. */
159
+ static Config = s.object({ maxNoteBytes: s.number().step(1).min(1).required() });
160
+ maxNoteBytes = __runInitializers(this, _instanceExtraInitializers);
161
+ operationTails = /* @__PURE__ */ new Map();
162
+ mutationAdmissionOpen = true;
163
+ /**
164
+ * @param ctx - Host context carrying Session persistence and live owners.
165
+ * @param config - Required note-size policy.
166
+ */
167
+ constructor(ctx, config) {
168
+ super(ctx, "messageFeedback");
169
+ if (!Number.isSafeInteger(config.maxNoteBytes) || config.maxNoteBytes < 1) throw new TypeError("message-feedback: maxNoteBytes must be a positive safe integer");
170
+ this.maxNoteBytes = config.maxNoteBytes;
171
+ }
172
+ [Service.init]() {
173
+ this.ctx.effect(() => async () => {
174
+ this.mutationAdmissionOpen = false;
175
+ await Promise.all(this.operationTails.values());
176
+ }, "message-feedback.drain");
177
+ }
178
+ /**
179
+ * Read current feedback from the canonical log.
180
+ * @param request - Session to inspect.
181
+ * @returns immutable items or a definite persistence miss.
182
+ */
183
+ list(request) {
184
+ return this.enqueue(request.sessionId, () => this.withSession(request.sessionId, false, (events) => success(Object.freeze({ items: Object.freeze(currentItems(request.sessionId, events).map(snapshotItem)) }))));
185
+ }
186
+ /**
187
+ * Create or replace feedback after checking its current version.
188
+ * Matching no-ops retain the version and append no event.
189
+ * @param request - Target, desired value, and observed item version.
190
+ * @returns the durable item or an explicit business failure.
191
+ */
192
+ put(request) {
193
+ const note = this.resolveNote(request.note);
194
+ if (!note.ok) return Promise.resolve(note);
195
+ return this.enqueue(request.sessionId, () => this.withSession(request.sessionId, true, async (events, append) => {
196
+ const items = currentItems(request.sessionId, events);
197
+ if (!events.some((event) => event.type === "assistant/message" && isAppendSurfaceEvent(event) && deriveEventMessage(event)?.id === request.messageId)) return rejected({
198
+ code: "target-not-found",
199
+ sessionId: request.sessionId,
200
+ messageId: request.messageId
201
+ });
202
+ const existing = items.find((item) => item.messageId === request.messageId);
203
+ if (request.ifVersion !== (existing?.version ?? null)) return rejected(this.versionConflict(existing ?? null));
204
+ if (existing !== void 0 && existing.rating === request.rating && existing.note === note.value && existing.category === request.category) {
205
+ await append();
206
+ return success(snapshotItem(existing));
207
+ }
208
+ const now = Date.now();
209
+ const item = {
210
+ messageId: request.messageId,
211
+ rating: request.rating,
212
+ ...note.value === void 0 ? {} : { note: note.value },
213
+ ...request.category === void 0 ? {} : { category: request.category },
214
+ version: randomUUID(),
215
+ createdAt: existing?.createdAt ?? now,
216
+ updatedAt: existing === void 0 ? now : Math.max(now, existing.updatedAt)
217
+ };
218
+ await append({
219
+ type: "feedback/message-put",
220
+ data: {
221
+ sessionId: request.sessionId,
222
+ item
223
+ }
224
+ });
225
+ return success(snapshotItem(item));
226
+ }));
227
+ }
228
+ /**
229
+ * Delete one item after checking its version; absence succeeds without an event.
230
+ * @param request - Session, message, and observed item version.
231
+ * @returns the stable absent postcondition or an explicit failure.
232
+ */
233
+ delete(request) {
234
+ return this.enqueue(request.sessionId, () => this.withSession(request.sessionId, true, async (events, append) => {
235
+ const existing = currentItems(request.sessionId, events).find((item) => item.messageId === request.messageId);
236
+ if (existing !== void 0) {
237
+ if (request.ifVersion !== existing.version) return rejected(this.versionConflict(existing));
238
+ await append({
239
+ type: "feedback/message-delete",
240
+ data: {
241
+ sessionId: request.sessionId,
242
+ messageId: request.messageId
243
+ }
244
+ });
245
+ } else await append();
246
+ return success(Object.freeze({ absent: true }));
247
+ }));
248
+ }
249
+ /** Hold cold write ownership across read/compare/append; use live owners directly. */
250
+ async withSession(sessionId, write, operation) {
251
+ if (this.ctx.sessions.get(sessionId) === void 0 && await this.ctx.sessionPersistence.stat(sessionId) === void 0 && this.ctx.sessions.get(sessionId) === void 0) return rejected({
252
+ code: "session-not-found",
253
+ sessionId
254
+ });
255
+ const live = this.ctx.sessions.get(sessionId);
256
+ if (live !== void 0) return operation(live.snapshotEvents(), async (event) => {
257
+ if (event !== void 0) live.append(event.type, event.data);
258
+ const last = live.snapshotEvents().at(-1);
259
+ if (!await this.ctx.sessions.flush(live)) throw new Error(`message-feedback: no durability listener participated for live session '${sessionId}'`);
260
+ const handle = await this.ctx.sessionPersistence.open(sessionId, "read");
261
+ try {
262
+ const { events: stored } = await handle.read(last?.seq ?? 0, 1);
263
+ if (!isDeepStrictEqual([
264
+ handle.header.id,
265
+ handle.header.createdAt,
266
+ handle.header.cwd
267
+ ], [
268
+ live.header.id,
269
+ live.header.createdAt,
270
+ live.header.cwd
271
+ ]) || last !== void 0 && !isDeepStrictEqual(stored[0], last)) throw new Error(`message-feedback: feedback prefix is not durable for live session '${sessionId}'`);
272
+ } finally {
273
+ await handle.close();
274
+ }
275
+ });
276
+ const handle = await this.ctx.sessionPersistence.open(sessionId, write ? "write" : "read");
277
+ try {
278
+ const { events } = await handle.read();
279
+ return await operation(events, async (event) => {
280
+ const entry = event === void 0 ? void 0 : {
281
+ ...event,
282
+ seq: SessionSeq(events.length),
283
+ time: Date.now()
284
+ };
285
+ if (entry !== void 0) await handle.append([entry]);
286
+ await handle.flush();
287
+ if (entry !== void 0) try {
288
+ await this.ctx.parallel("feedback/committed", {
289
+ meta: handle.header,
290
+ inheritedEventCount: handle.inheritedEventCount,
291
+ events: [...events, entry]
292
+ });
293
+ } catch (error) {
294
+ this.ctx.logger.warn("message-feedback: committed feedback observer failed", error);
295
+ }
296
+ });
297
+ } finally {
298
+ await handle.close();
299
+ }
300
+ }
301
+ resolveNote(note) {
302
+ if (note === void 0) return success(void 0);
303
+ if (note.trim().length === 0) return rejected({ code: "note-blank" });
304
+ const actualBytes = Buffer.byteLength(note, "utf8");
305
+ if (actualBytes > this.maxNoteBytes) return rejected({
306
+ code: "note-too-large",
307
+ maxBytes: this.maxNoteBytes,
308
+ actualBytes
309
+ });
310
+ return success(note);
311
+ }
312
+ versionConflict(current) {
313
+ return {
314
+ code: "version-conflict",
315
+ current: current === null ? null : snapshotItem(current)
316
+ };
317
+ }
318
+ /** Serialize complete operations and drain their handles before disposal. */
319
+ enqueue(sessionId, operation) {
320
+ if (!this.mutationAdmissionOpen) return Promise.reject(/* @__PURE__ */ new Error("message-feedback: service is disposing"));
321
+ const result = (this.operationTails.get(sessionId) ?? Promise.resolve()).then(operation);
322
+ const tail = result.then(() => void 0, () => void 0);
323
+ this.operationTails.set(sessionId, tail);
324
+ return result.finally(() => {
325
+ if (this.operationTails.get(sessionId) === tail) this.operationTails.delete(sessionId);
326
+ });
327
+ }
328
+ };
329
+ })();
330
+ //#endregion
331
+ export { MessageFeedbackService, MessageFeedbackService as default };
@@ -0,0 +1,3 @@
1
+ /* Generated by @unieai/rabi-typert-generator from FaceModel — do not edit. */
2
+
3
+ export declare const TYPERT: unknown