@praxisui/dynamic-form 9.0.0-beta.9 → 9.0.0-beta.90

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.
@@ -1,21 +1,22 @@
1
- import { firstValueFrom } from 'rxjs';
1
+ import { Observable } from 'rxjs';
2
+ import { withAuthoringScopePolicy } from '@praxisui/ai';
2
3
 
3
4
  class DynamicFormAgenticAuthoringTurnFlow {
4
5
  adapter;
5
- aiApi;
6
+ turnClient;
6
7
  mode = 'agentic-authoring';
7
- constructor(adapter, aiApi) {
8
+ constructor(adapter, turnClient) {
8
9
  this.adapter = adapter;
9
- this.aiApi = aiApi;
10
+ this.turnClient = turnClient;
10
11
  }
11
- async submit(request) {
12
+ submit(request) {
12
13
  const prompt = (request.prompt ?? '').trim();
13
14
  if (!prompt) {
14
- return {
15
+ return Promise.resolve({
15
16
  state: 'listening',
16
17
  phase: 'capture',
17
18
  statusText: '',
18
- };
19
+ });
19
20
  }
20
21
  const componentId = this.adapter.componentId || request.componentId || 'praxis-dynamic-form';
21
22
  const componentType = this.adapter.componentType || request.componentType || 'form';
@@ -23,25 +24,207 @@ class DynamicFormAgenticAuthoringTurnFlow {
23
24
  const runtimeState = this.optionalJsonObject(this.adapter.getRuntimeState?.());
24
25
  const contextHints = this.mergeJsonObjects(this.optionalJsonObject(this.adapter.getAuthoringContext?.()), this.optionalJsonObject(request.action?.contextHints));
25
26
  if (this.shouldRestrictToInlineHelp(contextHints)) {
26
- return this.toInlineHelpOnlyResult(prompt, request, contextHints);
27
+ return Promise.resolve(this.toInlineHelpOnlyResult(prompt, request, contextHints));
27
28
  }
28
- const response = await firstValueFrom(this.aiApi.getPatch({
29
- componentId,
30
- componentType,
31
- userPrompt: prompt,
32
- sessionId: request.sessionId,
33
- clientTurnId: request.clientTurnId,
34
- messages: this.toChatMessages(request.messages, prompt),
35
- currentState,
36
- currentStateDigest: this.buildCurrentStateDigest(currentState, runtimeState),
37
- uiContextRef: {
29
+ const buildRequest = async () => {
30
+ await this.adapter.prepareAuthoringContext?.();
31
+ const preparedRuntimeState = this.optionalJsonObject(this.adapter.getRuntimeState?.()) ?? runtimeState;
32
+ const preparedContextHints = this.mergeJsonObjects(this.optionalJsonObject(this.adapter.getAuthoringContext?.()), this.optionalJsonObject(request.action?.contextHints));
33
+ const dataProfile = this.optionalJsonObject(this.adapter.getDataProfile?.());
34
+ const schemaFields = this.adapter.getSchemaFields?.()
35
+ ?.map((field) => this.toAiJsonObject(field))
36
+ .filter((field) => Object.keys(field).length > 0);
37
+ const patchRequest = withAuthoringScopePolicy({
38
+ componentId,
39
+ componentType,
40
+ userPrompt: prompt,
41
+ sessionId: request.sessionId,
42
+ clientTurnId: request.clientTurnId,
43
+ messages: this.toChatMessages(request.messages, prompt),
44
+ currentState,
45
+ currentStateDigest: this.buildCurrentStateDigest(currentState, preparedRuntimeState),
46
+ uiContextRef: {
47
+ componentId,
48
+ componentType,
49
+ },
50
+ ...(dataProfile ? { dataProfile } : {}),
51
+ ...(preparedRuntimeState ? { runtimeState: preparedRuntimeState } : {}),
52
+ ...(schemaFields?.length ? { schemaFields } : {}),
53
+ ...(preparedContextHints ? { contextHints: preparedContextHints } : {}),
54
+ }, {
38
55
  componentId,
39
56
  componentType,
40
- },
41
- ...(runtimeState ? { runtimeState } : {}),
42
- ...(contextHints ? { contextHints } : {}),
57
+ componentLabel: this.adapter.componentName || 'formulário',
58
+ });
59
+ return {
60
+ ...patchRequest,
61
+ targetApp: 'praxis-ui-angular',
62
+ targetComponentId: componentId,
63
+ currentPage: currentState,
64
+ conversationMessages: this.toConversationMessages(request.messages),
65
+ pendingClarification: this.toPendingClarification(request),
66
+ attachmentSummaries: this.toAttachmentSummaries(request),
67
+ activeSemanticDecision: this.optionalJsonObject(request.activeSemanticDecision ?? request.action?.activeSemanticDecision),
68
+ contextHints: patchRequest.contextHints ?? null,
69
+ };
70
+ };
71
+ return this.submitViaAgenticStream(request, buildRequest);
72
+ }
73
+ submitViaAgenticStream(request, buildRequest) {
74
+ return new Observable((subscriber) => {
75
+ let closed = false;
76
+ let subscription = null;
77
+ const close = () => {
78
+ closed = true;
79
+ subscription?.unsubscribe();
80
+ subscription = null;
81
+ };
82
+ void buildRequest()
83
+ .then((turnRequest) => {
84
+ if (closed)
85
+ return;
86
+ subscription = this.turnClient.streamEvents(turnRequest, {
87
+ initialStatusText: 'Preparando o contexto seguro do formulário.',
88
+ resultTimeoutMs: 90_000,
89
+ streamTimeoutMs: 90_000,
90
+ }).subscribe({
91
+ next: (event) => {
92
+ if (closed)
93
+ return;
94
+ const result = this.toAgenticStreamTurnResult(event, request);
95
+ subscriber.next(result);
96
+ if (result.state !== 'processing') {
97
+ subscriber.complete();
98
+ close();
99
+ }
100
+ },
101
+ error: (error) => {
102
+ if (closed)
103
+ return;
104
+ subscriber.next(this.toAssistantErrorResult(error));
105
+ subscriber.complete();
106
+ close();
107
+ },
108
+ });
109
+ })
110
+ .catch((error) => {
111
+ if (closed)
112
+ return;
113
+ subscriber.next(this.toAssistantErrorResult(error));
114
+ subscriber.complete();
115
+ close();
116
+ });
117
+ return () => close();
118
+ });
119
+ }
120
+ toAgenticStreamTurnResult(event, request) {
121
+ if (event.kind === 'stream-started') {
122
+ return {
123
+ state: 'processing',
124
+ phase: 'contextualize',
125
+ statusText: 'Analisando o formulário e suas capacidades.',
126
+ sessionId: event.start.threadId,
127
+ clientTurnId: request.clientTurnId ?? event.start.turnId,
128
+ observationId: event.start.observationId ?? null,
129
+ canApply: false,
130
+ };
131
+ }
132
+ if (event.kind === 'stream-lifecycle') {
133
+ return {
134
+ state: 'processing',
135
+ phase: 'contextualize',
136
+ statusText: event.statusText,
137
+ sessionId: event.start.threadId,
138
+ clientTurnId: request.clientTurnId ?? event.start.turnId,
139
+ observationId: event.start.observationId ?? null,
140
+ canApply: false,
141
+ diagnostics: event.diagnostics
142
+ ? { streamLifecycle: { phase: event.phase, ...event.diagnostics } }
143
+ : undefined,
144
+ };
145
+ }
146
+ if (event.event.type === 'result') {
147
+ const payload = this.toRecord(event.event.payload) ?? {};
148
+ const rawResponse = this.toRecord(payload['response']) ?? payload;
149
+ const response = this.normalizeAgenticResponse(rawResponse);
150
+ return {
151
+ ...this.toTurnResult(this.compileAdapterResponse(response), request),
152
+ sessionId: event.event.threadId || request.sessionId,
153
+ clientTurnId: request.clientTurnId ?? event.event.turnId,
154
+ };
155
+ }
156
+ return this.turnClient.toTurnResult(event.event, request.clientTurnId);
157
+ }
158
+ normalizeAgenticResponse(response) {
159
+ const type = response['type'];
160
+ const normalizedType = type === 'patch'
161
+ || type === 'clarification'
162
+ || type === 'error'
163
+ || type === 'info'
164
+ ? type
165
+ : this.toRecord(response['patch']) || this.toRecord(response['compiledPatch'])
166
+ ? 'patch'
167
+ : 'info';
168
+ const patch = this.toRecord(response['patch']) ?? this.toRecord(response['compiledPatch']) ?? undefined;
169
+ const message = typeof response['message'] === 'string'
170
+ ? response['message']
171
+ : typeof response['assistantMessage'] === 'string'
172
+ ? response['assistantMessage']
173
+ : undefined;
174
+ return {
175
+ ...response,
176
+ type: normalizedType,
177
+ ...(patch ? { patch } : {}),
178
+ ...(message ? { message } : {}),
179
+ };
180
+ }
181
+ toConversationMessages(messages) {
182
+ return (messages ?? [])
183
+ .filter((message) => message.role === 'user' || message.role === 'assistant' || message.role === 'system')
184
+ .map((message) => ({
185
+ id: message.id,
186
+ role: message.role,
187
+ text: message.text,
188
+ }))
189
+ .filter((message) => message.text.trim().length > 0);
190
+ }
191
+ toPendingClarification(request) {
192
+ const pending = request.pendingClarification;
193
+ if (!pending?.sourcePrompt?.trim())
194
+ return null;
195
+ return {
196
+ sourcePrompt: pending.sourcePrompt,
197
+ questions: pending.questions.map((question) => question.label).filter(Boolean),
198
+ assistantMessage: pending.assistantMessage ?? null,
199
+ clientTurnId: pending.clientTurnId ?? null,
200
+ diagnostics: this.optionalJsonObject(pending.diagnostics) ?? null,
201
+ };
202
+ }
203
+ toAttachmentSummaries(request) {
204
+ return (request.attachments ?? []).map((attachment) => ({
205
+ id: attachment.id,
206
+ name: attachment.name,
207
+ kind: attachment.kind,
208
+ mimeType: attachment.mimeType ?? null,
209
+ sizeBytes: attachment.sizeBytes ?? null,
210
+ source: attachment.source ?? null,
211
+ hasPreview: !!attachment.previewUrl,
43
212
  }));
44
- return this.toTurnResult(this.compileAdapterResponse(response), request);
213
+ }
214
+ toAssistantErrorResult(error) {
215
+ const message = error instanceof Error
216
+ ? error.message
217
+ : typeof error === 'string' && error.trim()
218
+ ? error
219
+ : 'Não foi possível concluir o pedido do formulário.';
220
+ return {
221
+ state: 'error',
222
+ phase: 'capture',
223
+ assistantMessage: `Não consegui concluir este pedido. ${message}`,
224
+ errorText: message,
225
+ canApply: false,
226
+ pendingPatch: null,
227
+ };
45
228
  }
46
229
  async apply(request) {
47
230
  const contextHints = this.optionalJsonObject(this.adapter.getAuthoringContext?.());