@acorex-platform/module-ai-management-client 0.0.20

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.
Files changed (21) hide show
  1. package/fesm2022/acorex-platform-module-ai-management-client-agent-registry-tool-configurator-widget-column.component-BHdDG8z0.mjs +44 -0
  2. package/fesm2022/acorex-platform-module-ai-management-client-agent-registry-tool-configurator-widget-column.component-BHdDG8z0.mjs.map +1 -0
  3. package/fesm2022/acorex-platform-module-ai-management-client-agent-registry-tool-configurator-widget-edit.component-CMsc3P9O.mjs +259 -0
  4. package/fesm2022/acorex-platform-module-ai-management-client-agent-registry-tool-configurator-widget-edit.component-CMsc3P9O.mjs.map +1 -0
  5. package/fesm2022/acorex-platform-module-ai-management-client-assist-delegated-agent-configurator-widget-column.component-CWUhBvpf.mjs +62 -0
  6. package/fesm2022/acorex-platform-module-ai-management-client-assist-delegated-agent-configurator-widget-column.component-CWUhBvpf.mjs.map +1 -0
  7. package/fesm2022/acorex-platform-module-ai-management-client-assist-delegated-agent-configurator-widget-edit.component-Dmi8vzfr.mjs +293 -0
  8. package/fesm2022/acorex-platform-module-ai-management-client-assist-delegated-agent-configurator-widget-edit.component-Dmi8vzfr.mjs.map +1 -0
  9. package/fesm2022/acorex-platform-module-ai-management-client-contracts.mjs +1038 -0
  10. package/fesm2022/acorex-platform-module-ai-management-client-contracts.mjs.map +1 -0
  11. package/fesm2022/acorex-platform-module-ai-management-client-list-ai-command-registry-catalog.query-DHfiKVa2.mjs +106 -0
  12. package/fesm2022/acorex-platform-module-ai-management-client-list-ai-command-registry-catalog.query-DHfiKVa2.mjs.map +1 -0
  13. package/fesm2022/acorex-platform-module-ai-management-client-list-ai-query-registry-catalog.query-BX0uU1YX.mjs +107 -0
  14. package/fesm2022/acorex-platform-module-ai-management-client-list-ai-query-registry-catalog.query-BX0uU1YX.mjs.map +1 -0
  15. package/fesm2022/acorex-platform-module-ai-management-client-list-output-contract-transcript-segments.query-BQXySOH_.mjs +54 -0
  16. package/fesm2022/acorex-platform-module-ai-management-client-list-output-contract-transcript-segments.query-BQXySOH_.mjs.map +1 -0
  17. package/fesm2022/acorex-platform-module-ai-management-client.mjs +3642 -0
  18. package/fesm2022/acorex-platform-module-ai-management-client.mjs.map +1 -0
  19. package/package.json +28 -0
  20. package/types/acorex-platform-module-ai-management-client-contracts.d.ts +896 -0
  21. package/types/acorex-platform-module-ai-management-client.d.ts +797 -0
@@ -0,0 +1,1038 @@
1
+ import { axpContextDefinitionIsAiPrompt, resolveMultiLanguageString } from '@acorex-platform/framework-shared/core';
2
+
3
+ //#region ---- Feature keys ----
4
+ /**
5
+ * Edition / feature flags for AI Management.
6
+ * `ManageCatalog` is Platform Console only (Intelligence config menu).
7
+ */
8
+ const AXPAiManagementFeatureKeys = {
9
+ /** Configuration → Intelligence (agents, assists, models, endpoints, rules). */
10
+ ManageCatalog: 'AiManagement:Feature:ManageCatalog',
11
+ };
12
+ //#endregion
13
+
14
+ //#region ---- Menu Keys ----
15
+ /**
16
+ * AI Management menu keys.
17
+ * Pattern: AiManagement:Menu:{Path}
18
+ */
19
+ const AXPAiManagementMenuKeys = {
20
+ /** Configuration > AI Management (models, assists) */
21
+ AiManagementConfig: 'Common:Menu:Configuration:AiManagement',
22
+ /** OpenAI-compatible HTTP endpoints (base URL + API key). */
23
+ OpenAiEndpoints: 'AiManagement:Menu:OpenAiEndpoints',
24
+ /** List of AI models (from providers). */
25
+ Models: 'AiManagement:Menu:Models',
26
+ /** List of Assists. */
27
+ Assists: 'AiManagement:Menu:Assists',
28
+ /** Delegated specialist agents (supervisor routing). */
29
+ Agents: 'AiManagement:Menu:Agents',
30
+ /** Reusable system-prompt rules (Markdown fragments). */
31
+ Rules: 'AiManagement:Menu:Rules',
32
+ };
33
+ //#endregion
34
+
35
+ /**
36
+ * Administration capabilities used by this module.
37
+ * Domain capability keys for this module. Root groups live in `AXPCommonPermissionGroupKeys` (common contracts).
38
+ */
39
+ const AXPAdministrationPermissionKeys = {
40
+ Access: 'Administration:Permission:Access',
41
+ MaintainUsersAndRoles: 'Administration:Permission:MaintainUsersAndRoles',
42
+ ManageSessions: 'Administration:Permission:ManageSessions',
43
+ MaintainPolicies: 'Administration:Permission:MaintainPolicies',
44
+ ViewIntegrations: 'Administration:Permission:ViewIntegrations',
45
+ MaintainConnections: 'Administration:Permission:MaintainConnections',
46
+ MaintainWorkflows: 'Administration:Permission:MaintainWorkflows',
47
+ ManageWorkflowActions: 'Administration:Permission:ManageWorkflowActions',
48
+ ViewRules: 'Administration:Permission:ViewRules',
49
+ MaintainRules: 'Administration:Permission:MaintainRules',
50
+ ManageRuleActions: 'Administration:Permission:ManageRuleActions',
51
+ MaintainAi: 'Administration:Permission:MaintainAi',
52
+ UseAiAssist: 'Administration:Permission:UseAiAssist',
53
+ MaintainDashboards: 'Administration:Permission:MaintainDashboards',
54
+ ViewJobs: 'Administration:Permission:ViewJobs',
55
+ ManageJobActions: 'Administration:Permission:ManageJobActions',
56
+ ViewObservability: 'Administration:Permission:ViewObservability',
57
+ MaintainObservability: 'Administration:Permission:MaintainObservability',
58
+ };
59
+ /**
60
+ * Dynamic assist access permissions (`Assist.{name}.Use`) as children of UseAiAssist.
61
+ * Parent Assist.Use maps to {@link AXPAdministrationPermissionKeys.UseAiAssist}.
62
+ */
63
+ const AXMAiAssistPermissionKeys = {
64
+ Use: AXPAdministrationPermissionKeys.UseAiAssist,
65
+ useForAssist: (assistName) => `AiManagement:Permission:Assist.${assistName}.Use`,
66
+ };
67
+ /**
68
+ * @deprecated Prefer {@link AXPAdministrationPermissionKeys}.
69
+ * Legacy nested shape kept so existing imports compile during migration.
70
+ */
71
+ const AXMPermissionsKeys = {
72
+ AiManagement: {
73
+ Management: AXPAdministrationPermissionKeys.MaintainAi,
74
+ Assist: AXMAiAssistPermissionKeys,
75
+ },
76
+ };
77
+
78
+ //#region ---- Setting Keys ----
79
+ /**
80
+ * AI Management setting keys.
81
+ * Pattern: AiManagement:Setting:{Path}
82
+ */
83
+ const AXPAiManagementSettings = {
84
+ /** Assist primary key (`id`) used when no assist is explicitly selected (tenant-scoped). */
85
+ DefaultAssistId: 'AiManagement:Setting:DefaultAssistId',
86
+ /**
87
+ * System instructions prepended to every assist/agent chat system prompt in {@link AXPAiEngine}.
88
+ * Empty string means no global layer (default).
89
+ */
90
+ GlobalSystemPrompt: 'AiManagement:Setting:GlobalSystemPrompt',
91
+ Providers: {
92
+ Gemini: {
93
+ ApiKey: 'AiManagement:Setting:Providers.Gemini.ApiKey',
94
+ },
95
+ },
96
+ };
97
+ //#endregion
98
+
99
+ //#region ---- Module Config ----
100
+ const config = {
101
+ i18n: 'ai-management',
102
+ module: 'AiManagement',
103
+ route: 'ai-management',
104
+ };
105
+ const RootConfig = {
106
+ config,
107
+ module: {
108
+ name: config.module,
109
+ route: config.route,
110
+ title: `@${config.i18n}:module.title`,
111
+ icon: 'fa-light fa-robot',
112
+ },
113
+ entities: {
114
+ model: {
115
+ name: 'AiModel',
116
+ fullName: `${config.module}.AiModel`,
117
+ title: '@ai-management:models.entities.model.title',
118
+ titlePlural: '@ai-management:models.entities.model.plural',
119
+ icon: 'fa-light fa-microchip',
120
+ },
121
+ assist: {
122
+ name: 'Assist',
123
+ fullName: `${config.module}.Assist`,
124
+ title: '@ai-management:assists.entities.assist.title',
125
+ titlePlural: '@ai-management:assists.entities.assist.plural',
126
+ icon: 'fa-light fa-user-robot',
127
+ },
128
+ agent: {
129
+ name: 'AiAgent',
130
+ fullName: `${config.module}.AiAgent`,
131
+ title: '@ai-management:agents.entities.agent.title',
132
+ titlePlural: '@ai-management:agents.entities.agent.plural',
133
+ icon: 'fa-light fa-people-group',
134
+ },
135
+ openAiEndpoint: {
136
+ name: 'OpenAiEndpoint',
137
+ fullName: `${config.module}.OpenAiEndpoint`,
138
+ title: '@ai-management:open-ai-endpoints.entities.endpoint.title',
139
+ titlePlural: '@ai-management:open-ai-endpoints.entities.endpoint.plural',
140
+ icon: 'fa-light fa-plug',
141
+ },
142
+ rule: {
143
+ name: 'AiRule',
144
+ fullName: `${config.module}.AiRule`,
145
+ title: '@ai-management:rules.entities.rule.title',
146
+ titlePlural: '@ai-management:rules.entities.rule.plural',
147
+ icon: 'fa-light fa-list-check',
148
+ },
149
+ mcpServer: {
150
+ name: 'McpServer',
151
+ fullName: `${config.module}.McpServer`,
152
+ title: '@ai-management:mcp-servers.entities.mcp-server.title',
153
+ titlePlural: '@ai-management:mcp-servers.entities.mcp-server.plural',
154
+ icon: 'fa-light fa-plug-circle-bolt',
155
+ },
156
+ },
157
+ };
158
+ //#endregion
159
+
160
+ //#endregion
161
+
162
+ //#region ---- Platform runtime time & notes ----
163
+ const AXM_AI_PLATFORM_RUNTIME_CONTEXT_DEFINITIONS = [
164
+ {
165
+ name: 'currentInstant',
166
+ title: 'Current instant (UTC)',
167
+ description: 'Current moment as ISO 8601 UTC, built when platform runtime context is assembled before an AI engine run.',
168
+ order: 80,
169
+ capabilities: ['ai'],
170
+ },
171
+ {
172
+ name: 'currentLocalDateTime',
173
+ title: 'Current local date and time',
174
+ description: 'Current date and time formatted in the user IANA time zone for natural-language interpretation in system prompts.',
175
+ order: 90,
176
+ capabilities: ['ai'],
177
+ },
178
+ {
179
+ name: 'notes',
180
+ title: 'Runtime notes',
181
+ description: 'Optional free-text or structured notes merged into platform runtime context for a specific AI run (caller-supplied).',
182
+ order: 100,
183
+ capabilities: ['ai'],
184
+ },
185
+ ];
186
+ //#endregion
187
+
188
+ //#region ---- Imports ----
189
+ //#endregion
190
+
191
+ //#region ----- Imports -----
192
+ const AXP_AI_SDK_TOOL_CONTEXT_JSON_SCHEMA = {
193
+ type: 'object',
194
+ properties: {
195
+ runId: { type: 'string' },
196
+ assistId: { type: 'string' },
197
+ agentId: { type: 'string' },
198
+ chatTransport: { type: 'string' },
199
+ modelEntityId: { type: 'string' },
200
+ },
201
+ additionalProperties: false,
202
+ };
203
+ function stringifyRuntimeValue(value) {
204
+ if (value == null) {
205
+ return undefined;
206
+ }
207
+ if (typeof value === 'string') {
208
+ const trimmed = value.trim();
209
+ return trimmed.length > 0 ? trimmed : undefined;
210
+ }
211
+ if (typeof value === 'number' || typeof value === 'boolean') {
212
+ return String(value);
213
+ }
214
+ try {
215
+ const json = JSON.stringify(value);
216
+ return json && json !== '{}' && json !== '[]' ? json : undefined;
217
+ }
218
+ catch {
219
+ return undefined;
220
+ }
221
+ }
222
+ function compactStringRecord(input) {
223
+ const out = {};
224
+ for (const [key, value] of Object.entries(input)) {
225
+ const trimmed = value?.trim();
226
+ if (trimmed) {
227
+ out[key] = trimmed;
228
+ }
229
+ }
230
+ return Object.keys(out).length > 0 ? out : undefined;
231
+ }
232
+ /**
233
+ * Turns registered AI-capable context definitions + live values into the
234
+ * `## Platform runtime` system-prompt block. Identity ids are never assembled into values.
235
+ */
236
+ function formatAxpAiPlatformRuntimePrompt(platformRuntimeContext, definitions) {
237
+ if (!platformRuntimeContext || !definitions?.length) {
238
+ return '';
239
+ }
240
+ const lines = definitions
241
+ .filter(axpContextDefinitionIsAiPrompt)
242
+ .slice()
243
+ .sort((a, b) => (a.order ?? 0) - (b.order ?? 0))
244
+ .map((field) => {
245
+ const value = stringifyRuntimeValue(platformRuntimeContext[field.name]);
246
+ return value ? `- ${field.title}: ${value}` : null;
247
+ })
248
+ .filter((line) => line != null);
249
+ if (lines.length === 0) {
250
+ return '';
251
+ }
252
+ return ['## Platform runtime', ...lines].join('\n');
253
+ }
254
+ function buildAxpAiSdkChatContextBundle(input) {
255
+ const runtimeContext = compactStringRecord({
256
+ runId: input.runId,
257
+ assistId: input.assistId,
258
+ agentId: input.agentId,
259
+ agentName: input.agentName,
260
+ chatTransport: input.chatTransport,
261
+ modelEntityId: input.modelEntityId,
262
+ demisSessionUuid: input.demisSessionUuid,
263
+ });
264
+ const toolsContext = compactStringRecord({
265
+ runId: input.runId,
266
+ assistId: input.assistId,
267
+ agentId: input.agentId,
268
+ chatTransport: input.chatTransport,
269
+ modelEntityId: input.modelEntityId,
270
+ });
271
+ return {
272
+ ...(runtimeContext ? { runtimeContext } : {}),
273
+ ...(toolsContext ? { toolsContext } : {}),
274
+ promptAddendum: formatAxpAiPlatformRuntimePrompt(input.platformRuntimeContext, input.contextDefinitions),
275
+ };
276
+ }
277
+ function attachAxpAiSdkChatContext(options, bundle) {
278
+ const hasTools = Boolean(options.tools && options.tools.length > 0);
279
+ return {
280
+ ...options,
281
+ ...(bundle.runtimeContext ? { runtimeContext: bundle.runtimeContext } : {}),
282
+ ...(hasTools && bundle.toolsContext ? { toolsContext: bundle.toolsContext } : {}),
283
+ };
284
+ }
285
+ function formatAxpAiPlatformRuntimeLocalDateTime(now, ianaTimeZone) {
286
+ const tz = ianaTimeZone?.trim() || 'UTC';
287
+ try {
288
+ return (now.toLocaleString('en-US', {
289
+ timeZone: tz,
290
+ dateStyle: 'full',
291
+ timeStyle: 'long',
292
+ }) + ` (${tz})`);
293
+ }
294
+ catch {
295
+ return `${now.toISOString()} (UTC)`;
296
+ }
297
+ }
298
+ function assembleAxpAiPlatformRuntimeContext(sources) {
299
+ const now = sources.now ?? new Date();
300
+ const ctx = {};
301
+ const set = (key, value) => {
302
+ if (value == null) {
303
+ return;
304
+ }
305
+ const asString = typeof value === 'string' ? value.trim() : String(value).trim();
306
+ if (asString.length > 0) {
307
+ ctx[key] = typeof value === 'string' ? asString : value;
308
+ }
309
+ };
310
+ set('userDisplayName', sources.userDisplayName);
311
+ set('tenantTitle', sources.tenantTitle);
312
+ set('applicationTitle', sources.applicationTitle);
313
+ set('locale', sources.locale);
314
+ set('calendarSystem', sources.calendarSystem);
315
+ set('timeZone', sources.timeZone);
316
+ set('country', sources.country);
317
+ set('notes', sources.notes);
318
+ set('currentInstant', now.toISOString());
319
+ set('currentLocalDateTime', formatAxpAiPlatformRuntimeLocalDateTime(now, sources.timeZone));
320
+ return ctx;
321
+ }
322
+ //#endregion
323
+
324
+ //#region ---- Imports ----
325
+ /** Default structured retry count when `structuredRetries` is omitted on structured kinds. */
326
+ const AXPAI_AGENT_OUTPUT_CONTRACT_DEFAULT_STRUCTURED_RETRIES = 2;
327
+ //#endregion
328
+ //#region ---- Schema / response format parsers ----
329
+ function isJsonSchemaLike$1(value) {
330
+ return value != null && typeof value === 'object' && !Array.isArray(value);
331
+ }
332
+ function parseJsonSchemaLike(raw) {
333
+ if (!isJsonSchemaLike$1(raw)) {
334
+ return undefined;
335
+ }
336
+ return raw;
337
+ }
338
+ function parseResponseFormat(raw) {
339
+ if (raw == null || typeof raw !== 'object' || Array.isArray(raw)) {
340
+ return undefined;
341
+ }
342
+ const o = raw;
343
+ const t = o['type'];
344
+ if (t === 'text') {
345
+ return { type: 'text' };
346
+ }
347
+ if (t === 'json_object') {
348
+ return { type: 'json_object' };
349
+ }
350
+ if (t === 'json_schema' && isJsonSchemaLike$1(o['schema'])) {
351
+ const name = typeof o['name'] === 'string' ? o['name'].trim() : undefined;
352
+ const strict = o['strict'] === true;
353
+ return {
354
+ type: 'json_schema',
355
+ schema: o['schema'],
356
+ ...(name && name.length > 0 ? { name } : {}),
357
+ ...(strict ? { strict: true } : {}),
358
+ };
359
+ }
360
+ return undefined;
361
+ }
362
+ //#endregion
363
+ //#region ---- Resolve helpers ----
364
+ const STRUCTURED_OUTPUT_KINDS$1 = new Set(['object', 'array']);
365
+ function isOutputKind(value) {
366
+ return value === 'string' || value === 'object' || value === 'array';
367
+ }
368
+ function isTranscriptSegment(value) {
369
+ return value === 'text' || value === 'node' || value === 'followUp' || value === 'file';
370
+ }
371
+ /** Resolved transcript mapping for an object contract (defaults to `text`). */
372
+ function resolveOutputTranscriptSegment(contract) {
373
+ if (contract.kind !== 'object') {
374
+ return 'text';
375
+ }
376
+ return contract.transcriptSegment ?? 'text';
377
+ }
378
+ //#endregion
379
+ //#region ---- Parser ----
380
+ /**
381
+ * Normalizes persisted `outputContract` (object or JSON string from entity forms).
382
+ * Returns `null` when absent or invalid (engine treats as implicit `string`).
383
+ */
384
+ function parseAgentOutputContract(raw) {
385
+ let value = raw;
386
+ if (typeof raw === 'string') {
387
+ const t = raw.trim();
388
+ if (!t.length) {
389
+ return null;
390
+ }
391
+ try {
392
+ value = JSON.parse(t);
393
+ }
394
+ catch {
395
+ return null;
396
+ }
397
+ }
398
+ if (value == null || typeof value !== 'object' || Array.isArray(value)) {
399
+ return null;
400
+ }
401
+ const o = value;
402
+ const kind = o['kind'];
403
+ if (!isOutputKind(kind)) {
404
+ return null;
405
+ }
406
+ const instruction = typeof o['instruction'] === 'string' ? o['instruction'].trim() : undefined;
407
+ const schemaSummary = typeof o['schemaSummary'] === 'string' ? o['schemaSummary'].trim() : undefined;
408
+ const validationCommandName = typeof o['validationCommandName'] === 'string' ? o['validationCommandName'].trim() : undefined;
409
+ const schema = parseJsonSchemaLike(o['schema']);
410
+ const schemaName = typeof o['schemaName'] === 'string' ? o['schemaName'].trim() : undefined;
411
+ const schemaStrict = o['schemaStrict'] === true;
412
+ const providerResponseFormat = parseResponseFormat(o['providerResponseFormat']);
413
+ const transcriptSegment = kind === 'object' && isTranscriptSegment(o['transcriptSegment']) ? o['transcriptSegment'] : undefined;
414
+ let structuredRetries;
415
+ if (typeof o['structuredRetries'] === 'number' && !Number.isNaN(o['structuredRetries'])) {
416
+ structuredRetries = Math.max(0, Math.min(10, Math.floor(o['structuredRetries'])));
417
+ }
418
+ return {
419
+ kind,
420
+ ...(transcriptSegment ? { transcriptSegment } : {}),
421
+ ...(instruction && instruction.length > 0 ? { instruction } : {}),
422
+ ...(schemaSummary && schemaSummary.length > 0 ? { schemaSummary } : {}),
423
+ ...(schema ? { schema } : {}),
424
+ ...(schemaName && schemaName.length > 0 ? { schemaName } : {}),
425
+ ...(schemaStrict ? { schemaStrict: true } : {}),
426
+ ...(validationCommandName && validationCommandName.length > 0 ? { validationCommandName } : {}),
427
+ ...(structuredRetries !== undefined ? { structuredRetries } : {}),
428
+ ...(providerResponseFormat ? { providerResponseFormat } : {}),
429
+ };
430
+ }
431
+ /** Resolved contract for engine (never null; defaults to string). */
432
+ function resolveAgentOutputContract(raw) {
433
+ const parsed = parseAgentOutputContract(raw);
434
+ if (parsed) {
435
+ return parsed;
436
+ }
437
+ return { kind: 'string' };
438
+ }
439
+ function axpAiAgentOutputContractUsesStructuredFinalize(contract) {
440
+ return STRUCTURED_OUTPUT_KINDS$1.has(contract.kind);
441
+ }
442
+ /** Structured kinds omit the string role baseline (Markdown prose hint) in the mock engine. */
443
+ function axpAiAgentOutputContractOmitsRoleBaseline(contract) {
444
+ return axpAiAgentOutputContractUsesStructuredFinalize(contract);
445
+ }
446
+ function axpAiAgentOutputContractStructuredRetryCap(contract) {
447
+ if (!axpAiAgentOutputContractUsesStructuredFinalize(contract)) {
448
+ return 0;
449
+ }
450
+ if (typeof contract.structuredRetries === 'number') {
451
+ return Math.max(0, Math.min(10, Math.floor(contract.structuredRetries)));
452
+ }
453
+ return AXPAI_AGENT_OUTPUT_CONTRACT_DEFAULT_STRUCTURED_RETRIES;
454
+ }
455
+ //#endregion
456
+
457
+ //#region ---- Imports ----
458
+ function isSegmentPresetId(value) {
459
+ return value === 'text' || value === 'node' || value === 'followUp' || value === 'file';
460
+ }
461
+ function contractFromSegmentPresetId(id) {
462
+ if (id === 'text' || id === 'file') {
463
+ return { kind: 'string' };
464
+ }
465
+ if (id === 'node') {
466
+ return { kind: 'object', transcriptSegment: 'node' };
467
+ }
468
+ if (id === 'followUp') {
469
+ return { kind: 'object', transcriptSegment: 'followUp' };
470
+ }
471
+ return null;
472
+ }
473
+ function contractFromUnknown(raw) {
474
+ if (raw == null) {
475
+ return null;
476
+ }
477
+ if (typeof raw === 'string') {
478
+ const id = raw.trim();
479
+ if (!id.length) {
480
+ return null;
481
+ }
482
+ const preset = isSegmentPresetId(id) ? contractFromSegmentPresetId(id) : null;
483
+ if (preset) {
484
+ return preset;
485
+ }
486
+ return parseAgentOutputContract(raw);
487
+ }
488
+ if (typeof raw === 'object' && !Array.isArray(raw) && 'kind' in raw) {
489
+ const parsed = parseAgentOutputContract(raw);
490
+ if (parsed) {
491
+ return parsed;
492
+ }
493
+ }
494
+ return parseAgentOutputContract(raw);
495
+ }
496
+ /**
497
+ * Resolves the effective output contract for one engine turn.
498
+ *
499
+ * Priority: runtime > input > agent > assist > `{ kind: 'string' }`.
500
+ */
501
+ function resolveEffectiveOutputContract(params) {
502
+ const runtime = contractFromUnknown(params.runtime);
503
+ if (runtime) {
504
+ return runtime;
505
+ }
506
+ const input = contractFromUnknown(params.input);
507
+ if (input) {
508
+ return input;
509
+ }
510
+ const agent = contractFromUnknown(params.agent);
511
+ if (agent) {
512
+ return agent;
513
+ }
514
+ const assist = contractFromUnknown(params.assist);
515
+ if (assist) {
516
+ return assist;
517
+ }
518
+ return resolveAgentOutputContract(null);
519
+ }
520
+ //#endregion
521
+
522
+ //#region ---- Imports ----
523
+ //#endregion
524
+ //#region ---- AXPWidgetNode (provider JSON Schema hint) ----
525
+ /**
526
+ * JSON Schema hint for {@link AXPWidgetNode} roots returned by layout specialists.
527
+ * Intentionally permissive (`additionalProperties`) — strict validation runs via
528
+ * `AiFormbuilder:ValidateLayoutJsonForAi` when configured on the agent contract.
529
+ */
530
+ const AXP_WIDGET_NODE_JSON_SCHEMA = {
531
+ type: 'object',
532
+ required: ['type'],
533
+ additionalProperties: true,
534
+ properties: {
535
+ type: {
536
+ type: 'string',
537
+ description: 'AXPWidgetNode.type — widget registry name (e.g. block-layout, table-layout).',
538
+ },
539
+ mode: {
540
+ type: 'string',
541
+ enum: ['view', 'edit', 'designer', 'print', 'column', 'filter'],
542
+ description: 'AXPWidgetNode.mode render surface.',
543
+ },
544
+ path: { type: 'string' },
545
+ name: { type: 'string' },
546
+ visible: { description: 'boolean or AXPExpression object.' },
547
+ defaultValue: { description: 'Widget default value.' },
548
+ children: {
549
+ type: 'array',
550
+ description: 'Nested AXPWidgetNode[]',
551
+ items: {
552
+ type: 'object',
553
+ required: ['type'],
554
+ additionalProperties: true,
555
+ properties: {
556
+ type: { type: 'string' },
557
+ mode: { type: 'string' },
558
+ children: { type: 'array', items: { type: 'object', additionalProperties: true } },
559
+ options: { type: 'object', additionalProperties: true },
560
+ },
561
+ },
562
+ },
563
+ options: { type: 'object', additionalProperties: true },
564
+ triggers: { type: 'object', additionalProperties: true },
565
+ meta: { type: 'object', additionalProperties: true },
566
+ valueTransforms: { type: 'object', additionalProperties: true },
567
+ },
568
+ };
569
+ //#endregion
570
+ //#region ---- followUp envelope ----
571
+ /** JSON Schema for the followUp transcript envelope (`type` + `content` chips). */
572
+ const AXP_FOLLOW_UP_ENVELOPE_JSON_SCHEMA = {
573
+ type: 'object',
574
+ required: ['type', 'content'],
575
+ additionalProperties: false,
576
+ properties: {
577
+ type: { type: 'string', enum: ['followUp'] },
578
+ content: {
579
+ type: 'array',
580
+ minItems: 2,
581
+ maxItems: 5,
582
+ description: 'Suggestion chips: each item is either a plain string label or { text, command: { name, options? } }.',
583
+ items: {
584
+ oneOf: [
585
+ { type: 'string', minLength: 1 },
586
+ {
587
+ type: 'object',
588
+ required: ['text', 'command'],
589
+ additionalProperties: false,
590
+ properties: {
591
+ text: { type: 'string' },
592
+ command: {
593
+ type: 'object',
594
+ required: ['name'],
595
+ additionalProperties: true,
596
+ properties: {
597
+ name: { type: 'string' },
598
+ options: { type: 'object', additionalProperties: true },
599
+ },
600
+ },
601
+ },
602
+ },
603
+ ],
604
+ },
605
+ },
606
+ },
607
+ };
608
+ //#endregion
609
+ //#region ---- Resolve builtin schema ----
610
+ /** Built-in JSON Schema for known transcript segments when the contract omits `schema`. */
611
+ function resolveBuiltinSchemaForOutputContract(contract) {
612
+ if (contract.kind !== 'object') {
613
+ return undefined;
614
+ }
615
+ const segment = resolveOutputTranscriptSegment(contract);
616
+ if (segment === 'node') {
617
+ return AXP_WIDGET_NODE_JSON_SCHEMA;
618
+ }
619
+ if (segment === 'followUp') {
620
+ return AXP_FOLLOW_UP_ENVELOPE_JSON_SCHEMA;
621
+ }
622
+ return undefined;
623
+ }
624
+ //#endregion
625
+
626
+ //#region ---- Imports ----
627
+ //#endregion
628
+ //#region ---- Structured output kinds ----
629
+ const STRUCTURED_OUTPUT_KINDS = new Set(['object', 'array']);
630
+ function usesStructuredFinalize(kind) {
631
+ return STRUCTURED_OUTPUT_KINDS.has(kind);
632
+ }
633
+ function isJsonSchemaLike(value) {
634
+ return value != null && typeof value === 'object' && !Array.isArray(value);
635
+ }
636
+ //#endregion
637
+ //#region ---- Retry defaults ----
638
+ /** Default structured retry count for a contract kind when `structuredRetries` is omitted. */
639
+ function defaultRetriesForKind(kind) {
640
+ if (kind === 'string') {
641
+ return 0;
642
+ }
643
+ return AXPAI_AGENT_OUTPUT_CONTRACT_DEFAULT_STRUCTURED_RETRIES;
644
+ }
645
+ //#endregion
646
+ //#region ---- Derive provider format ----
647
+ /**
648
+ * Maps an effective output contract to a provider request hint.
649
+ * Explicit {@link AXPAiAgentOutputContract.providerResponseFormat} wins; otherwise derived from `kind` + `schema`.
650
+ */
651
+ function deriveProviderResponseFormat(contract) {
652
+ if (contract.providerResponseFormat) {
653
+ return contract.providerResponseFormat;
654
+ }
655
+ if (!usesStructuredFinalize(contract.kind)) {
656
+ return undefined;
657
+ }
658
+ const schema = (contract.schema && isJsonSchemaLike(contract.schema) ? contract.schema : undefined) ??
659
+ resolveBuiltinSchemaForOutputContract(contract);
660
+ if (schema) {
661
+ const segment = resolveOutputTranscriptSegment(contract);
662
+ const name = contract.schemaName?.trim() ||
663
+ (segment === 'node' ? 'widget_layout' : segment === 'followUp' ? 'follow_up' : 'structured_output');
664
+ return {
665
+ type: 'json_schema',
666
+ schema,
667
+ name,
668
+ strict: contract.schemaStrict === true,
669
+ };
670
+ }
671
+ return { type: 'json_object' };
672
+ }
673
+ //#endregion
674
+
675
+ //#region ---- Imports ----
676
+ /**
677
+ * Native structured output (AI SDK `output` / provider schema) must not run on tool-calling
678
+ * turns — only when tools are absent or explicitly disabled (`toolChoice: 'none'`).
679
+ */
680
+ function axpAiShouldApplyChatStructuredOutput(params) {
681
+ const format = params.responseFormat;
682
+ if (!format || format.type === 'text') {
683
+ return false;
684
+ }
685
+ if (!params.hasTools) {
686
+ return true;
687
+ }
688
+ return params.toolChoice === 'none';
689
+ }
690
+ //#endregion
691
+ //#region ---- Duplicate JSON in text ----
692
+ function stripJsonFences(raw) {
693
+ const fence = raw.match(/```(?:json)?\s*([\s\S]*?)```/i);
694
+ return fence ? fence[1].trim() : raw.trim();
695
+ }
696
+ function axpAiTryParseJsonValueFromAssistantText(text) {
697
+ const trimmed = stripJsonFences(text.trim());
698
+ if (!trimmed) {
699
+ return undefined;
700
+ }
701
+ if (!trimmed.startsWith('{') && !trimmed.startsWith('[')) {
702
+ return undefined;
703
+ }
704
+ try {
705
+ return JSON.parse(trimmed);
706
+ }
707
+ catch {
708
+ return undefined;
709
+ }
710
+ }
711
+ function isFollowUpEnvelope(value) {
712
+ if (value == null || typeof value !== 'object' || Array.isArray(value)) {
713
+ return false;
714
+ }
715
+ const o = value;
716
+ return o['type'] === 'followUp' && Array.isArray(o['content']);
717
+ }
718
+ function isLikelyWidgetRoot(value) {
719
+ if (value == null || typeof value !== 'object' || Array.isArray(value)) {
720
+ return false;
721
+ }
722
+ const t = value['type'];
723
+ return typeof t === 'string' && t.trim().length > 0 && t !== 'node' && t !== 'followUp';
724
+ }
725
+ function isNodeEnvelope(value) {
726
+ if (value == null || typeof value !== 'object' || Array.isArray(value)) {
727
+ return false;
728
+ }
729
+ const o = value;
730
+ return o['type'] === 'node' && o['content'] != null;
731
+ }
732
+ /** True when assistant `text` duplicates a structured segment already attached as `node` / `followUp`. */
733
+ function axpAiTextDuplicatesStructuredSegment(text, segment) {
734
+ const parsed = axpAiTryParseJsonValueFromAssistantText(text);
735
+ if (parsed === undefined) {
736
+ return false;
737
+ }
738
+ if (segment === 'followUp') {
739
+ return isFollowUpEnvelope(parsed);
740
+ }
741
+ return isLikelyWidgetRoot(parsed) || isNodeEnvelope(parsed);
742
+ }
743
+ //#endregion
744
+
745
+ //#region ---- Imports ----
746
+ //#endregion
747
+ //#region ---- Supervisor delegated-agent helpers ----
748
+ /** Prefix for supervisor-delegated specialist tools (`${AXPAI_SUPERVISOR_AGENT_TOOL_PREFIX}${agentId}`). */
749
+ const AXPAI_SUPERVISOR_AGENT_TOOL_PREFIX = 'agent:';
750
+ function axpAiSupervisorAgentToolName(agentCatalogId) {
751
+ return `${AXPAI_SUPERVISOR_AGENT_TOOL_PREFIX}${agentCatalogId.trim()}`;
752
+ }
753
+ function axpAiParseSupervisorAgentToolName(toolName) {
754
+ const n = toolName.trim();
755
+ if (!n.startsWith(AXPAI_SUPERVISOR_AGENT_TOOL_PREFIX)) {
756
+ return null;
757
+ }
758
+ const id = n.slice(AXPAI_SUPERVISOR_AGENT_TOOL_PREFIX.length).trim();
759
+ return id.length > 0 ? id : null;
760
+ }
761
+ //#endregion
762
+ //#region ---- Message builders ----
763
+ function axpAiChatTextMessage(role, text) {
764
+ return {
765
+ role,
766
+ responses: [{ type: 'text', content: text }],
767
+ };
768
+ }
769
+ function axpAiChatToolResultMessage(callId, content, toolName) {
770
+ const id = callId.trim();
771
+ return {
772
+ role: 'tool',
773
+ ...(toolName?.trim() ? { name: toolName.trim() } : {}),
774
+ responses: [
775
+ {
776
+ type: 'tool_result',
777
+ callId: id,
778
+ content,
779
+ },
780
+ ],
781
+ };
782
+ }
783
+ //#endregion
784
+ //#region ---- Transcript read helpers ----
785
+ function axpAiChatMessageGetText(message) {
786
+ const parts = [];
787
+ for (const r of message.responses) {
788
+ if (r.type === 'text') {
789
+ parts.push(r.content);
790
+ }
791
+ else if (r.type === 'node' || r.type === 'followUp') {
792
+ try {
793
+ parts.push(JSON.stringify({ type: r.type, content: r.content }));
794
+ }
795
+ catch {
796
+ parts.push(`[${r.type}]`);
797
+ }
798
+ }
799
+ }
800
+ return parts.join('\n\n');
801
+ }
802
+ //#endregion
803
+ //#region ---- Tool result normalization ----
804
+ function axpAiNormalizeHandlerResultToToolBody(handlerResult) {
805
+ if (handlerResult === undefined || handlerResult === null) {
806
+ return { success: false, error: 'Tool returned no result.' };
807
+ }
808
+ if (typeof handlerResult === 'string') {
809
+ const t = handlerResult.trim();
810
+ if (!t) {
811
+ return { success: false, error: 'Tool returned an empty string.' };
812
+ }
813
+ try {
814
+ return JSON.parse(t);
815
+ }
816
+ catch {
817
+ return { success: true, kind: 'object', data: handlerResult };
818
+ }
819
+ }
820
+ if (typeof handlerResult === 'object' && !Array.isArray(handlerResult)) {
821
+ return handlerResult;
822
+ }
823
+ return { success: true, kind: 'object', data: handlerResult };
824
+ }
825
+ //#endregion
826
+
827
+ //#region ---- Imports ----
828
+ //#endregion
829
+
830
+ //#region ----- Types -----
831
+ //#endregion
832
+ //#region ----- Constants -----
833
+ const IMAGE_MIME_TYPES = new Set([
834
+ 'image/jpeg',
835
+ 'image/png',
836
+ 'image/webp',
837
+ 'image/gif',
838
+ 'image/bmp',
839
+ 'image/tiff',
840
+ ]);
841
+ const IMAGE_EXTENSION_PATTERN = /\.(png|jpe?g|gif|webp|bmp|tif|tiff)$/i;
842
+ const TEXT_MIME_TYPES = new Set([
843
+ 'text/plain',
844
+ 'text/markdown',
845
+ 'text/csv',
846
+ 'application/json',
847
+ ]);
848
+ const TEXT_EXTENSION_PATTERN = /\.(txt|md|csv|json)$/i;
849
+ const PDF_MIME = 'application/pdf';
850
+ const PDF_EXTENSION_PATTERN = /\.pdf$/i;
851
+ //#endregion
852
+ //#region ----- Helpers -----
853
+ function normalizeMime(mimeType) {
854
+ return typeof mimeType === 'string' ? mimeType.trim().toLowerCase() : '';
855
+ }
856
+ function isTextMime(mime) {
857
+ if (TEXT_MIME_TYPES.has(mime)) {
858
+ return true;
859
+ }
860
+ return mime.startsWith('text/');
861
+ }
862
+ function classifyByFilename(filename) {
863
+ const name = typeof filename === 'string' ? filename.trim() : '';
864
+ if (!name) {
865
+ return 'unsupported';
866
+ }
867
+ if (IMAGE_EXTENSION_PATTERN.test(name)) {
868
+ return 'image';
869
+ }
870
+ if (PDF_EXTENSION_PATTERN.test(name)) {
871
+ return 'pdf';
872
+ }
873
+ if (TEXT_EXTENSION_PATTERN.test(name)) {
874
+ return 'text';
875
+ }
876
+ return 'unsupported';
877
+ }
878
+ //#endregion
879
+ //#region ----- Classification -----
880
+ /**
881
+ * Classifies a document for AI text extraction (image OCR, PDF file part, or UTF-8 text).
882
+ * Does not include Office formats.
883
+ */
884
+ function classifyAiExtractDocument(mimeType, filename) {
885
+ const mime = normalizeMime(mimeType);
886
+ if (mime && mime !== 'application/octet-stream') {
887
+ if (mime.startsWith('image/') || IMAGE_MIME_TYPES.has(mime)) {
888
+ return 'image';
889
+ }
890
+ if (mime === PDF_MIME) {
891
+ return 'pdf';
892
+ }
893
+ if (isTextMime(mime)) {
894
+ return 'text';
895
+ }
896
+ }
897
+ return classifyByFilename(filename);
898
+ }
899
+ function canAiExtractDocument(mimeType, filename) {
900
+ return classifyAiExtractDocument(mimeType, filename) !== 'unsupported';
901
+ }
902
+ //#endregion
903
+
904
+ //#region ---- Imports ----
905
+ //#endregion
906
+
907
+ //#region ---- AI chat registry command keys ----
908
+ const AIMANAGEMENT_CHAT_GENERATE_IMAGE_COMMAND_KEY = 'AiManagement:ChatGenerateImage';
909
+ const AIMANAGEMENT_CHAT_TRANSCRIBE_SPEECH_COMMAND_KEY = 'AiManagement:ChatTranscribeSpeech';
910
+ const AIMANAGEMENT_CHAT_SYNTHESIZE_SPEECH_COMMAND_KEY = 'AiManagement:ChatSynthesizeSpeech';
911
+ const AIMANAGEMENT_EXTRACT_DOCUMENT_TEXT_COMMAND_KEY = 'AiManagement:ExtractDocumentText';
912
+ const AIMANAGEMENT_STRUCTURED_TEXT_COMPLETION_COMMAND_KEY = 'AiManagement:StructuredTextCompletion';
913
+ //#endregion
914
+
915
+ //#region ---- AI engine runtime transport keys ----
916
+ const AXMAiManagementTransportKeys = {
917
+ Engine: {
918
+ Run: 'AiManagement:Engine:Run',
919
+ SubmitToolResult: 'AiManagement:Engine:SubmitToolResult',
920
+ },
921
+ ConversationAssist: {
922
+ Subscribe: 'ConversationManagement:Assist:Subscribe',
923
+ AssistSync: 'ConversationManagement:Assist:AssistSync',
924
+ RetryAssist: 'ConversationManagement:Assist:RetryAssist',
925
+ CancelAssist: 'ConversationManagement:Assist:CancelAssist',
926
+ },
927
+ };
928
+ //#endregion
929
+
930
+ //#region ---- Model catalog helpers ----
931
+ function readModelPurposes(row) {
932
+ if (!row) {
933
+ return [];
934
+ }
935
+ const multi = row['modelPurposes'];
936
+ if (!Array.isArray(multi)) {
937
+ return [];
938
+ }
939
+ const out = multi
940
+ .map((x) => String(x).trim())
941
+ .filter((x) => x.length > 0);
942
+ return [...new Set(out)];
943
+ }
944
+ function modelRowHasPurpose(row, purpose) {
945
+ return readModelPurposes(row).includes(purpose);
946
+ }
947
+ function isChatPurposeModelRow(row) {
948
+ const p = readModelPurposes(row);
949
+ return p.includes('chat') || p.includes('vision');
950
+ }
951
+ function parseChatTransport(raw) {
952
+ let v = '';
953
+ if (typeof raw === 'string') {
954
+ v = raw.trim().toLowerCase();
955
+ }
956
+ else if (raw != null && typeof raw === 'object' && 'value' in raw) {
957
+ const inner = raw.value;
958
+ v = inner == null ? '' : String(inner).trim().toLowerCase();
959
+ }
960
+ if (v === 'gemini' || v === 'openai' || v === 'demis') {
961
+ return v;
962
+ }
963
+ return undefined;
964
+ }
965
+ //#endregion
966
+
967
+ //#region ---- Imports ----
968
+ //#endregion
969
+ //#region ---- Transcript helpers ----
970
+ function axpAiChatMessagesFromProviderAssistant(text, toolCalls) {
971
+ const normalized = (text ?? '')
972
+ .replace(/&lt;(\/?redacted_thinking)&gt;/gi, '<$1>')
973
+ .replace(/&lt;(\/?think)&gt;/gi, '<$1>');
974
+ const responses = [];
975
+ const thinkRe = /<(redacted_thinking|think)>([\s\S]*?)<\/\1>/gi;
976
+ let last = 0;
977
+ let m;
978
+ while ((m = thinkRe.exec(normalized)) !== null) {
979
+ const plain = normalized.slice(last, m.index).trim();
980
+ if (plain.length > 0) {
981
+ responses.push({ type: 'text', content: plain });
982
+ }
983
+ const think = (m[2] ?? '').trim();
984
+ if (think.length > 0) {
985
+ responses.push({ type: 'think', content: think });
986
+ }
987
+ last = m.index + m[0].length;
988
+ }
989
+ const tail = normalized.slice(last).trim();
990
+ if (tail.length > 0) {
991
+ responses.push({ type: 'text', content: tail });
992
+ }
993
+ const out = [];
994
+ if (responses.length > 0) {
995
+ out.push({ role: 'assistant', responses });
996
+ }
997
+ for (const tc of toolCalls ?? []) {
998
+ const isDelegatedAgent = axpAiParseSupervisorAgentToolName(tc.name) != null;
999
+ out.push({
1000
+ role: 'assistant',
1001
+ responses: [
1002
+ isDelegatedAgent
1003
+ ? {
1004
+ type: 'agent',
1005
+ content: { command: tc.name, arguments: tc.arguments },
1006
+ callId: tc.id,
1007
+ ...(tc.metadata ? { metadata: { ...tc.metadata } } : {}),
1008
+ }
1009
+ : {
1010
+ type: 'tool',
1011
+ content: { command: tc.name, arguments: tc.arguments },
1012
+ callId: tc.id,
1013
+ ...(tc.metadata ? { metadata: { ...tc.metadata } } : {}),
1014
+ },
1015
+ ],
1016
+ });
1017
+ }
1018
+ return out;
1019
+ }
1020
+ function axcResolveAiMlOrPlainString(value, locale = 'en-US') {
1021
+ if (value == null) {
1022
+ return '';
1023
+ }
1024
+ if (typeof value === 'string') {
1025
+ return value.trim();
1026
+ }
1027
+ return resolveMultiLanguageString(value, locale).trim();
1028
+ }
1029
+ //#endregion
1030
+
1031
+ //#region ---- Contracts barrel ----
1032
+
1033
+ /**
1034
+ * Generated bundle index. Do not edit.
1035
+ */
1036
+
1037
+ export { AIMANAGEMENT_CHAT_GENERATE_IMAGE_COMMAND_KEY, AIMANAGEMENT_CHAT_SYNTHESIZE_SPEECH_COMMAND_KEY, AIMANAGEMENT_CHAT_TRANSCRIBE_SPEECH_COMMAND_KEY, AIMANAGEMENT_EXTRACT_DOCUMENT_TEXT_COMMAND_KEY, AIMANAGEMENT_STRUCTURED_TEXT_COMPLETION_COMMAND_KEY, AXMAiAssistPermissionKeys, AXMAiManagementTransportKeys, AXMPermissionsKeys, AXM_AI_PLATFORM_RUNTIME_CONTEXT_DEFINITIONS, AXPAI_AGENT_OUTPUT_CONTRACT_DEFAULT_STRUCTURED_RETRIES, AXPAI_SUPERVISOR_AGENT_TOOL_PREFIX, AXPAdministrationPermissionKeys, AXPAiManagementFeatureKeys, AXPAiManagementMenuKeys, AXPAiManagementSettings, AXP_AI_SDK_TOOL_CONTEXT_JSON_SCHEMA, AXP_FOLLOW_UP_ENVELOPE_JSON_SCHEMA, AXP_WIDGET_NODE_JSON_SCHEMA, RootConfig, assembleAxpAiPlatformRuntimeContext, attachAxpAiSdkChatContext, axcResolveAiMlOrPlainString, axpAiAgentOutputContractOmitsRoleBaseline, axpAiAgentOutputContractStructuredRetryCap, axpAiAgentOutputContractUsesStructuredFinalize, axpAiChatMessageGetText, axpAiChatMessagesFromProviderAssistant, axpAiChatTextMessage, axpAiChatToolResultMessage, axpAiNormalizeHandlerResultToToolBody, axpAiParseSupervisorAgentToolName, axpAiShouldApplyChatStructuredOutput, axpAiSupervisorAgentToolName, axpAiTextDuplicatesStructuredSegment, axpAiTryParseJsonValueFromAssistantText, buildAxpAiSdkChatContextBundle, canAiExtractDocument, classifyAiExtractDocument, defaultRetriesForKind, deriveProviderResponseFormat, formatAxpAiPlatformRuntimeLocalDateTime, formatAxpAiPlatformRuntimePrompt, isChatPurposeModelRow, modelRowHasPurpose, parseAgentOutputContract, parseChatTransport, parseJsonSchemaLike, parseResponseFormat, readModelPurposes, resolveAgentOutputContract, resolveBuiltinSchemaForOutputContract, resolveEffectiveOutputContract, resolveOutputTranscriptSegment };
1038
+ //# sourceMappingURL=acorex-platform-module-ai-management-client-contracts.mjs.map