@defai.digital/ax-cli 3.6.2 → 3.7.2

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,291 @@
1
+ /**
2
+ * Testing utilities for AX CLI SDK
3
+ *
4
+ * This module provides mock implementations and test helpers to make
5
+ * it easy to test code that uses the AX CLI SDK.
6
+ *
7
+ * @packageDocumentation
8
+ */
9
+ import { EventEmitter } from 'events';
10
+ /**
11
+ * Mock agent for testing
12
+ *
13
+ * Implements the same interface as LLMAgent but with predictable,
14
+ * controllable behavior for testing.
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * import { MockAgent } from '@defai.digital/ax-cli/sdk/testing';
19
+ *
20
+ * test('my integration', async () => {
21
+ * const agent = new MockAgent({
22
+ * responses: ['First response', 'Second response']
23
+ * });
24
+ *
25
+ * const result = await agent.processUserMessage('Hello');
26
+ * expect(result[0].content).toBe('First response');
27
+ * });
28
+ * ```
29
+ */
30
+ export class MockAgent extends EventEmitter {
31
+ responses;
32
+ currentResponseIndex = 0;
33
+ history = [];
34
+ disposed = false;
35
+ /**
36
+ * Create a new mock agent
37
+ *
38
+ * @param options - Configuration for mock behavior
39
+ */
40
+ constructor(options = {}) {
41
+ super();
42
+ this.responses = options.responses || ['Mock response'];
43
+ }
44
+ /**
45
+ * Process a user message (mock implementation)
46
+ *
47
+ * Returns the next predefined response and adds it to history.
48
+ * Cycles through responses if called more times than responses available.
49
+ *
50
+ * @param message - User message (stored in history)
51
+ * @returns Mock chat history
52
+ */
53
+ async processUserMessage(message) {
54
+ this.checkDisposed();
55
+ // Add user message to history
56
+ const userEntry = {
57
+ type: 'user',
58
+ content: message,
59
+ timestamp: new Date(),
60
+ };
61
+ this.history.push(userEntry);
62
+ // Get next response (cycle through)
63
+ const response = this.responses[this.currentResponseIndex % this.responses.length];
64
+ this.currentResponseIndex++;
65
+ // Add assistant response to history
66
+ const assistantEntry = {
67
+ type: 'assistant',
68
+ content: response,
69
+ timestamp: new Date(),
70
+ };
71
+ this.history.push(assistantEntry);
72
+ // Emit stream event for compatibility
73
+ this.emit('stream', {
74
+ type: 'content',
75
+ content: response,
76
+ });
77
+ this.emit('stream', {
78
+ type: 'done',
79
+ });
80
+ return [...this.history];
81
+ }
82
+ /**
83
+ * Process user message with streaming (mock implementation)
84
+ *
85
+ * Yields mock stream chunks for the response.
86
+ */
87
+ async *processUserMessageStream(message) {
88
+ this.checkDisposed();
89
+ // Add user message to history
90
+ const userEntry = {
91
+ type: 'user',
92
+ content: message,
93
+ timestamp: new Date(),
94
+ };
95
+ this.history.push(userEntry);
96
+ // Get next response
97
+ const response = this.responses[this.currentResponseIndex % this.responses.length];
98
+ this.currentResponseIndex++;
99
+ // Stream the response character by character (for realistic testing)
100
+ const words = response.split(' ');
101
+ for (const word of words) {
102
+ yield {
103
+ type: 'content',
104
+ content: word + ' ',
105
+ };
106
+ }
107
+ // Add assistant response to history
108
+ const assistantEntry = {
109
+ type: 'assistant',
110
+ content: response,
111
+ timestamp: new Date(),
112
+ };
113
+ this.history.push(assistantEntry);
114
+ yield {
115
+ type: 'done',
116
+ };
117
+ }
118
+ /**
119
+ * Get chat history (mock implementation)
120
+ */
121
+ getChatHistory() {
122
+ this.checkDisposed();
123
+ return [...this.history];
124
+ }
125
+ /**
126
+ * Execute bash command (mock implementation)
127
+ *
128
+ * Always returns success with predefined output.
129
+ */
130
+ async executeBashCommand(command) {
131
+ this.checkDisposed();
132
+ return {
133
+ success: true,
134
+ output: `Mock output for command: ${command}`,
135
+ };
136
+ }
137
+ /**
138
+ * Get current directory (mock implementation)
139
+ */
140
+ getCurrentDirectory() {
141
+ this.checkDisposed();
142
+ return '/mock/directory';
143
+ }
144
+ /**
145
+ * Create checkpoint (mock implementation)
146
+ */
147
+ async createCheckpoint(_description) {
148
+ this.checkDisposed();
149
+ return `mock-checkpoint-${Date.now()}`;
150
+ }
151
+ /**
152
+ * Rewind conversation (mock implementation)
153
+ */
154
+ async rewindConversation(_checkpointId) {
155
+ this.checkDisposed();
156
+ this.history = [];
157
+ return { success: true };
158
+ }
159
+ /**
160
+ * Check if bash is executing (mock implementation)
161
+ */
162
+ isBashExecuting() {
163
+ this.checkDisposed();
164
+ return false;
165
+ }
166
+ /**
167
+ * Dispose of mock agent
168
+ */
169
+ async dispose() {
170
+ if (this.disposed)
171
+ return;
172
+ this.disposed = true;
173
+ this.removeAllListeners();
174
+ this.history = [];
175
+ this.responses = [];
176
+ }
177
+ /**
178
+ * Reset mock agent state
179
+ *
180
+ * Clears history and resets response index.
181
+ * Useful for reusing the same mock across multiple tests.
182
+ */
183
+ reset() {
184
+ this.history = [];
185
+ this.currentResponseIndex = 0;
186
+ }
187
+ /**
188
+ * Set new responses
189
+ *
190
+ * @param responses - New responses to use
191
+ */
192
+ setResponses(responses) {
193
+ this.responses = responses;
194
+ this.currentResponseIndex = 0;
195
+ }
196
+ /**
197
+ * Get number of messages processed
198
+ */
199
+ getMessageCount() {
200
+ return this.history.filter(entry => entry.type === 'user').length;
201
+ }
202
+ checkDisposed() {
203
+ if (this.disposed) {
204
+ throw new Error('MockAgent has been disposed and cannot be used');
205
+ }
206
+ }
207
+ }
208
+ /**
209
+ * Create a mock agent with predefined responses
210
+ *
211
+ * Convenience function for creating mock agents.
212
+ *
213
+ * @param responses - Predefined responses (optional)
214
+ * @returns Mock agent instance
215
+ *
216
+ * @example
217
+ * ```typescript
218
+ * import { createMockAgent } from '@defai.digital/ax-cli/sdk/testing';
219
+ *
220
+ * const agent = createMockAgent(['Hello!', 'How can I help?']);
221
+ * const result = await agent.processUserMessage('Hi');
222
+ * expect(result[0].content).toBe('Hello!');
223
+ * ```
224
+ */
225
+ export function createMockAgent(responses) {
226
+ return new MockAgent({ responses });
227
+ }
228
+ /**
229
+ * Mock settings manager for testing
230
+ *
231
+ * Allows tests to control what settings are returned without
232
+ * needing actual config files.
233
+ *
234
+ * @example
235
+ * ```typescript
236
+ * import { MockSettingsManager } from '@defai.digital/ax-cli/sdk/testing';
237
+ *
238
+ * const settings = new MockSettingsManager({
239
+ * apiKey: 'test-key',
240
+ * baseURL: 'https://test.api.com',
241
+ * model: 'glm-4.6'
242
+ * });
243
+ * ```
244
+ */
245
+ export class MockSettingsManager {
246
+ settings;
247
+ constructor(settings = {}) {
248
+ this.settings = settings;
249
+ }
250
+ loadUserSettings() {
251
+ // No-op for mock
252
+ }
253
+ loadProjectSettings() {
254
+ // No-op for mock
255
+ }
256
+ getApiKey() {
257
+ return this.settings.apiKey;
258
+ }
259
+ getBaseURL() {
260
+ return this.settings.baseURL;
261
+ }
262
+ getCurrentModel() {
263
+ return this.settings.model || 'glm-4.6';
264
+ }
265
+ updateUserSetting(key, value) {
266
+ this.settings[key] = value;
267
+ }
268
+ saveUserSettings() {
269
+ // No-op for mock
270
+ }
271
+ }
272
+ /**
273
+ * Create a mock settings manager
274
+ *
275
+ * @param settings - Settings to return
276
+ * @returns Mock settings manager
277
+ *
278
+ * @example
279
+ * ```typescript
280
+ * import { createMockSettings } from '@defai.digital/ax-cli/sdk/testing';
281
+ *
282
+ * const settings = createMockSettings({
283
+ * apiKey: 'test-key',
284
+ * model: 'glm-4.6'
285
+ * });
286
+ * ```
287
+ */
288
+ export function createMockSettings(settings) {
289
+ return new MockSettingsManager(settings);
290
+ }
291
+ //# sourceMappingURL=testing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testing.js","sourceRoot":"","sources":["../../src/sdk/testing.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAItC;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,OAAO,SAAU,SAAQ,YAAY;IACjC,SAAS,CAAW;IACpB,oBAAoB,GAAG,CAAC,CAAC;IACzB,OAAO,GAAgB,EAAE,CAAC;IAC1B,QAAQ,GAAG,KAAK,CAAC;IAEzB;;;;OAIG;IACH,YAAY,UAGR,EAAE;QACJ,KAAK,EAAE,CAAC;QACR,IAA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OAAO,IAAI,SAAS,CAAC,EAAE,SAAS,EAAE,CAAC,CAAC;AACtC,CAAC;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,OAAO,mBAAmB;IACtB,QAAQ,CAId;IAEF,YAAY,WAIR,EAAE;QACJ,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC3B,CAAC;IAED,gBAAgB;QACd,iBAAiB;IACnB,CAAC;IAED,mBAAmB;QACjB,iBAAiB;IACnB,CAAC;IAED,SAAS;QACP,OAAO,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC;IAC9B,CAAC;IAED,UAAU;QACR,OAAO,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC;IAC/B,CAAC;IAED,eAAe;QACb,OAAO,IAAI,CAAC,QAAQ,CAAC,KAAK,IAAI,SAAS,CAAC;IAC1C,CAAC;IAED,iBAAiB,CAAC,GAAW,EAAE,KAAc;QAC1C,IAAI,CAAC,QAAgB,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;IACtC,CAAC;IAED,gBAAgB;QACd,iBAAiB;IACnB,CAAC;CACF;AAED;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,kBAAkB,CAAC,QAIlC;IACC,OAAO,IAAI,mBAAmB,CAAC,QAAQ,CAAC,CAAC;AAC3C,CAAC"}
@@ -0,0 +1,163 @@
1
+ /**
2
+ * Shared Tool Registry - Unified tool discovery for AX <-> ax-cli integration
3
+ *
4
+ * Allows AutomatosX agents to register custom tools that become available to ax-cli,
5
+ * and vice versa. Enables seamless tool sharing across both systems.
6
+ */
7
+ import type { LLMTool } from '../llm/client.js';
8
+ /**
9
+ * Tool execution context
10
+ */
11
+ export interface ToolExecutionContext {
12
+ /** Source system that's executing the tool */
13
+ source: 'ax-cli' | 'automatosx';
14
+ /** Agent ID executing the tool */
15
+ agentId?: string;
16
+ /** Additional context data */
17
+ metadata?: Record<string, unknown>;
18
+ }
19
+ /**
20
+ * Tool executor function
21
+ */
22
+ export type ToolExecutor = (args: Record<string, unknown>, context: ToolExecutionContext) => Promise<{
23
+ success: boolean;
24
+ output?: string;
25
+ error?: string;
26
+ data?: unknown;
27
+ }>;
28
+ /**
29
+ * Registered tool with execution handler
30
+ */
31
+ export interface RegisteredTool {
32
+ /** Tool definition (OpenAI format) */
33
+ definition: LLMTool;
34
+ /** Execution handler */
35
+ executor: ToolExecutor;
36
+ /** Source system that registered this tool */
37
+ registeredBy: 'ax-cli' | 'automatosx';
38
+ /** Registration timestamp */
39
+ registeredAt: number;
40
+ /** Optional tags for categorization */
41
+ tags?: string[];
42
+ }
43
+ /**
44
+ * Tool registration options
45
+ */
46
+ export interface ToolRegistrationOptions {
47
+ /** Tags for categorization */
48
+ tags?: string[];
49
+ /** Whether to allow overwriting existing tool */
50
+ allowOverwrite?: boolean;
51
+ }
52
+ /**
53
+ * Shared Tool Registry - Centralized tool management
54
+ */
55
+ export declare class ToolRegistry {
56
+ private static instance;
57
+ private tools;
58
+ private toolsBySource;
59
+ private constructor();
60
+ /**
61
+ * Get the singleton instance
62
+ */
63
+ static getInstance(): ToolRegistry;
64
+ /**
65
+ * Reset the singleton (for testing)
66
+ */
67
+ static reset(): void;
68
+ /**
69
+ * Register a tool
70
+ */
71
+ registerTool(source: 'ax-cli' | 'automatosx', definition: LLMTool, executor: ToolExecutor, options?: ToolRegistrationOptions): void;
72
+ /**
73
+ * Unregister a tool
74
+ */
75
+ unregisterTool(toolName: string): boolean;
76
+ /**
77
+ * Get a registered tool
78
+ */
79
+ getTool(toolName: string): RegisteredTool | undefined;
80
+ /**
81
+ * Check if a tool is registered
82
+ */
83
+ hasTool(toolName: string): boolean;
84
+ /**
85
+ * Get all tool definitions (OpenAI format)
86
+ */
87
+ getAllToolDefinitions(): LLMTool[];
88
+ /**
89
+ * Get tool definitions from specific source
90
+ */
91
+ getToolDefinitionsBySource(source: 'ax-cli' | 'automatosx'): LLMTool[];
92
+ /**
93
+ * Get tool definitions by tag
94
+ */
95
+ getToolDefinitionsByTag(tag: string): LLMTool[];
96
+ /**
97
+ * Execute a tool
98
+ */
99
+ executeTool(toolName: string, args: Record<string, unknown>, context: ToolExecutionContext): Promise<{
100
+ success: boolean;
101
+ output?: string;
102
+ error?: string;
103
+ data?: unknown;
104
+ }>;
105
+ /**
106
+ * Get all registered tool names
107
+ */
108
+ getToolNames(): string[];
109
+ /**
110
+ * Get tool names by source
111
+ */
112
+ getToolNamesBySource(source: 'ax-cli' | 'automatosx'): string[];
113
+ /**
114
+ * Clear all tools (optionally filter by source)
115
+ */
116
+ clear(source?: 'ax-cli' | 'automatosx'): void;
117
+ /**
118
+ * Get registry statistics
119
+ */
120
+ getStats(): {
121
+ total: number;
122
+ bySource: Record<string, number>;
123
+ byTag: Record<string, number>;
124
+ };
125
+ /**
126
+ * Export registry as JSON (excluding executors)
127
+ */
128
+ exportDefinitions(): {
129
+ tools: Array<{
130
+ name: string;
131
+ definition: LLMTool;
132
+ registeredBy: string;
133
+ registeredAt: number;
134
+ tags?: string[];
135
+ }>;
136
+ stats: {
137
+ total: number;
138
+ bySource: Record<string, number>;
139
+ byTag: Record<string, number>;
140
+ };
141
+ };
142
+ }
143
+ /**
144
+ * Get the global tool registry instance
145
+ */
146
+ export declare function getToolRegistry(): ToolRegistry;
147
+ /**
148
+ * Helper: Register multiple tools at once
149
+ */
150
+ export declare function registerTools(source: 'ax-cli' | 'automatosx', tools: Array<{
151
+ definition: LLMTool;
152
+ executor: ToolExecutor;
153
+ options?: ToolRegistrationOptions;
154
+ }>): void;
155
+ /**
156
+ * Helper: Create a simple tool executor from a function
157
+ */
158
+ export declare function createToolExecutor<T extends Record<string, unknown>>(handler: (args: T) => Promise<{
159
+ success: boolean;
160
+ output?: string;
161
+ error?: string;
162
+ data?: unknown;
163
+ }>): ToolExecutor;
@@ -0,0 +1,218 @@
1
+ /**
2
+ * Shared Tool Registry - Unified tool discovery for AX <-> ax-cli integration
3
+ *
4
+ * Allows AutomatosX agents to register custom tools that become available to ax-cli,
5
+ * and vice versa. Enables seamless tool sharing across both systems.
6
+ */
7
+ /**
8
+ * Shared Tool Registry - Centralized tool management
9
+ */
10
+ export class ToolRegistry {
11
+ static instance = null;
12
+ tools = new Map();
13
+ toolsBySource = new Map(); // source -> tool names
14
+ constructor() {
15
+ // Initialize source maps
16
+ this.toolsBySource.set('ax-cli', new Set());
17
+ this.toolsBySource.set('automatosx', new Set());
18
+ }
19
+ /**
20
+ * Get the singleton instance
21
+ */
22
+ static getInstance() {
23
+ if (!ToolRegistry.instance) {
24
+ ToolRegistry.instance = new ToolRegistry();
25
+ }
26
+ return ToolRegistry.instance;
27
+ }
28
+ /**
29
+ * Reset the singleton (for testing)
30
+ */
31
+ static reset() {
32
+ if (ToolRegistry.instance) {
33
+ ToolRegistry.instance.clear();
34
+ ToolRegistry.instance = null;
35
+ }
36
+ }
37
+ /**
38
+ * Register a tool
39
+ */
40
+ registerTool(source, definition, executor, options = {}) {
41
+ const toolName = definition.function.name;
42
+ // Check if tool already exists
43
+ if (this.tools.has(toolName) && !options.allowOverwrite) {
44
+ throw new Error(`Tool '${toolName}' is already registered. Use allowOverwrite: true to replace it.`);
45
+ }
46
+ const registeredTool = {
47
+ definition,
48
+ executor,
49
+ registeredBy: source,
50
+ registeredAt: Date.now(),
51
+ tags: options.tags,
52
+ };
53
+ this.tools.set(toolName, registeredTool);
54
+ this.toolsBySource.get(source).add(toolName);
55
+ }
56
+ /**
57
+ * Unregister a tool
58
+ */
59
+ unregisterTool(toolName) {
60
+ const tool = this.tools.get(toolName);
61
+ if (!tool) {
62
+ return false;
63
+ }
64
+ this.tools.delete(toolName);
65
+ this.toolsBySource.get(tool.registeredBy).delete(toolName);
66
+ return true;
67
+ }
68
+ /**
69
+ * Get a registered tool
70
+ */
71
+ getTool(toolName) {
72
+ return this.tools.get(toolName);
73
+ }
74
+ /**
75
+ * Check if a tool is registered
76
+ */
77
+ hasTool(toolName) {
78
+ return this.tools.has(toolName);
79
+ }
80
+ /**
81
+ * Get all tool definitions (OpenAI format)
82
+ */
83
+ getAllToolDefinitions() {
84
+ return Array.from(this.tools.values()).map(tool => tool.definition);
85
+ }
86
+ /**
87
+ * Get tool definitions from specific source
88
+ */
89
+ getToolDefinitionsBySource(source) {
90
+ const toolNames = this.toolsBySource.get(source) || new Set();
91
+ return Array.from(toolNames)
92
+ .map(name => this.tools.get(name))
93
+ .filter((tool) => tool !== undefined)
94
+ .map(tool => tool.definition);
95
+ }
96
+ /**
97
+ * Get tool definitions by tag
98
+ */
99
+ getToolDefinitionsByTag(tag) {
100
+ return Array.from(this.tools.values())
101
+ .filter(tool => tool.tags?.includes(tag))
102
+ .map(tool => tool.definition);
103
+ }
104
+ /**
105
+ * Execute a tool
106
+ */
107
+ async executeTool(toolName, args, context) {
108
+ const tool = this.tools.get(toolName);
109
+ if (!tool) {
110
+ return {
111
+ success: false,
112
+ error: `Tool '${toolName}' not found in registry`,
113
+ };
114
+ }
115
+ try {
116
+ const result = await tool.executor(args, context);
117
+ return result;
118
+ }
119
+ catch (error) {
120
+ return {
121
+ success: false,
122
+ error: error instanceof Error ? error.message : 'Unknown execution error',
123
+ };
124
+ }
125
+ }
126
+ /**
127
+ * Get all registered tool names
128
+ */
129
+ getToolNames() {
130
+ return Array.from(this.tools.keys());
131
+ }
132
+ /**
133
+ * Get tool names by source
134
+ */
135
+ getToolNamesBySource(source) {
136
+ return Array.from(this.toolsBySource.get(source) || []);
137
+ }
138
+ /**
139
+ * Clear all tools (optionally filter by source)
140
+ */
141
+ clear(source) {
142
+ if (source) {
143
+ // Clear only tools from specific source
144
+ const toolNames = Array.from(this.toolsBySource.get(source) || []);
145
+ for (const name of toolNames) {
146
+ this.tools.delete(name);
147
+ }
148
+ this.toolsBySource.get(source).clear();
149
+ }
150
+ else {
151
+ // Clear all tools
152
+ this.tools.clear();
153
+ this.toolsBySource.get('ax-cli').clear();
154
+ this.toolsBySource.get('automatosx').clear();
155
+ }
156
+ }
157
+ /**
158
+ * Get registry statistics
159
+ */
160
+ getStats() {
161
+ const byTag = {};
162
+ for (const tool of this.tools.values()) {
163
+ if (tool.tags) {
164
+ for (const tag of tool.tags) {
165
+ byTag[tag] = (byTag[tag] || 0) + 1;
166
+ }
167
+ }
168
+ }
169
+ return {
170
+ total: this.tools.size,
171
+ bySource: {
172
+ 'ax-cli': this.toolsBySource.get('ax-cli').size,
173
+ 'automatosx': this.toolsBySource.get('automatosx').size,
174
+ },
175
+ byTag,
176
+ };
177
+ }
178
+ /**
179
+ * Export registry as JSON (excluding executors)
180
+ */
181
+ exportDefinitions() {
182
+ const tools = Array.from(this.tools.entries()).map(([name, tool]) => ({
183
+ name,
184
+ definition: tool.definition,
185
+ registeredBy: tool.registeredBy,
186
+ registeredAt: tool.registeredAt,
187
+ tags: tool.tags,
188
+ }));
189
+ return {
190
+ tools,
191
+ stats: this.getStats(),
192
+ };
193
+ }
194
+ }
195
+ /**
196
+ * Get the global tool registry instance
197
+ */
198
+ export function getToolRegistry() {
199
+ return ToolRegistry.getInstance();
200
+ }
201
+ /**
202
+ * Helper: Register multiple tools at once
203
+ */
204
+ export function registerTools(source, tools) {
205
+ const registry = getToolRegistry();
206
+ for (const { definition, executor, options } of tools) {
207
+ registry.registerTool(source, definition, executor, options);
208
+ }
209
+ }
210
+ /**
211
+ * Helper: Create a simple tool executor from a function
212
+ */
213
+ export function createToolExecutor(handler) {
214
+ return async (args, _context) => {
215
+ return handler(args);
216
+ };
217
+ }
218
+ //# sourceMappingURL=tool-registry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool-registry.js","sourceRoot":"","sources":["../../src/sdk/tool-registry.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAuDH;;GAEG;AACH,MAAM,OAAO,YAAY;IACf,MAAM,CAAC,QAAQ,GAAwB,IAAI,CAAC;IAE5C,KAAK,GAAgC,IAAI,GAAG,EAAE,CAAC;IAC/C,aAAa,GAA6B,IAAI,GAAG,EAAE,CAAC,CAAC,uBAAuB;IAEpF;QACE,yBAAyB;QACzB,IAAI,CAAC,a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