@defai.digital/ax-cli 3.0.2 → 3.1.0

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 (81) hide show
  1. package/README.md +74 -0
  2. package/dist/agent/llm-agent.d.ts +21 -0
  3. package/dist/agent/llm-agent.js +64 -15
  4. package/dist/agent/llm-agent.js.map +1 -1
  5. package/dist/agent/subagent-orchestrator.js +4 -0
  6. package/dist/agent/subagent-orchestrator.js.map +1 -1
  7. package/dist/commands/mcp.js +10 -6
  8. package/dist/commands/mcp.js.map +1 -1
  9. package/dist/commands/memory.d.ts +1 -0
  10. package/dist/commands/memory.js +285 -1
  11. package/dist/commands/memory.js.map +1 -1
  12. package/dist/hooks/use-enhanced-input.js +3 -1
  13. package/dist/hooks/use-enhanced-input.js.map +1 -1
  14. package/dist/hooks/use-input-handler.js +18 -7
  15. package/dist/hooks/use-input-handler.js.map +1 -1
  16. package/dist/index.js +4 -0
  17. package/dist/index.js.map +1 -1
  18. package/dist/llm/client.js +52 -5
  19. package/dist/llm/client.js.map +1 -1
  20. package/dist/llm/tools.js +12 -2
  21. package/dist/llm/tools.js.map +1 -1
  22. package/dist/llm/types.d.ts +93 -1
  23. package/dist/llm/types.js +60 -0
  24. package/dist/llm/types.js.map +1 -1
  25. package/dist/mcp/client.d.ts +1 -1
  26. package/dist/mcp/client.js +8 -3
  27. package/dist/mcp/client.js.map +1 -1
  28. package/dist/memory/context-generator.d.ts +84 -0
  29. package/dist/memory/context-generator.js +537 -0
  30. package/dist/memory/context-generator.js.map +1 -0
  31. package/dist/memory/context-injector.d.ts +83 -0
  32. package/dist/memory/context-injector.js +142 -0
  33. package/dist/memory/context-injector.js.map +1 -0
  34. package/dist/memory/context-store.d.ts +76 -0
  35. package/dist/memory/context-store.js +212 -0
  36. package/dist/memory/context-store.js.map +1 -0
  37. package/dist/memory/index.d.ts +42 -0
  38. package/dist/memory/index.js +47 -0
  39. package/dist/memory/index.js.map +1 -0
  40. package/dist/memory/schemas.d.ts +316 -0
  41. package/dist/memory/schemas.js +103 -0
  42. package/dist/memory/schemas.js.map +1 -0
  43. package/dist/memory/stats-collector.d.ts +73 -0
  44. package/dist/memory/stats-collector.js +170 -0
  45. package/dist/memory/stats-collector.js.map +1 -0
  46. package/dist/memory/types.d.ts +175 -0
  47. package/dist/memory/types.js +70 -0
  48. package/dist/memory/types.js.map +1 -0
  49. package/dist/planner/task-planner.js +19 -2
  50. package/dist/planner/task-planner.js.map +1 -1
  51. package/dist/schemas/api-schemas.js +1 -1
  52. package/dist/schemas/api-schemas.js.map +1 -1
  53. package/dist/schemas/index.d.ts +4 -4
  54. package/dist/schemas/settings-schemas.d.ts +14 -0
  55. package/dist/schemas/settings-schemas.js +10 -0
  56. package/dist/schemas/settings-schemas.js.map +1 -1
  57. package/dist/tools/bash.js +28 -7
  58. package/dist/tools/bash.js.map +1 -1
  59. package/dist/ui/components/chat-history.js +4 -2
  60. package/dist/ui/components/chat-history.js.map +1 -1
  61. package/dist/ui/components/chat-interface.js +9 -4
  62. package/dist/ui/components/chat-interface.js.map +1 -1
  63. package/dist/ui/components/toast-notification.d.ts +3 -0
  64. package/dist/ui/components/toast-notification.js +18 -12
  65. package/dist/ui/components/toast-notification.js.map +1 -1
  66. package/dist/utils/background-task-manager.js +31 -9
  67. package/dist/utils/background-task-manager.js.map +1 -1
  68. package/dist/utils/custom-instructions.js +9 -1
  69. package/dist/utils/custom-instructions.js.map +1 -1
  70. package/dist/utils/prompt-builder.d.ts +4 -0
  71. package/dist/utils/prompt-builder.js +15 -0
  72. package/dist/utils/prompt-builder.js.map +1 -1
  73. package/dist/utils/settings-manager.d.ts +16 -1
  74. package/dist/utils/settings-manager.js +49 -0
  75. package/dist/utils/settings-manager.js.map +1 -1
  76. package/dist/utils/token-counter.js +4 -0
  77. package/dist/utils/token-counter.js.map +1 -1
  78. package/dist/utils/usage-tracker.d.ts +19 -0
  79. package/dist/utils/usage-tracker.js +22 -1
  80. package/dist/utils/usage-tracker.js.map +1 -1
  81. package/package.json +1 -1
@@ -0,0 +1,316 @@
1
+ /**
2
+ * Zod schemas for Project Memory validation
3
+ *
4
+ * Provides runtime validation for memory.json structure
5
+ */
6
+ import { z } from 'zod';
7
+ /**
8
+ * Schema for directory configuration
9
+ */
10
+ export declare const DirectoryConfigSchema: z.ZodObject<{
11
+ path: z.ZodString;
12
+ max_depth: z.ZodNumber;
13
+ }, "strip", z.ZodTypeAny, {
14
+ path: string;
15
+ max_depth: number;
16
+ }, {
17
+ path: string;
18
+ max_depth: number;
19
+ }>;
20
+ /**
21
+ * Schema for source configuration
22
+ */
23
+ export declare const SourceConfigSchema: z.ZodObject<{
24
+ directories: z.ZodArray<z.ZodObject<{
25
+ path: z.ZodString;
26
+ max_depth: z.ZodNumber;
27
+ }, "strip", z.ZodTypeAny, {
28
+ path: string;
29
+ max_depth: number;
30
+ }, {
31
+ path: string;
32
+ max_depth: number;
33
+ }>, "many">;
34
+ files: z.ZodArray<z.ZodString, "many">;
35
+ ignore: z.ZodArray<z.ZodString, "many">;
36
+ }, "strip", z.ZodTypeAny, {
37
+ directories: {
38
+ path: string;
39
+ max_depth: number;
40
+ }[];
41
+ files: string[];
42
+ ignore: string[];
43
+ }, {
44
+ directories: {
45
+ path: string;
46
+ max_depth: number;
47
+ }[];
48
+ files: string[];
49
+ ignore: string[];
50
+ }>;
51
+ /**
52
+ * Schema for context sections token distribution
53
+ */
54
+ export declare const ContextSectionsSchema: z.ZodObject<{
55
+ structure: z.ZodOptional<z.ZodNumber>;
56
+ readme: z.ZodOptional<z.ZodNumber>;
57
+ config: z.ZodOptional<z.ZodNumber>;
58
+ patterns: z.ZodOptional<z.ZodNumber>;
59
+ }, "strip", z.ZodTypeAny, {
60
+ structure?: number | undefined;
61
+ readme?: number | undefined;
62
+ config?: number | undefined;
63
+ patterns?: number | undefined;
64
+ }, {
65
+ structure?: number | undefined;
66
+ readme?: number | undefined;
67
+ config?: number | undefined;
68
+ patterns?: number | undefined;
69
+ }>;
70
+ /**
71
+ * Schema for generated context data
72
+ */
73
+ export declare const ContextDataSchema: z.ZodObject<{
74
+ formatted: z.ZodString;
75
+ token_estimate: z.ZodNumber;
76
+ sections: z.ZodObject<{
77
+ structure: z.ZodOptional<z.ZodNumber>;
78
+ readme: z.ZodOptional<z.ZodNumber>;
79
+ config: z.ZodOptional<z.ZodNumber>;
80
+ patterns: z.ZodOptional<z.ZodNumber>;
81
+ }, "strip", z.ZodTypeAny, {
82
+ structure?: number | undefined;
83
+ readme?: number | undefined;
84
+ config?: number | undefined;
85
+ patterns?: number | undefined;
86
+ }, {
87
+ structure?: number | undefined;
88
+ readme?: number | undefined;
89
+ config?: number | undefined;
90
+ patterns?: number | undefined;
91
+ }>;
92
+ }, "strip", z.ZodTypeAny, {
93
+ sections: {
94
+ structure?: number | undefined;
95
+ readme?: number | undefined;
96
+ config?: number | undefined;
97
+ patterns?: number | undefined;
98
+ };
99
+ formatted: string;
100
+ token_estimate: number;
101
+ }, {
102
+ sections: {
103
+ structure?: number | undefined;
104
+ readme?: number | undefined;
105
+ config?: number | undefined;
106
+ patterns?: number | undefined;
107
+ };
108
+ formatted: string;
109
+ token_estimate: number;
110
+ }>;
111
+ /**
112
+ * Schema for cache statistics
113
+ */
114
+ export declare const CacheStatsSchema: z.ZodObject<{
115
+ last_cached_tokens: z.ZodOptional<z.ZodNumber>;
116
+ last_prompt_tokens: z.ZodOptional<z.ZodNumber>;
117
+ total_tokens_saved: z.ZodOptional<z.ZodNumber>;
118
+ usage_count: z.ZodOptional<z.ZodNumber>;
119
+ last_used_at: z.ZodOptional<z.ZodString>;
120
+ }, "strip", z.ZodTypeAny, {
121
+ last_cached_tokens?: number | undefined;
122
+ last_prompt_tokens?: number | undefined;
123
+ total_tokens_saved?: number | undefined;
124
+ usage_count?: number | undefined;
125
+ last_used_at?: string | undefined;
126
+ }, {
127
+ last_cached_tokens?: number | undefined;
128
+ last_prompt_tokens?: number | undefined;
129
+ total_tokens_saved?: number | undefined;
130
+ usage_count?: number | undefined;
131
+ last_used_at?: string | undefined;
132
+ }>;
133
+ /**
134
+ * Main Project Memory schema
135
+ */
136
+ export declare const ProjectMemorySchema: z.ZodObject<{
137
+ version: z.ZodLiteral<1>;
138
+ created_at: z.ZodString;
139
+ updated_at: z.ZodString;
140
+ project_root: z.ZodString;
141
+ content_hash: z.ZodString;
142
+ source: z.ZodObject<{
143
+ directories: z.ZodArray<z.ZodObject<{
144
+ path: z.ZodString;
145
+ max_depth: z.ZodNumber;
146
+ }, "strip", z.ZodTypeAny, {
147
+ path: string;
148
+ max_depth: number;
149
+ }, {
150
+ path: string;
151
+ max_depth: number;
152
+ }>, "many">;
153
+ files: z.ZodArray<z.ZodString, "many">;
154
+ ignore: z.ZodArray<z.ZodString, "many">;
155
+ }, "strip", z.ZodTypeAny, {
156
+ directories: {
157
+ path: string;
158
+ max_depth: number;
159
+ }[];
160
+ files: string[];
161
+ ignore: string[];
162
+ }, {
163
+ directories: {
164
+ path: string;
165
+ max_depth: number;
166
+ }[];
167
+ files: string[];
168
+ ignore: string[];
169
+ }>;
170
+ context: z.ZodObject<{
171
+ formatted: z.ZodString;
172
+ token_estimate: z.ZodNumber;
173
+ sections: z.ZodObject<{
174
+ structure: z.ZodOptional<z.ZodNumber>;
175
+ readme: z.ZodOptional<z.ZodNumber>;
176
+ config: z.ZodOptional<z.ZodNumber>;
177
+ patterns: z.ZodOptional<z.ZodNumber>;
178
+ }, "strip", z.ZodTypeAny, {
179
+ structure?: number | undefined;
180
+ readme?: number | undefined;
181
+ config?: number | undefined;
182
+ patterns?: number | undefined;
183
+ }, {
184
+ structure?: number | undefined;
185
+ readme?: number | undefined;
186
+ config?: number | undefined;
187
+ patterns?: number | undefined;
188
+ }>;
189
+ }, "strip", z.ZodTypeAny, {
190
+ sections: {
191
+ structure?: number | undefined;
192
+ readme?: number | undefined;
193
+ config?: number | undefined;
194
+ patterns?: number | undefined;
195
+ };
196
+ formatted: string;
197
+ token_estimate: number;
198
+ }, {
199
+ sections: {
200
+ structure?: number | undefined;
201
+ readme?: number | undefined;
202
+ config?: number | undefined;
203
+ patterns?: number | undefined;
204
+ };
205
+ formatted: string;
206
+ token_estimate: number;
207
+ }>;
208
+ stats: z.ZodOptional<z.ZodObject<{
209
+ last_cached_tokens: z.ZodOptional<z.ZodNumber>;
210
+ last_prompt_tokens: z.ZodOptional<z.ZodNumber>;
211
+ total_tokens_saved: z.ZodOptional<z.ZodNumber>;
212
+ usage_count: z.ZodOptional<z.ZodNumber>;
213
+ last_used_at: z.ZodOptional<z.ZodString>;
214
+ }, "strip", z.ZodTypeAny, {
215
+ last_cached_tokens?: number | undefined;
216
+ last_prompt_tokens?: number | undefined;
217
+ total_tokens_saved?: number | undefined;
218
+ usage_count?: number | undefined;
219
+ last_used_at?: string | undefined;
220
+ }, {
221
+ last_cached_tokens?: number | undefined;
222
+ last_prompt_tokens?: number | undefined;
223
+ total_tokens_saved?: number | undefined;
224
+ usage_count?: number | undefined;
225
+ last_used_at?: string | undefined;
226
+ }>>;
227
+ }, "strip", z.ZodTypeAny, {
228
+ version: 1;
229
+ created_at: string;
230
+ updated_at: string;
231
+ project_root: string;
232
+ content_hash: string;
233
+ source: {
234
+ directories: {
235
+ path: string;
236
+ max_depth: number;
237
+ }[];
238
+ files: string[];
239
+ ignore: string[];
240
+ };
241
+ context: {
242
+ sections: {
243
+ structure?: number | undefined;
244
+ readme?: number | undefined;
245
+ config?: number | undefined;
246
+ patterns?: number | undefined;
247
+ };
248
+ formatted: string;
249
+ token_estimate: number;
250
+ };
251
+ stats?: {
252
+ last_cached_tokens?: number | undefined;
253
+ last_prompt_tokens?: number | undefined;
254
+ total_tokens_saved?: number | undefined;
255
+ usage_count?: number | undefined;
256
+ last_used_at?: string | undefined;
257
+ } | undefined;
258
+ }, {
259
+ version: 1;
260
+ created_at: string;
261
+ updated_at: string;
262
+ project_root: string;
263
+ content_hash: string;
264
+ source: {
265
+ directories: {
266
+ path: string;
267
+ max_depth: number;
268
+ }[];
269
+ files: string[];
270
+ ignore: string[];
271
+ };
272
+ context: {
273
+ sections: {
274
+ structure?: number | undefined;
275
+ readme?: number | undefined;
276
+ config?: number | undefined;
277
+ patterns?: number | undefined;
278
+ };
279
+ formatted: string;
280
+ token_estimate: number;
281
+ };
282
+ stats?: {
283
+ last_cached_tokens?: number | undefined;
284
+ last_prompt_tokens?: number | undefined;
285
+ total_tokens_saved?: number | undefined;
286
+ usage_count?: number | undefined;
287
+ last_used_at?: string | undefined;
288
+ } | undefined;
289
+ }>;
290
+ /**
291
+ * Inferred TypeScript type from schema
292
+ */
293
+ export type ProjectMemorySchema = z.infer<typeof ProjectMemorySchema>;
294
+ /**
295
+ * Safe validation result type
296
+ */
297
+ export type ValidationResult<T> = {
298
+ success: true;
299
+ data: T;
300
+ } | {
301
+ success: false;
302
+ error: string;
303
+ };
304
+ /**
305
+ * Safely validate project memory data
306
+ * Returns a discriminated union for easy error handling
307
+ */
308
+ export declare function safeValidateProjectMemory(data: unknown): ValidationResult<ProjectMemorySchema>;
309
+ /**
310
+ * Validate partial memory update (for stats updates)
311
+ */
312
+ export declare function safeValidateCacheStats(data: unknown): ValidationResult<z.infer<typeof CacheStatsSchema>>;
313
+ /**
314
+ * Validate source configuration
315
+ */
316
+ export declare function safeValidateSourceConfig(data: unknown): ValidationResult<z.infer<typeof SourceConfigSchema>>;
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Zod schemas for Project Memory validation
3
+ *
4
+ * Provides runtime validation for memory.json structure
5
+ */
6
+ import { z } from 'zod';
7
+ /**
8
+ * Schema for directory configuration
9
+ */
10
+ export const DirectoryConfigSchema = z.object({
11
+ path: z.string().min(1, 'Directory path cannot be empty'),
12
+ max_depth: z.number().int().min(1).max(10),
13
+ });
14
+ /**
15
+ * Schema for source configuration
16
+ */
17
+ export const SourceConfigSchema = z.object({
18
+ directories: z.array(DirectoryConfigSchema),
19
+ files: z.array(z.string()),
20
+ ignore: z.array(z.string()),
21
+ });
22
+ /**
23
+ * Schema for context sections token distribution
24
+ */
25
+ export const ContextSectionsSchema = z.object({
26
+ structure: z.number().int().min(0).optional(),
27
+ readme: z.number().int().min(0).optional(),
28
+ config: z.number().int().min(0).optional(),
29
+ patterns: z.number().int().min(0).optional(),
30
+ });
31
+ /**
32
+ * Schema for generated context data
33
+ */
34
+ export const ContextDataSchema = z.object({
35
+ formatted: z.string(),
36
+ token_estimate: z.number().int().min(0),
37
+ sections: ContextSectionsSchema,
38
+ });
39
+ /**
40
+ * Schema for cache statistics
41
+ */
42
+ export const CacheStatsSchema = z.object({
43
+ last_cached_tokens: z.number().int().min(0).optional(),
44
+ last_prompt_tokens: z.number().int().min(0).optional(),
45
+ total_tokens_saved: z.number().int().min(0).optional(),
46
+ usage_count: z.number().int().min(0).optional(),
47
+ last_used_at: z.string().datetime().optional(),
48
+ });
49
+ /**
50
+ * Main Project Memory schema
51
+ */
52
+ export const ProjectMemorySchema = z.object({
53
+ version: z.literal(1),
54
+ created_at: z.string().datetime(),
55
+ updated_at: z.string().datetime(),
56
+ project_root: z.string().min(1),
57
+ content_hash: z.string().regex(/^sha256:[a-f0-9]{64}$/, 'Content hash must be in format: sha256:<64 hex chars>'),
58
+ source: SourceConfigSchema,
59
+ context: ContextDataSchema,
60
+ stats: CacheStatsSchema.optional(),
61
+ });
62
+ /**
63
+ * Safely validate project memory data
64
+ * Returns a discriminated union for easy error handling
65
+ */
66
+ export function safeValidateProjectMemory(data) {
67
+ const result = ProjectMemorySchema.safeParse(data);
68
+ if (result.success) {
69
+ return { success: true, data: result.data };
70
+ }
71
+ // Format error message
72
+ const errors = result.error.errors
73
+ .map((e) => `${e.path.join('.')}: ${e.message}`)
74
+ .join('; ');
75
+ return { success: false, error: errors };
76
+ }
77
+ /**
78
+ * Validate partial memory update (for stats updates)
79
+ */
80
+ export function safeValidateCacheStats(data) {
81
+ const result = CacheStatsSchema.safeParse(data);
82
+ if (result.success) {
83
+ return { success: true, data: result.data };
84
+ }
85
+ const errors = result.error.errors
86
+ .map((e) => `${e.path.join('.')}: ${e.message}`)
87
+ .join('; ');
88
+ return { success: false, error: errors };
89
+ }
90
+ /**
91
+ * Validate source configuration
92
+ */
93
+ export function safeValidateSourceConfig(data) {
94
+ const result = SourceConfigSchema.safeParse(data);
95
+ if (result.success) {
96
+ return { success: true, data: result.data };
97
+ }
98
+ const errors = result.error.errors
99
+ .map((e) => `${e.path.join('.')}: ${e.message}`)
100
+ .join('; ');
101
+ return { success: false, error: errors };
102
+ }
103
+ //# sourceMappingURL=schemas.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schemas.js","sourceRoot":"","sources":["../../src/memory/schemas.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB;;GAEG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,CAAC,MAAM,CAAC;IAC5C,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,EAAE,gCAAgC,CAAC;IACzD,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC;CAC3C,CAAC,CAAC;AAEH;;GAEG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,CAAC,MAAM,CAAC;IACzC,WAAW,EAAE,CAAC,CAAC,KAAK,CAAC,qBAAqB,CAAC;IAC3C,KAAK,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC;IAC1B,MAAM,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC;CAC5B,CAAC,CAAC;AAEH;;GAEG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,CAAC,MAAM,CAAC;IAC5C,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,CA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AS,CAAC,IAAI,CAAC,CAAC;IAEhD,IAAI,MAAM,CAAC,OAAO,EAAE,CAAC;QACnB,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,EAAE,CAAC;IAC9C,CAAC;IAED,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,MAAM;SAC/B,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,OAAO,EAAE,CAAC;SAC/C,IAAI,CAAC,IAAI,CAAC,CAAC;IAEd,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC;AAC3C,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,wBAAwB,CACtC,IAAa;IAEb,MAAM,MAAM,GAAG,kBAAkB,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;IAElD,IAAI,MAAM,CAAC,OAAO,EAAE,CAAC;QACnB,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,EAAE,CAAC;IAC9C,CAAC;IAED,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,MAAM;SAC/B,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,OAAO,EAAE,CAAC;SAC/C,IAAI,CAAC,IAAI,CAAC,CAAC;IAEd,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC;AAC3C,CAAC"}
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Stats Collector - Collects and reports cache statistics
3
+ *
4
+ * Tracks z.ai cache performance by recording cached_tokens
5
+ * from API responses and calculating efficiency metrics.
6
+ */
7
+ import type { CacheStats } from './types.js';
8
+ /**
9
+ * Formatted statistics for display
10
+ */
11
+ export interface FormattedStats {
12
+ /** Human-readable stats text */
13
+ text: string;
14
+ /** Cache hit rate percentage (0-100) */
15
+ cacheRate: number;
16
+ /** Total tokens saved through caching */
17
+ tokensSaved: number;
18
+ /** Number of API calls */
19
+ usageCount: number;
20
+ /** Estimated cost savings (rough estimate) */
21
+ estimatedSavings: number;
22
+ }
23
+ /**
24
+ * StatsCollector - Manages cache statistics
25
+ */
26
+ export declare class StatsCollector {
27
+ private store;
28
+ constructor(projectRoot?: string);
29
+ /**
30
+ * Record API response statistics
31
+ *
32
+ * @param promptTokens - Total prompt tokens from response
33
+ * @param cachedTokens - Cached tokens from response (from usage.prompt_tokens_details.cached_tokens)
34
+ */
35
+ recordResponse(promptTokens: number, cachedTokens: number): void;
36
+ /**
37
+ * Get raw statistics
38
+ */
39
+ getStats(): CacheStats | null;
40
+ /**
41
+ * Calculate cache hit rate from last request
42
+ */
43
+ getLastCacheRate(): number;
44
+ /**
45
+ * Calculate estimated cost savings
46
+ */
47
+ getEstimatedSavings(): number;
48
+ /**
49
+ * Get formatted statistics for display
50
+ */
51
+ getFormattedStats(): FormattedStats | null;
52
+ /**
53
+ * Format a brief cache status line for verbose output
54
+ */
55
+ formatBriefStatus(promptTokens: number, cachedTokens: number): string;
56
+ /**
57
+ * Check if caching appears to be working
58
+ * Returns a warning message if cache hits are consistently zero
59
+ */
60
+ checkCacheHealth(): string | null;
61
+ /**
62
+ * Reset statistics (keeps memory content, only clears stats)
63
+ */
64
+ resetStats(): boolean;
65
+ }
66
+ /**
67
+ * Get the default stats collector instance
68
+ */
69
+ export declare function getStatsCollector(projectRoot?: string): StatsCollector;
70
+ /**
71
+ * Reset the default collector (mainly for testing)
72
+ */
73
+ export declare function resetDefaultCollector(): void;
@@ -0,0 +1,170 @@
1
+ /**
2
+ * Stats Collector - Collects and reports cache statistics
3
+ *
4
+ * Tracks z.ai cache performance by recording cached_tokens
5
+ * from API responses and calculating efficiency metrics.
6
+ */
7
+ import { ContextStore } from './context-store.js';
8
+ /**
9
+ * Token pricing constants (rough estimates for z.ai)
10
+ * These are approximate and should be updated based on actual pricing
11
+ */
12
+ const PRICING = {
13
+ /** Cost per 1K input tokens (USD) */
14
+ INPUT_PER_1K: 0.002,
15
+ /** Cost per 1K cached tokens (50% discount) */
16
+ CACHED_PER_1K: 0.001,
17
+ };
18
+ /**
19
+ * StatsCollector - Manages cache statistics
20
+ */
21
+ export class StatsCollector {
22
+ store;
23
+ constructor(projectRoot = process.cwd()) {
24
+ this.store = new ContextStore(projectRoot);
25
+ }
26
+ /**
27
+ * Record API response statistics
28
+ *
29
+ * @param promptTokens - Total prompt tokens from response
30
+ * @param cachedTokens - Cached tokens from response (from usage.prompt_tokens_details.cached_tokens)
31
+ */
32
+ recordResponse(promptTokens, cachedTokens) {
33
+ // Use the store's recordUsage method
34
+ this.store.recordUsage(promptTokens, cachedTokens);
35
+ }
36
+ /**
37
+ * Get raw statistics
38
+ */
39
+ getStats() {
40
+ const result = this.store.load();
41
+ if (!result.success) {
42
+ return null;
43
+ }
44
+ return result.data.stats || null;
45
+ }
46
+ /**
47
+ * Calculate cache hit rate from last request
48
+ */
49
+ getLastCacheRate() {
50
+ const stats = this.getStats();
51
+ if (!stats || !stats.last_prompt_tokens || !stats.last_cached_tokens) {
52
+ return 0;
53
+ }
54
+ return Math.round((stats.last_cached_tokens / stats.last_prompt_tokens) * 100);
55
+ }
56
+ /**
57
+ * Calculate estimated cost savings
58
+ */
59
+ getEstimatedSavings() {
60
+ const stats = this.getStats();
61
+ if (!stats || !stats.total_tokens_saved) {
62
+ return 0;
63
+ }
64
+ // Savings = tokens_saved * (regular_price - cached_price)
65
+ const savingsPerToken = (PRICING.INPUT_PER_1K - PRICING.CACHED_PER_1K) / 1000;
66
+ return stats.total_tokens_saved * savingsPerToken;
67
+ }
68
+ /**
69
+ * Get formatted statistics for display
70
+ */
71
+ getFormattedStats() {
72
+ const stats = this.getStats();
73
+ if (!stats) {
74
+ return null;
75
+ }
76
+ const cacheRate = this.getLastCacheRate();
77
+ const tokensSaved = stats.total_tokens_saved || 0;
78
+ const usageCount = stats.usage_count || 0;
79
+ const estimatedSavings = this.getEstimatedSavings();
80
+ const lines = [
81
+ '📈 Cache Statistics',
82
+ '',
83
+ ` Usage count: ${usageCount}`,
84
+ ` Last cache rate: ${cacheRate}%`,
85
+ ` Tokens saved: ${tokensSaved.toLocaleString()}`,
86
+ ` Est. savings: $${estimatedSavings.toFixed(2)}`,
87
+ ];
88
+ if (stats.last_used_at) {
89
+ const lastUsed = new Date(stats.last_used_at);
90
+ lines.push(` Last used: ${lastUsed.toLocaleString()}`);
91
+ }
92
+ return {
93
+ text: lines.join('\n'),
94
+ cacheRate,
95
+ tokensSaved,
96
+ usageCount,
97
+ estimatedSavings,
98
+ };
99
+ }
100
+ /**
101
+ * Format a brief cache status line for verbose output
102
+ */
103
+ formatBriefStatus(promptTokens, cachedTokens) {
104
+ const rate = promptTokens > 0
105
+ ? Math.round((cachedTokens / promptTokens) * 100)
106
+ : 0;
107
+ return `cached: ${cachedTokens.toLocaleString()}/${promptTokens.toLocaleString()} tokens (${rate}% cache hit)`;
108
+ }
109
+ /**
110
+ * Check if caching appears to be working
111
+ * Returns a warning message if cache hits are consistently zero
112
+ */
113
+ checkCacheHealth() {
114
+ const stats = this.getStats();
115
+ if (!stats) {
116
+ return null;
117
+ }
118
+ // If we've had multiple uses but no cache hits, something might be wrong
119
+ if (stats.usage_count && stats.usage_count >= 3) {
120
+ if (!stats.total_tokens_saved || stats.total_tokens_saved === 0) {
121
+ return 'Warning: No cache hits detected after multiple uses. ' +
122
+ 'Consider running "ax memory refresh" to regenerate context.';
123
+ }
124
+ // Check for very low cache rate
125
+ const avgSavedPerUse = stats.total_tokens_saved / stats.usage_count;
126
+ if (avgSavedPerUse < 100) {
127
+ return 'Note: Cache hit rate is lower than expected. ' +
128
+ 'This may indicate context has changed frequently.';
129
+ }
130
+ }
131
+ return null;
132
+ }
133
+ /**
134
+ * Reset statistics (keeps memory content, only clears stats)
135
+ */
136
+ resetStats() {
137
+ const result = this.store.load();
138
+ if (!result.success) {
139
+ return false;
140
+ }
141
+ const memory = result.data;
142
+ memory.stats = undefined;
143
+ memory.updated_at = new Date().toISOString();
144
+ const saveResult = this.store.save(memory);
145
+ return saveResult.success;
146
+ }
147
+ }
148
+ /**
149
+ * Singleton instance
150
+ */
151
+ let defaultCollector = null;
152
+ /**
153
+ * Get the default stats collector instance
154
+ */
155
+ export function getStatsCollector(projectRoot) {
156
+ if (projectRoot) {
157
+ return new StatsCollector(projectRoot);
158
+ }
159
+ if (!defaultCollector) {
160
+ defaultCollector = new StatsCollector();
161
+ }
162
+ return defaultCollector;
163
+ }
164
+ /**
165
+ * Reset the default collector (mainly for testing)
166
+ */
167
+ export function resetDefaultCollector() {
168
+ defaultCollector = null;
169
+ }
170
+ //# sourceMappingURL=stats-collector.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stats-collector.js","sourceRoot":"","sources":["../../src/memory/stats-collector.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAmBlD;;;GAGG;AACH,MAAM,OAAO,GAAG;IACd,qCAAqC;IACrC,YAAY,EAAE,KAAK;IACnB,+CAA+C;IAC/C,aAAa,EAAE,KAAK;CACZ,CAAC;AAEX;;GAEG;AACH,MAAM,OAAO,cAAc;IACjB,KAAK,CAAe;IAE5B,YAAY,cAAsB,OAAO,CAAC,GAAG,EAAE;QAC7C,IAAI,CAAC,KAAK,GAAG,IAAI,YAAY,CAAC,WAAW,CAAC,CAAC;IAC7C,CAAC;IAED;;;;;OAKG;IACH,cAAc,CAAC,YAAoB,EAAE,YAAoB;QACvD,qCAAqC;QACrC,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,YAAY,EAAE,YAAY,CAAC,CAAC;IACrD,CAAC;IAED;;OAEG;IACH,QAAQ;QACN,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,C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