@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.
@@ -0,0 +1,232 @@
1
+ /* Generated by @unieai/rabi-typert-generator from the Host FaceModel — do not edit. */
2
+ import { z } from 'zod'
3
+
4
+ import { createTypertRemoteInfo } from '@unieai/rabi-typert-protocol/remote-info'
5
+
6
+ let _unieai_rabi_message_feedback_messageFeedback_delete_parameter_0$schema$value
7
+ const _unieai_rabi_message_feedback_messageFeedback_delete_parameter_0$schema = () => (_unieai_rabi_message_feedback_messageFeedback_delete_parameter_0$schema$value ??= z.object({
8
+ 'sessionId': z.string().readonly().describe('Session that owns the feedback.'),
9
+ 'messageId': z.string().readonly().describe('Message whose feedback should be absent after this operation.'),
10
+ 'ifVersion': z.string().readonly().describe('Observed item version; ignored when the item is already absent.'),
11
+ }))
12
+ let _unieai_rabi_message_feedback_messageFeedback_delete_result$schema$value
13
+ const _unieai_rabi_message_feedback_messageFeedback_delete_result$schema = () => (_unieai_rabi_message_feedback_messageFeedback_delete_result$schema$value ??= z.union([z.object({
14
+ 'ok': z.literal(true).readonly(),
15
+ 'value': z.object({
16
+ 'absent': z.literal(true).readonly().describe('Stable postcondition shared by the first deletion and every retry.'),
17
+ }).readonly(),
18
+ }), z.object({
19
+ 'ok': z.literal(false).readonly(),
20
+ 'error': z.union([z.object({
21
+ 'code': z.literal("session-not-found").readonly(),
22
+ 'sessionId': z.string().readonly(),
23
+ }), z.object({
24
+ 'code': z.literal("version-conflict").readonly(),
25
+ 'current': z.union([z.literal(null), z.object({
26
+ 'messageId': z.string().readonly().describe('Stable identity of the assistant message inside the owning Session.'),
27
+ 'rating': z.union([z.literal("positive"), z.literal("negative")]).readonly().describe('Overall positive or negative judgment.'),
28
+ 'note': z.string().readonly().optional().describe('Optional explanation, preserved verbatim after validation.'),
29
+ 'category': z.union([z.literal("other"), z.literal("task-result"), z.literal("instruction-following"), z.literal("product-interaction"), z.literal("service-stability"), z.literal("resource-cost"), z.literal("security-privacy-permission")]).readonly().optional().describe('Category the human filed the judgment under.'),
30
+ 'version': z.string().readonly().describe('Equality-only token replaced by every material create or update.'),
31
+ 'createdAt': z.number().readonly().describe('Host-assigned creation time in Unix epoch milliseconds.'),
32
+ 'updatedAt': z.number().readonly().describe('Host-assigned time of the most recent material update.'),
33
+ })]).readonly().describe('Authoritative current item, or `null` when it does not exist.'),
34
+ })]).readonly(),
35
+ })]))
36
+ let _unieai_rabi_message_feedback_messageFeedback_list_parameter_0$schema$value
37
+ const _unieai_rabi_message_feedback_messageFeedback_list_parameter_0$schema = () => (_unieai_rabi_message_feedback_messageFeedback_list_parameter_0$schema$value ??= z.object({
38
+ 'sessionId': z.string().readonly().describe('Session whose feedback events should be read.'),
39
+ }))
40
+ let _unieai_rabi_message_feedback_messageFeedback_list_result$schema$value
41
+ const _unieai_rabi_message_feedback_messageFeedback_list_result$schema = () => (_unieai_rabi_message_feedback_messageFeedback_list_result$schema$value ??= z.union([z.object({
42
+ 'ok': z.literal(true).readonly(),
43
+ 'value': z.object({
44
+ 'items': z.array(z.object({
45
+ 'messageId': z.string().readonly().describe('Stable identity of the assistant message inside the owning Session.'),
46
+ 'rating': z.union([z.literal("positive"), z.literal("negative")]).readonly().describe('Overall positive or negative judgment.'),
47
+ 'note': z.string().readonly().optional().describe('Optional explanation, preserved verbatim after validation.'),
48
+ 'category': z.union([z.literal("other"), z.literal("task-result"), z.literal("instruction-following"), z.literal("product-interaction"), z.literal("service-stability"), z.literal("resource-cost"), z.literal("security-privacy-permission")]).readonly().optional().describe('Category the human filed the judgment under.'),
49
+ 'version': z.string().readonly().describe('Equality-only token replaced by every material create or update.'),
50
+ 'createdAt': z.number().readonly().describe('Host-assigned creation time in Unix epoch milliseconds.'),
51
+ 'updatedAt': z.number().readonly().describe('Host-assigned time of the most recent material update.'),
52
+ })).readonly().describe('Fresh immutable item snapshots.'),
53
+ }).readonly(),
54
+ }), z.object({
55
+ 'ok': z.literal(false).readonly(),
56
+ 'error': z.object({
57
+ 'code': z.literal("session-not-found").readonly(),
58
+ 'sessionId': z.string().readonly(),
59
+ }).readonly(),
60
+ })]))
61
+ let _unieai_rabi_message_feedback_messageFeedback_put_parameter_0$schema$value
62
+ const _unieai_rabi_message_feedback_messageFeedback_put_parameter_0$schema = () => (_unieai_rabi_message_feedback_messageFeedback_put_parameter_0$schema$value ??= z.object({
63
+ 'sessionId': z.string().readonly().describe('Persisted Session that owns the target message.'),
64
+ 'messageId': z.string().readonly().describe('Target assistant-message identity.'),
65
+ 'rating': z.union([z.literal("positive"), z.literal("negative")]).readonly().describe('Desired overall judgment.'),
66
+ 'note': z.string().readonly().optional().describe('Optional non-blank explanation.'),
67
+ 'category': z.union([z.literal("other"), z.literal("task-result"), z.literal("instruction-following"), z.literal("product-interaction"), z.literal("service-stability"), z.literal("resource-cost"), z.literal("security-privacy-permission")]).readonly().optional().describe('Optional category; absent keeps the item uncategorized.'),
68
+ 'ifVersion': z.union([z.literal(null), z.string()]).readonly().describe('Observed item version, or `null` to require that no item exists.'),
69
+ }))
70
+ let _unieai_rabi_message_feedback_messageFeedback_put_result$schema$value
71
+ const _unieai_rabi_message_feedback_messageFeedback_put_result$schema = () => (_unieai_rabi_message_feedback_messageFeedback_put_result$schema$value ??= z.union([z.object({
72
+ 'ok': z.literal(true).readonly(),
73
+ 'value': z.object({
74
+ 'messageId': z.string().readonly().describe('Stable identity of the assistant message inside the owning Session.'),
75
+ 'rating': z.union([z.literal("positive"), z.literal("negative")]).readonly().describe('Overall positive or negative judgment.'),
76
+ 'note': z.string().readonly().optional().describe('Optional explanation, preserved verbatim after validation.'),
77
+ 'category': z.union([z.literal("other"), z.literal("task-result"), z.literal("instruction-following"), z.literal("product-interaction"), z.literal("service-stability"), z.literal("resource-cost"), z.literal("security-privacy-permission")]).readonly().optional().describe('Category the human filed the judgment under.'),
78
+ 'version': z.string().readonly().describe('Equality-only token replaced by every material create or update.'),
79
+ 'createdAt': z.number().readonly().describe('Host-assigned creation time in Unix epoch milliseconds.'),
80
+ 'updatedAt': z.number().readonly().describe('Host-assigned time of the most recent material update.'),
81
+ }).readonly(),
82
+ }), z.object({
83
+ 'ok': z.literal(false).readonly(),
84
+ 'error': z.union([z.object({
85
+ 'code': z.literal("session-not-found").readonly(),
86
+ 'sessionId': z.string().readonly(),
87
+ }), z.object({
88
+ 'code': z.literal("target-not-found").readonly(),
89
+ 'sessionId': z.string().readonly(),
90
+ 'messageId': z.string().readonly(),
91
+ }), z.object({
92
+ 'code': z.literal("version-conflict").readonly(),
93
+ 'current': z.union([z.literal(null), z.object({
94
+ 'messageId': z.string().readonly().describe('Stable identity of the assistant message inside the owning Session.'),
95
+ 'rating': z.union([z.literal("positive"), z.literal("negative")]).readonly().describe('Overall positive or negative judgment.'),
96
+ 'note': z.string().readonly().optional().describe('Optional explanation, preserved verbatim after validation.'),
97
+ 'category': z.union([z.literal("other"), z.literal("task-result"), z.literal("instruction-following"), z.literal("product-interaction"), z.literal("service-stability"), z.literal("resource-cost"), z.literal("security-privacy-permission")]).readonly().optional().describe('Category the human filed the judgment under.'),
98
+ 'version': z.string().readonly().describe('Equality-only token replaced by every material create or update.'),
99
+ 'createdAt': z.number().readonly().describe('Host-assigned creation time in Unix epoch milliseconds.'),
100
+ 'updatedAt': z.number().readonly().describe('Host-assigned time of the most recent material update.'),
101
+ })]).readonly().describe('Authoritative current item, or `null` when it does not exist.'),
102
+ }), z.object({
103
+ 'code': z.literal("note-blank").readonly(),
104
+ }), z.object({
105
+ 'code': z.literal("note-too-large").readonly(),
106
+ 'maxBytes': z.number().readonly(),
107
+ 'actualBytes': z.number().readonly(),
108
+ })]).readonly(),
109
+ })]))
110
+ let _unieai_rabi_message_feedback_messageFeedback_delete_parameter_0_strict$schema$value
111
+ const _unieai_rabi_message_feedback_messageFeedback_delete_parameter_0_strict$schema = () => (_unieai_rabi_message_feedback_messageFeedback_delete_parameter_0_strict$schema$value ??= z.strictObject({
112
+ 'sessionId': z.string().readonly().describe('Session that owns the feedback.'),
113
+ 'messageId': z.string().readonly().describe('Message whose feedback should be absent after this operation.'),
114
+ 'ifVersion': z.string().readonly().describe('Observed item version; ignored when the item is already absent.'),
115
+ }))
116
+ let _unieai_rabi_message_feedback_messageFeedback_list_parameter_0_strict$schema$value
117
+ const _unieai_rabi_message_feedback_messageFeedback_list_parameter_0_strict$schema = () => (_unieai_rabi_message_feedback_messageFeedback_list_parameter_0_strict$schema$value ??= z.strictObject({
118
+ 'sessionId': z.string().readonly().describe('Session whose feedback events should be read.'),
119
+ }))
120
+ let _unieai_rabi_message_feedback_messageFeedback_put_parameter_0_strict$schema$value
121
+ const _unieai_rabi_message_feedback_messageFeedback_put_parameter_0_strict$schema = () => (_unieai_rabi_message_feedback_messageFeedback_put_parameter_0_strict$schema$value ??= z.strictObject({
122
+ 'sessionId': z.string().readonly().describe('Persisted Session that owns the target message.'),
123
+ 'messageId': z.string().readonly().describe('Target assistant-message identity.'),
124
+ 'rating': z.union([z.literal("positive"), z.literal("negative")]).readonly().describe('Desired overall judgment.'),
125
+ 'note': z.string().readonly().optional().describe('Optional non-blank explanation.'),
126
+ 'category': z.union([z.literal("other"), z.literal("task-result"), z.literal("instruction-following"), z.literal("product-interaction"), z.literal("service-stability"), z.literal("resource-cost"), z.literal("security-privacy-permission")]).readonly().optional().describe('Optional category; absent keeps the item uncategorized.'),
127
+ 'ifVersion': z.union([z.literal(null), z.string()]).readonly().describe('Observed item version, or `null` to require that no item exists.'),
128
+ }))
129
+
130
+ export const TYPERT_REMOTE = createTypertRemoteInfo({
131
+ package: '@unieai/rabi-message-feedback',
132
+ methods: {
133
+ 'messageFeedback/delete': {
134
+ service: 'messageFeedback',
135
+ description: 'Delete one item after checking its version; absence succeeds without an event.',
136
+ invocation: { kind: 'direct' },
137
+ parameters: [
138
+ {
139
+ name: 'request',
140
+ description: 'Session, message, and observed item version.',
141
+ source: 'json',
142
+ codec: {
143
+ mode: 'strict',
144
+ typeSymbol: '@unieai/rabi-message-feedback/types#MessageFeedbackDeleteRequest',
145
+ create: _unieai_rabi_message_feedback_messageFeedback_delete_parameter_0$schema,
146
+ jsonSchema: {"type":"object","properties":{"sessionId":{"type":"string","description":"Session that owns the feedback."},"messageId":{"type":"string","description":"Message whose feedback should be absent after this operation."},"ifVersion":{"type":"string","description":"Observed item version; ignored when the item is already absent."}},"required":["sessionId","messageId","ifVersion"],"additionalProperties":true},
147
+ },
148
+ strictCodec: {
149
+ mode: 'strict',
150
+ typeSymbol: '@unieai/rabi-message-feedback/types#MessageFeedbackDeleteRequest',
151
+ create: _unieai_rabi_message_feedback_messageFeedback_delete_parameter_0_strict$schema,
152
+ jsonSchema: {"type":"object","properties":{"sessionId":{"type":"string","description":"Session that owns the feedback."},"messageId":{"type":"string","description":"Message whose feedback should be absent after this operation."},"ifVersion":{"type":"string","description":"Observed item version; ignored when the item is already absent."}},"required":["sessionId","messageId","ifVersion"],"additionalProperties":false},
153
+ },
154
+ },
155
+ ],
156
+ result: {
157
+ mode: 'strict',
158
+ typeSymbol: '@unieai/rabi-message-feedback/types#MessageFeedbackDeleteResult',
159
+ create: _unieai_rabi_message_feedback_messageFeedback_delete_result$schema,
160
+ description: 'the stable absent postcondition or an explicit failure.',
161
+ jsonSchema: {"oneOf":[{"type":"object","properties":{"ok":{"type":"boolean","const":true},"value":{"type":"object","properties":{"absent":{"type":"boolean","const":true,"description":"Stable postcondition shared by the first deletion and every retry."}},"required":["absent"],"additionalProperties":true}},"required":["ok","value"],"additionalProperties":true},{"type":"object","properties":{"ok":{"type":"boolean","const":false},"error":{"oneOf":[{"type":"object","properties":{"code":{"type":"string","const":"session-not-found"},"sessionId":{"type":"string"}},"required":["code","sessionId"],"additionalProperties":true},{"type":"object","properties":{"code":{"type":"string","const":"version-conflict"},"current":{"oneOf":[{"type":"null","const":null},{"type":"object","properties":{"messageId":{"type":"string","description":"Stable identity of the assistant message inside the owning Session."},"rating":{"type":"string","enum":["positive","negative"],"description":"Overall positive or negative judgment."},"note":{"type":"string","description":"Optional explanation, preserved verbatim after validation."},"category":{"type":"string","enum":["other","task-result","instruction-following","product-interaction","service-stability","resource-cost","security-privacy-permission"],"description":"Category the human filed the judgment under."},"version":{"type":"string","description":"Equality-only token replaced by every material create or update."},"createdAt":{"type":"number","description":"Host-assigned creation time in Unix epoch milliseconds."},"updatedAt":{"type":"number","description":"Host-assigned time of the most recent material update."}},"required":["messageId","rating","version","createdAt","updatedAt"],"additionalProperties":true}],"description":"Authoritative current item, or `null` when it does not exist."}},"required":["code","current"],"additionalProperties":true}]}},"required":["ok","error"],"additionalProperties":true}]},
162
+ },
163
+ sourceLocation: {"file":"packages/feedback/message-feedback/src/index.ts","line":207,"column":3},
164
+ },
165
+ 'messageFeedback/list': {
166
+ service: 'messageFeedback',
167
+ description: 'Read current feedback from the canonical log.',
168
+ invocation: { kind: 'direct' },
169
+ parameters: [
170
+ {
171
+ name: 'request',
172
+ description: 'Session to inspect.',
173
+ source: 'json',
174
+ codec: {
175
+ mode: 'strict',
176
+ typeSymbol: '@unieai/rabi-message-feedback/types#MessageFeedbackListRequest',
177
+ create: _unieai_rabi_message_feedback_messageFeedback_list_parameter_0$schema,
178
+ jsonSchema: {"type":"object","properties":{"sessionId":{"type":"string","description":"Session whose feedback events should be read."}},"required":["sessionId"],"additionalProperties":true},
179
+ },
180
+ strictCodec: {
181
+ mode: 'strict',
182
+ typeSymbol: '@unieai/rabi-message-feedback/types#MessageFeedbackListRequest',
183
+ create: _unieai_rabi_message_feedback_messageFeedback_list_parameter_0_strict$schema,
184
+ jsonSchema: {"type":"object","properties":{"sessionId":{"type":"string","description":"Session whose feedback events should be read."}},"required":["sessionId"],"additionalProperties":false},
185
+ },
186
+ },
187
+ ],
188
+ result: {
189
+ mode: 'strict',
190
+ typeSymbol: '@unieai/rabi-message-feedback/types#MessageFeedbackListResult',
191
+ create: _unieai_rabi_message_feedback_messageFeedback_list_result$schema,
192
+ description: 'immutable items or a definite persistence miss.',
193
+ jsonSchema: {"oneOf":[{"type":"object","properties":{"ok":{"type":"boolean","const":true},"value":{"type":"object","properties":{"items":{"type":"array","items":{"type":"object","properties":{"messageId":{"type":"string","description":"Stable identity of the assistant message inside the owning Session."},"rating":{"type":"string","enum":["positive","negative"],"description":"Overall positive or negative judgment."},"note":{"type":"string","description":"Optional explanation, preserved verbatim after validation."},"category":{"type":"string","enum":["other","task-result","instruction-following","product-interaction","service-stability","resource-cost","security-privacy-permission"],"description":"Category the human filed the judgment under."},"version":{"type":"string","description":"Equality-only token replaced by every material create or update."},"createdAt":{"type":"number","description":"Host-assigned creation time in Unix epoch milliseconds."},"updatedAt":{"type":"number","description":"Host-assigned time of the most recent material update."}},"required":["messageId","rating","version","createdAt","updatedAt"],"additionalProperties":true},"description":"Fresh immutable item snapshots."}},"required":["items"],"additionalProperties":true}},"required":["ok","value"],"additionalProperties":true},{"type":"object","properties":{"ok":{"type":"boolean","const":false},"error":{"type":"object","properties":{"code":{"type":"string","const":"session-not-found"},"sessionId":{"type":"string"}},"required":["code","sessionId"],"additionalProperties":true}},"required":["ok","error"],"additionalProperties":true}]},
194
+ },
195
+ sourceLocation: {"file":"packages/feedback/message-feedback/src/index.ts","line":155,"column":3},
196
+ },
197
+ 'messageFeedback/put': {
198
+ service: 'messageFeedback',
199
+ description: 'Create or replace feedback after checking its current version. Matching no-ops retain the version and append no event.',
200
+ invocation: { kind: 'direct' },
201
+ parameters: [
202
+ {
203
+ name: 'request',
204
+ description: 'Target, desired value, and observed item version.',
205
+ source: 'json',
206
+ codec: {
207
+ mode: 'strict',
208
+ typeSymbol: '@unieai/rabi-message-feedback/types#MessageFeedbackPutRequest',
209
+ create: _unieai_rabi_message_feedback_messageFeedback_put_parameter_0$schema,
210
+ jsonSchema: {"type":"object","properties":{"sessionId":{"type":"string","description":"Persisted Session that owns the target message."},"messageId":{"type":"string","description":"Target assistant-message identity."},"rating":{"type":"string","enum":["positive","negative"],"description":"Desired overall judgment."},"note":{"type":"string","description":"Optional non-blank explanation."},"category":{"type":"string","enum":["other","task-result","instruction-following","product-interaction","service-stability","resource-cost","security-privacy-permission"],"description":"Optional category; absent keeps the item uncategorized."},"ifVersion":{"oneOf":[{"type":"null","const":null},{"type":"string"}],"description":"Observed item version, or `null` to require that no item exists."}},"required":["sessionId","messageId","rating","ifVersion"],"additionalProperties":true},
211
+ },
212
+ strictCodec: {
213
+ mode: 'strict',
214
+ typeSymbol: '@unieai/rabi-message-feedback/types#MessageFeedbackPutRequest',
215
+ create: _unieai_rabi_message_feedback_messageFeedback_put_parameter_0_strict$schema,
216
+ jsonSchema: {"type":"object","properties":{"sessionId":{"type":"string","description":"Persisted Session that owns the target message."},"messageId":{"type":"string","description":"Target assistant-message identity."},"rating":{"type":"string","enum":["positive","negative"],"description":"Desired overall judgment."},"note":{"type":"string","description":"Optional non-blank explanation."},"category":{"type":"string","enum":["other","task-result","instruction-following","product-interaction","service-stability","resource-cost","security-privacy-permission"],"description":"Optional category; absent keeps the item uncategorized."},"ifVersion":{"oneOf":[{"type":"null","const":null},{"type":"string"}],"description":"Observed item version, or `null` to require that no item exists."}},"required":["sessionId","messageId","rating","ifVersion"],"additionalProperties":false},
217
+ },
218
+ },
219
+ ],
220
+ result: {
221
+ mode: 'strict',
222
+ typeSymbol: '@unieai/rabi-message-feedback/types#MessageFeedbackPutResult',
223
+ create: _unieai_rabi_message_feedback_messageFeedback_put_result$schema,
224
+ description: 'the durable item or an explicit business failure.',
225
+ jsonSchema: {"oneOf":[{"type":"object","properties":{"ok":{"type":"boolean","const":true},"value":{"type":"object","properties":{"messageId":{"type":"string","description":"Stable identity of the assistant message inside the owning Session."},"rating":{"type":"string","enum":["positive","negative"],"description":"Overall positive or negative judgment."},"note":{"type":"string","description":"Optional explanation, preserved verbatim after validation."},"category":{"type":"string","enum":["other","task-result","instruction-following","product-interaction","service-stability","resource-cost","security-privacy-permission"],"description":"Category the human filed the judgment under."},"version":{"type":"string","description":"Equality-only token replaced by every material create or update."},"createdAt":{"type":"number","description":"Host-assigned creation time in Unix epoch milliseconds."},"updatedAt":{"type":"number","description":"Host-assigned time of the most recent material update."}},"required":["messageId","rating","version","createdAt","updatedAt"],"additionalProperties":true}},"required":["ok","value"],"additionalProperties":true},{"type":"object","properties":{"ok":{"type":"boolean","const":false},"error":{"oneOf":[{"type":"object","properties":{"code":{"type":"string","const":"session-not-found"},"sessionId":{"type":"string"}},"required":["code","sessionId"],"additionalProperties":true},{"type":"object","properties":{"code":{"type":"string","const":"target-not-found"},"sessionId":{"type":"string"},"messageId":{"type":"string"}},"required":["code","sessionId","messageId"],"additionalProperties":true},{"type":"object","properties":{"code":{"type":"string","const":"version-conflict"},"current":{"oneOf":[{"type":"null","const":null},{"type":"object","properties":{"messageId":{"type":"string","description":"Stable identity of the assistant message inside the owning Session."},"rating":{"type":"string","enum":["positive","negative"],"description":"Overall positive or negative judgment."},"note":{"type":"string","description":"Optional explanation, preserved verbatim after validation."},"category":{"type":"string","enum":["other","task-result","instruction-following","product-interaction","service-stability","resource-cost","security-privacy-permission"],"description":"Category the human filed the judgment under."},"version":{"type":"string","description":"Equality-only token replaced by every material create or update."},"createdAt":{"type":"number","description":"Host-assigned creation time in Unix epoch milliseconds."},"updatedAt":{"type":"number","description":"Host-assigned time of the most recent material update."}},"required":["messageId","rating","version","createdAt","updatedAt"],"additionalProperties":true}],"description":"Authoritative current item, or `null` when it does not exist."}},"required":["code","current"],"additionalProperties":true},{"type":"object","properties":{"code":{"type":"string","const":"note-blank"}},"required":["code"],"additionalProperties":true},{"type":"object","properties":{"code":{"type":"string","const":"note-too-large"},"maxBytes":{"type":"number"},"actualBytes":{"type":"number"}},"required":["code","maxBytes","actualBytes"],"additionalProperties":true}]}},"required":["ok","error"],"additionalProperties":true}]},
226
+ },
227
+ sourceLocation: {"file":"packages/feedback/message-feedback/src/index.ts","line":167,"column":3},
228
+ },
229
+ },
230
+ }, z)
231
+
232
+ export default TYPERT_REMOTE
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Canonical Session-log feedback for finalized assistant messages.
3
+ * @module @unieai/rabi-message-feedback
4
+ */
5
+ import { Context, Service } from '@unieai/cordis';
6
+ import s from '@unieai/schemastery';
7
+ import type { SessionInspection } from '@unieai/rabi-session-persistence';
8
+ import { TypertRemoteService } from '@unieai/rabi-typert-protocol';
9
+ import type { MessageFeedbackDeleteRequest, MessageFeedbackDeleteResult, MessageFeedbackListRequest, MessageFeedbackListResult, MessageFeedbackPutRequest, MessageFeedbackPutResult } from './types.ts';
10
+ export type * from './types.ts';
11
+ /** Required deployment policy for optional notes. */
12
+ export interface Config {
13
+ /** Maximum UTF-8 byte length accepted for one note. */
14
+ readonly maxNoteBytes: number;
15
+ }
16
+ declare module '@unieai/cordis' {
17
+ interface Context {
18
+ messageFeedback: MessageFeedbackService;
19
+ }
20
+ interface Events {
21
+ /**
22
+ * Observe a durable cold feedback mutation without publishing a live Session.
23
+ * Observers run before write ownership is released and must not await
24
+ * another message-feedback operation for this Session. The payload is borrowed
25
+ * read-only; deep-clone it before transferring ownership (for example, to Session.fromRestore).
26
+ * @param inspection - committed canonical prefix, including the feedback as its last event.
27
+ * @mode parallel
28
+ */
29
+ 'feedback/committed'(inspection: SessionInspection): void;
30
+ }
31
+ }
32
+ /** Session-log service; cold operations never construct a Session or Agent. */
33
+ export declare class MessageFeedbackService extends TypertRemoteService {
34
+ static inject: string[];
35
+ /** Loader validation for the required note-size policy. */
36
+ static Config: s<Config>;
37
+ private readonly maxNoteBytes;
38
+ private readonly operationTails;
39
+ private mutationAdmissionOpen;
40
+ /**
41
+ * @param ctx - Host context carrying Session persistence and live owners.
42
+ * @param config - Required note-size policy.
43
+ */
44
+ constructor(ctx: Context, config: Config);
45
+ protected [Service.init](): void;
46
+ /**
47
+ * Read current feedback from the canonical log.
48
+ * @param request - Session to inspect.
49
+ * @returns immutable items or a definite persistence miss.
50
+ */
51
+ list(request: MessageFeedbackListRequest): Promise<MessageFeedbackListResult>;
52
+ /**
53
+ * Create or replace feedback after checking its current version.
54
+ * Matching no-ops retain the version and append no event.
55
+ * @param request - Target, desired value, and observed item version.
56
+ * @returns the durable item or an explicit business failure.
57
+ */
58
+ put(request: MessageFeedbackPutRequest): Promise<MessageFeedbackPutResult>;
59
+ /**
60
+ * Delete one item after checking its version; absence succeeds without an event.
61
+ * @param request - Session, message, and observed item version.
62
+ * @returns the stable absent postcondition or an explicit failure.
63
+ */
64
+ delete(request: MessageFeedbackDeleteRequest): Promise<MessageFeedbackDeleteResult>;
65
+ /** Hold cold write ownership across read/compare/append; use live owners directly. */
66
+ private withSession;
67
+ private resolveNote;
68
+ private versionConflict;
69
+ /** Serialize complete operations and drain their handles before disposal. */
70
+ private enqueue;
71
+ }
72
+ export default MessageFeedbackService;
73
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,293 @@
1
+ /**
2
+ * Canonical Session-log feedback for finalized assistant messages.
3
+ * @module @unieai/rabi-message-feedback
4
+ */
5
+ var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
6
+ var useValue = arguments.length > 2;
7
+ for (var i = 0; i < initializers.length; i++) {
8
+ value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
9
+ }
10
+ return useValue ? value : void 0;
11
+ };
12
+ var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
13
+ function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
14
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
15
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
16
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
17
+ var _, done = false;
18
+ for (var i = decorators.length - 1; i >= 0; i--) {
19
+ var context = {};
20
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
21
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
22
+ context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
23
+ var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
24
+ if (kind === "accessor") {
25
+ if (result === void 0) continue;
26
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
27
+ if (_ = accept(result.get)) descriptor.get = _;
28
+ if (_ = accept(result.set)) descriptor.set = _;
29
+ if (_ = accept(result.init)) initializers.unshift(_);
30
+ }
31
+ else if (_ = accept(result)) {
32
+ if (kind === "field") initializers.unshift(_);
33
+ else descriptor[key] = _;
34
+ }
35
+ }
36
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
37
+ done = true;
38
+ };
39
+ import { Buffer } from 'node:buffer';
40
+ import { randomUUID } from 'node:crypto';
41
+ import { isDeepStrictEqual } from 'node:util';
42
+ import { Service } from '@unieai/cordis';
43
+ import s from '@unieai/schemastery';
44
+ import { z } from 'zod';
45
+ import { FEEDBACK_CATEGORIES } from '@unieai/rabi-command-feedback';
46
+ import { SessionSeq } from '@unieai/rabi-session/types';
47
+ import { deriveEventMessage, isAppendSurfaceEvent } from '@unieai/rabi-session/surface';
48
+ import { TypertRemoteService, Remote } from '@unieai/rabi-typert-protocol';
49
+ const timestamp = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
50
+ const itemSchema = z.object({
51
+ messageId: z.string().min(1),
52
+ rating: z.enum(['positive', 'negative']),
53
+ note: z.string().refine(note => note.trim().length > 0).optional(),
54
+ category: z.enum(FEEDBACK_CATEGORIES).optional(),
55
+ version: z.uuid(),
56
+ createdAt: timestamp,
57
+ updatedAt: timestamp,
58
+ }).refine(item => item.updatedAt >= item.createdAt);
59
+ const putSchema = z.object({ sessionId: z.string().min(1), item: itemSchema });
60
+ const deleteSchema = z.object({ sessionId: z.string().min(1), messageId: z.string().min(1) });
61
+ /** Return a caller-owned immutable value, detached from the log. */
62
+ function snapshotItem(item) {
63
+ return Object.freeze({ ...item });
64
+ }
65
+ function success(value) {
66
+ return Object.freeze({ ok: true, value });
67
+ }
68
+ function rejected(error) {
69
+ return Object.freeze({ ok: false, error: Object.freeze(error) });
70
+ }
71
+ /** Validate persisted payloads before deriving current, Session-owned feedback. */
72
+ function currentItems(sessionId, events) {
73
+ const items = new Map();
74
+ for (const event of events) {
75
+ switch (event.type) {
76
+ case 'feedback/message-put':
77
+ putSchema.parse(event.data);
78
+ if (event.data.sessionId === sessionId)
79
+ items.set(event.data.item.messageId, event.data.item);
80
+ break;
81
+ case 'feedback/message-delete':
82
+ deleteSchema.parse(event.data);
83
+ if (event.data.sessionId === sessionId)
84
+ items.delete(event.data.messageId);
85
+ break;
86
+ default:
87
+ // Other plugins' events do not change message feedback.
88
+ break;
89
+ }
90
+ }
91
+ return [...items.values()];
92
+ }
93
+ /** Session-log service; cold operations never construct a Session or Agent. */
94
+ let MessageFeedbackService = (() => {
95
+ let _classSuper = TypertRemoteService;
96
+ let _instanceExtraInitializers = [];
97
+ let _list_decorators;
98
+ let _put_decorators;
99
+ let _delete_decorators;
100
+ return class MessageFeedbackService extends _classSuper {
101
+ static {
102
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
103
+ _list_decorators = [Remote('list')];
104
+ _put_decorators = [Remote('put')];
105
+ _delete_decorators = [Remote('delete')];
106
+ __esDecorate(this, null, _list_decorators, { kind: "method", name: "list", static: false, private: false, access: { has: obj => "list" in obj, get: obj => obj.list }, metadata: _metadata }, null, _instanceExtraInitializers);
107
+ __esDecorate(this, null, _put_decorators, { kind: "method", name: "put", static: false, private: false, access: { has: obj => "put" in obj, get: obj => obj.put }, metadata: _metadata }, null, _instanceExtraInitializers);
108
+ __esDecorate(this, null, _delete_decorators, { kind: "method", name: "delete", static: false, private: false, access: { has: obj => "delete" in obj, get: obj => obj.delete }, metadata: _metadata }, null, _instanceExtraInitializers);
109
+ if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
110
+ }
111
+ static inject = ['sessionPersistence', 'sessions'];
112
+ /** Loader validation for the required note-size policy. */
113
+ static Config = s.object({
114
+ maxNoteBytes: s.number().step(1).min(1).required(),
115
+ });
116
+ maxNoteBytes = __runInitializers(this, _instanceExtraInitializers);
117
+ operationTails = new Map();
118
+ mutationAdmissionOpen = true;
119
+ /**
120
+ * @param ctx - Host context carrying Session persistence and live owners.
121
+ * @param config - Required note-size policy.
122
+ */
123
+ constructor(ctx, config) {
124
+ super(ctx, 'messageFeedback');
125
+ if (!Number.isSafeInteger(config.maxNoteBytes) || config.maxNoteBytes < 1) {
126
+ throw new TypeError('message-feedback: maxNoteBytes must be a positive safe integer');
127
+ }
128
+ this.maxNoteBytes = config.maxNoteBytes;
129
+ }
130
+ [Service.init]() {
131
+ this.ctx.effect(() => async () => {
132
+ this.mutationAdmissionOpen = false;
133
+ await Promise.all(this.operationTails.values());
134
+ }, 'message-feedback.drain');
135
+ }
136
+ /**
137
+ * Read current feedback from the canonical log.
138
+ * @param request - Session to inspect.
139
+ * @returns immutable items or a definite persistence miss.
140
+ */
141
+ list(request) {
142
+ return this.enqueue(request.sessionId, () => this.withSession(request.sessionId, false, events => success(Object.freeze({ items: Object.freeze(currentItems(request.sessionId, events).map(snapshotItem)) }))));
143
+ }
144
+ /**
145
+ * Create or replace feedback after checking its current version.
146
+ * Matching no-ops retain the version and append no event.
147
+ * @param request - Target, desired value, and observed item version.
148
+ * @returns the durable item or an explicit business failure.
149
+ */
150
+ put(request) {
151
+ const note = this.resolveNote(request.note);
152
+ if (!note.ok)
153
+ return Promise.resolve(note);
154
+ return this.enqueue(request.sessionId, () => this.withSession(request.sessionId, true, async (events, append) => {
155
+ const items = currentItems(request.sessionId, events);
156
+ if (!events.some(event => event.type === 'assistant/message'
157
+ && isAppendSurfaceEvent(event)
158
+ && deriveEventMessage(event)?.id === request.messageId)) {
159
+ return rejected({ code: 'target-not-found', sessionId: request.sessionId, messageId: request.messageId });
160
+ }
161
+ const existing = items.find(item => item.messageId === request.messageId);
162
+ if (request.ifVersion !== (existing?.version ?? null)) {
163
+ return rejected(this.versionConflict(existing ?? null));
164
+ }
165
+ if (existing !== undefined && existing.rating === request.rating && existing.note === note.value
166
+ && existing.category === request.category) {
167
+ await append();
168
+ return success(snapshotItem(existing));
169
+ }
170
+ const now = Date.now();
171
+ const item = {
172
+ messageId: request.messageId,
173
+ rating: request.rating,
174
+ ...(note.value === undefined ? {} : { note: note.value }),
175
+ ...(request.category === undefined ? {} : { category: request.category }),
176
+ version: randomUUID(),
177
+ createdAt: existing?.createdAt ?? now,
178
+ updatedAt: existing === undefined ? now : Math.max(now, existing.updatedAt),
179
+ };
180
+ await append({ type: 'feedback/message-put', data: { sessionId: request.sessionId, item } });
181
+ return success(snapshotItem(item));
182
+ }));
183
+ }
184
+ /**
185
+ * Delete one item after checking its version; absence succeeds without an event.
186
+ * @param request - Session, message, and observed item version.
187
+ * @returns the stable absent postcondition or an explicit failure.
188
+ */
189
+ delete(request) {
190
+ return this.enqueue(request.sessionId, () => this.withSession(request.sessionId, true, async (events, append) => {
191
+ const existing = currentItems(request.sessionId, events).find(item => item.messageId === request.messageId);
192
+ if (existing !== undefined) {
193
+ if (request.ifVersion !== existing.version)
194
+ return rejected(this.versionConflict(existing));
195
+ await append({ type: 'feedback/message-delete', data: { sessionId: request.sessionId, messageId: request.messageId } });
196
+ }
197
+ else {
198
+ await append();
199
+ }
200
+ return success(Object.freeze({ absent: true }));
201
+ }));
202
+ }
203
+ /** Hold cold write ownership across read/compare/append; use live owners directly. */
204
+ async withSession(sessionId, write, operation) {
205
+ if (this.ctx.sessions.get(sessionId) === undefined
206
+ && await this.ctx.sessionPersistence.stat(sessionId) === undefined
207
+ && this.ctx.sessions.get(sessionId) === undefined) {
208
+ return rejected({ code: 'session-not-found', sessionId });
209
+ }
210
+ const live = this.ctx.sessions.get(sessionId);
211
+ if (live !== undefined) {
212
+ // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
213
+ return operation(live.snapshotEvents(), async (event) => {
214
+ if (event !== undefined) {
215
+ live.append(event.type, event.data);
216
+ }
217
+ // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
218
+ const last = live.snapshotEvents().at(-1);
219
+ if (!(await this.ctx.sessions.flush(live))) {
220
+ throw new Error(`message-feedback: no durability listener participated for live session '${sessionId}'`);
221
+ }
222
+ // Listener participation alone does not prove this Session has a persistence writer.
223
+ const handle = await this.ctx.sessionPersistence.open(sessionId, 'read');
224
+ try {
225
+ const { events: stored } = await handle.read(last?.seq ?? 0, 1);
226
+ if (!isDeepStrictEqual([handle.header.id, handle.header.createdAt, handle.header.cwd], [live.header.id, live.header.createdAt, live.header.cwd])
227
+ || (last !== undefined && !isDeepStrictEqual(stored[0], last))) {
228
+ throw new Error(`message-feedback: feedback prefix is not durable for live session '${sessionId}'`);
229
+ }
230
+ }
231
+ finally {
232
+ await handle.close();
233
+ }
234
+ });
235
+ }
236
+ const handle = await this.ctx.sessionPersistence.open(sessionId, write ? 'write' : 'read');
237
+ try {
238
+ const { events } = await handle.read();
239
+ return await operation(events, async (event) => {
240
+ const entry = event === undefined ? undefined
241
+ : { ...event, seq: SessionSeq(events.length), time: Date.now() };
242
+ if (entry !== undefined)
243
+ await handle.append([entry]);
244
+ await handle.flush();
245
+ if (entry !== undefined) {
246
+ try {
247
+ await this.ctx.parallel('feedback/committed', {
248
+ meta: handle.header,
249
+ inheritedEventCount: handle.inheritedEventCount,
250
+ events: [...events, entry],
251
+ });
252
+ }
253
+ catch (error) {
254
+ this.ctx.logger.warn('message-feedback: committed feedback observer failed', error);
255
+ }
256
+ }
257
+ });
258
+ }
259
+ finally {
260
+ await handle.close();
261
+ }
262
+ }
263
+ resolveNote(note) {
264
+ if (note === undefined)
265
+ return success(undefined);
266
+ if (note.trim().length === 0)
267
+ return rejected({ code: 'note-blank' });
268
+ const actualBytes = Buffer.byteLength(note, 'utf8');
269
+ if (actualBytes > this.maxNoteBytes) {
270
+ return rejected({ code: 'note-too-large', maxBytes: this.maxNoteBytes, actualBytes });
271
+ }
272
+ return success(note);
273
+ }
274
+ versionConflict(current) {
275
+ return { code: 'version-conflict', current: current === null ? null : snapshotItem(current) };
276
+ }
277
+ /** Serialize complete operations and drain their handles before disposal. */
278
+ enqueue(sessionId, operation) {
279
+ if (!this.mutationAdmissionOpen)
280
+ return Promise.reject(new Error('message-feedback: service is disposing'));
281
+ const previous = this.operationTails.get(sessionId) ?? Promise.resolve();
282
+ const result = previous.then(operation);
283
+ const tail = result.then(() => undefined, () => undefined);
284
+ this.operationTails.set(sessionId, tail);
285
+ return result.finally(() => {
286
+ if (this.operationTails.get(sessionId) === tail)
287
+ this.operationTails.delete(sessionId);
288
+ });
289
+ }
290
+ };
291
+ })();
292
+ export { MessageFeedbackService };
293
+ export default MessageFeedbackService;