-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathindex.ts
More file actions
1235 lines (1192 loc) · 39.7 KB
/
index.ts
File metadata and controls
1235 lines (1192 loc) · 39.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Account } from "@/account"
import { Config } from "@/config/config"
import { Installation } from "@/installation"
import { Log } from "@/util/log"
import { createHash, randomUUID } from "crypto"
import fs from "fs"
import path from "path"
import os from "os"
const log = Log.create({ service: "telemetry" })
// altimate_change start — telemetry query reference for Azure App Insights (KQL)
/**
* Telemetry Module — Azure App Insights Integration
*
* QUERYING TELEMETRY DATA (KQL / Log Analytics):
*
* customDimensions → string fields (tool_name, model_id, provider_id, error_class, os, etc.)
* customMeasurements → numeric fields (tokens_input, cost, duration_ms, etc.)
*
* Serialization rules (see toAppInsightsEnvelopes):
* - typeof number → measurements map (customMeasurements)
* - typeof string → properties map (customDimensions)
* - typeof boolean → properties map (as "true"/"false")
* - typeof object → properties map (JSON.stringify)
* - session_id / project_id are lifted into envelope tags, not properties
* - cli_version is injected into every event's properties automatically
*
* Example KQL:
*
* // Token usage per model
* customEvents
* | where name == "generation"
* | extend model = tostring(customDimensions.model_id),
* tokens_in = todouble(customMeasurements.tokens_input),
* tokens_out = todouble(customMeasurements.tokens_output)
* | summarize avg(tokens_in), avg(tokens_out) by model
*
* // Error class distribution
* customEvents
* | where name == "core_failure"
* | extend err = tostring(customDimensions.error_class)
* | summarize count() by err
*/
// altimate_change end
export namespace Telemetry {
const FLUSH_INTERVAL_MS = 5_000
const MAX_BUFFER_SIZE = 200
const REQUEST_TIMEOUT_MS = 10_000
export type Event =
// altimate_change start — add os/arch/node_version for environment segmentation
| {
type: "session_start"
timestamp: number
session_id: string
model_id: string
provider_id: string
agent: string
project_id: string
os: string
arch: string
node_version: string
}
// altimate_change end
| {
type: "session_end"
timestamp: number
session_id: string
total_cost: number
total_tokens: number
tool_call_count: number
duration_ms: number
}
| {
type: "generation"
timestamp: number
session_id: string
message_id: string
model_id: string
provider_id: string
agent: string
finish_reason: string
cost: number
duration_ms: number
// Flat token fields — only present when data is available from the provider.
// No nested objects: Azure App Insights custom measures must be top-level numbers.
tokens_input: number
tokens_output: number
// altimate_change start — total input tokens including cached (for providers like Anthropic that exclude cache from tokens_input)
tokens_input_total?: number
// altimate_change end
tokens_reasoning?: number // only for reasoning models
tokens_cache_read?: number // only when a cached prompt was reused
tokens_cache_write?: number // only when a new cache entry was written
}
| {
type: "tool_call"
timestamp: number
session_id: string
message_id: string
tool_name: string
tool_type: "standard" | "mcp"
tool_category: string
status: "success" | "error"
duration_ms: number
sequence_index: number
previous_tool: string | null
input_signature?: string
error?: string
}
| {
type: "native_call"
timestamp: number
session_id: string
method: string
status: "success" | "error"
duration_ms: number
error?: string
}
| {
type: "error"
timestamp: number
session_id: string
error_name: string
error_message: string
context: string
}
| {
type: "command"
timestamp: number
session_id: string
command_name: string
command_source: "command" | "mcp" | "skill" | "unknown"
message_id: string
}
| {
type: "context_overflow_recovered"
timestamp: number
session_id: string
model_id: string
provider_id: string
tokens_used: number
}
| {
type: "compaction_triggered"
timestamp: number
session_id: string
trigger: "overflow_detection" | "error_recovery"
attempt: number
}
| {
type: "tool_outputs_pruned"
timestamp: number
session_id: string
count: number
tokens_pruned: number
}
| {
type: "auth_login"
timestamp: number
session_id: string
provider_id: string
method: "oauth" | "api_key"
status: "success" | "error"
error?: string
}
| {
type: "auth_logout"
timestamp: number
session_id: string
provider_id: string
}
| {
type: "mcp_server_status"
timestamp: number
session_id: string
server_name: string
transport: "stdio" | "sse" | "streamable-http"
status: "connected" | "disconnected" | "error"
error?: string
duration_ms?: number
}
| {
type: "provider_error"
timestamp: number
session_id: string
provider_id: string
model_id: string
error_type: string
error_message: string
http_status?: number
}
// DEPRECATED: Python engine eliminated. These event types are retained
// for backward compatibility with existing telemetry dashboards but
// are never fired by the native TypeScript implementation.
| {
type: "engine_started"
timestamp: number
session_id: string
engine_version: string
python_version: string
extras?: string
status: "started" | "restarted" | "upgraded"
duration_ms: number
}
| {
type: "engine_error"
timestamp: number
session_id: string
phase: "uv_download" | "venv_create" | "pip_install" | "startup" | "runtime"
error_message: string
}
| {
type: "upgrade_attempted"
timestamp: number
session_id: string
from_version: string
to_version: string
method: "npm" | "bun" | "brew" | "other"
status: "success" | "error"
error?: string
}
| {
type: "session_forked"
timestamp: number
session_id: string
parent_session_id: string
message_count: number
}
| {
type: "permission_denied"
timestamp: number
session_id: string
tool_name: string
tool_category: string
source: "user" | "config_rule"
}
| {
type: "doom_loop_detected"
timestamp: number
session_id: string
tool_name: string
repeat_count: number
}
| {
type: "environment_census"
timestamp: number
session_id: string
warehouse_types: string[]
warehouse_count: number
dbt_detected: boolean
dbt_adapter: string | null
dbt_model_count_bucket: string
dbt_source_count_bucket: string
dbt_test_count_bucket: string
// altimate_change start — dbt project fingerprint expansion
dbt_snapshot_count_bucket?: string
dbt_seed_count_bucket?: string
/** JSON-encoded Record<string, number> — count per materialization type */
dbt_materialization_dist?: string
dbt_macro_count_bucket?: string
// altimate_change end
connection_sources: string[]
mcp_server_count: number
skill_count: number
os: string
feature_flags: string[]
}
| {
type: "context_utilization"
timestamp: number
session_id: string
model_id: string
tokens_used: number
context_limit: number
utilization_pct: number
generation_number: number
cache_hit_ratio: number
}
| {
type: "agent_outcome"
timestamp: number
session_id: string
agent: string
tool_calls: number
generations: number
duration_ms: number
cost: number
compactions: number
outcome: "completed" | "abandoned" | "aborted" | "error"
}
| {
type: "error_recovered"
timestamp: number
session_id: string
error_type: string
recovery_strategy: string
attempts: number
recovered: boolean
duration_ms: number
}
| {
type: "mcp_server_census"
timestamp: number
session_id: string
server_name: string
transport: "stdio" | "sse" | "streamable-http"
tool_count: number
resource_count: number
}
| {
type: "mcp_discovery"
timestamp: number
session_id: string
server_count: number
server_names: string[]
sources: string[]
}
| {
type: "memory_operation"
timestamp: number
session_id: string
operation: "write" | "delete"
scope: "global" | "project"
block_id: string
is_update: boolean
duplicate_count: number
tags_count: number
}
| {
type: "memory_injection"
timestamp: number
session_id: string
block_count: number
total_chars: number
budget: number
scopes_used: string[]
}
| {
type: "warehouse_connect"
timestamp: number
session_id: string
warehouse_type: string
auth_method: string
success: boolean
duration_ms: number
error?: string
error_category?: string
}
| {
type: "warehouse_query"
timestamp: number
session_id: string
warehouse_type: string
query_type: string
success: boolean
duration_ms: number
row_count: number
truncated: boolean
error?: string
error_category?: string
}
| {
type: "warehouse_introspection"
timestamp: number
session_id: string
warehouse_type: string
operation: string
success: boolean
duration_ms: number
result_count: number
error?: string
}
| {
type: "warehouse_discovery"
timestamp: number
session_id: string
source: string
connections_found: number
warehouse_types: string[]
}
| {
type: "warehouse_census"
timestamp: number
session_id: string
total_connections: number
warehouse_types: string[]
connection_sources: string[]
has_ssh_tunnel: boolean
has_keychain: boolean
}
| {
type: "skill_used"
timestamp: number
session_id: string
message_id: string
skill_name: string
skill_source: "builtin" | "global" | "project"
duration_ms: number
// altimate_change start — skill trigger classification for discovery analytics
trigger: "user_command" | "llm_selected" | "auto_suggested" | "unknown"
// altimate_change end
has_followups: boolean
followup_count: number
}
// altimate_change start — first_launch event for new user counting (privacy-safe: only version + machine_id)
| {
type: "first_launch"
timestamp: number
session_id: string
version: string
is_upgrade: boolean
}
// altimate_change end
// altimate_change start — telemetry for skill management operations
| {
type: "skill_created"
timestamp: number
session_id: string
skill_name: string
language: string
source: "cli" | "tui"
}
| {
type: "skill_installed"
timestamp: number
session_id: string
install_source: string
skill_count: number
skill_names: string[]
source: "cli" | "tui"
}
| {
type: "skill_removed"
timestamp: number
session_id: string
skill_name: string
source: "cli" | "tui"
}
// altimate_change end
// altimate_change start — plan refinement telemetry event
| {
type: "plan_revision"
timestamp: number
session_id: string
revision_number: number
action: "refine" | "approve" | "reject" | "cap_reached"
}
// altimate_change end
| {
type: "sql_execute_failure"
timestamp: number
session_id: string
warehouse_type: string
query_type: string
error_message: string
masked_sql: string
duration_ms: number
}
// altimate_change start — feature_suggestion event for post-connect and progressive disclosure tracking
| {
type: "feature_suggestion"
timestamp: number
session_id: string
suggestion_type: "post_warehouse_connect" | "dbt_detected" | "progressive_disclosure"
suggestions_shown: string[]
warehouse_type?: string
}
// altimate_change end
| {
type: "core_failure"
timestamp: number
session_id: string
tool_name: string
tool_category: string
error_class: "parse_error" | "connection" | "timeout" | "validation" | "internal" | "permission" | "http_error" | "file_not_found" | "edit_mismatch" | "not_configured" | "resource_exhausted" | "unknown"
error_message: string
input_signature: string
masked_args?: string
duration_ms: number
}
// altimate_change start — sql quality telemetry for issue prevention metrics
| {
type: "sql_quality"
timestamp: number
session_id: string
tool_name: string
tool_category: string
finding_count: number
/** JSON-encoded Record<string, number> — count per issue category */
by_category: string
has_schema: boolean
dialect?: string
duration_ms: number
}
// implicit quality signal for task outcome intelligence
| {
type: "task_outcome_signal"
timestamp: number
session_id: string
/** Behavioral signal derived from session outcome patterns */
signal: "accepted" | "error" | "abandoned" | "cancelled"
/** Total tool calls in this loop() invocation */
tool_count: number
/** Number of LLM generation steps in this loop() invocation */
step_count: number
/** Total session wall-clock duration in milliseconds */
duration_ms: number
/** Last tool category the agent used (or "none") */
last_tool_category: string
}
// task intent classification for understanding DE problem distribution
| {
type: "task_classified"
timestamp: number
session_id: string
/** Classified intent category */
intent:
| "debug_dbt"
| "write_sql"
| "optimize_query"
| "build_model"
| "analyze_lineage"
| "explore_schema"
| "migrate_sql"
| "manage_warehouse"
| "finops"
| "general"
/** Keyword match confidence: 1.0 for strong match, 0.5 for weak */
confidence: number
/** Detected warehouse type from fingerprint (or "unknown") */
warehouse_type: string
}
// schema complexity signal — structural metrics from warehouse introspection
| {
type: "schema_complexity"
timestamp: number
session_id: string
warehouse_type: string
/** Bucketed table count */
table_count_bucket: string
/** Bucketed total column count across all tables */
column_count_bucket: string
/** Bucketed schema count */
schema_count_bucket: string
/** Average columns per table (rounded to integer) */
avg_columns_per_table: number
}
// sql structure fingerprint — AST shape without content
| {
type: "sql_fingerprint"
timestamp: number
session_id: string
/** JSON-encoded statement types, e.g. ["SELECT"] */
statement_types: string
/** Broad categories, e.g. ["query"] */
categories: string
/** Number of tables referenced */
table_count: number
/** Number of functions used */
function_count: number
/** Whether the query has subqueries */
has_subqueries: boolean
/** Whether the query uses aggregation */
has_aggregation: boolean
/** Whether the query uses window functions */
has_window_functions: boolean
/** AST node count — proxy for complexity */
node_count: number
}
// error pattern fingerprint — hashed error grouping with recovery data
| {
type: "error_fingerprint"
timestamp: number
session_id: string
/** SHA256 hash of normalized (masked) error message for grouping */
error_hash: string
/** Classification from classifyError() */
error_class: string
/** Tool that produced the error */
tool_name: string
/** Tool category */
tool_category: string
/** Whether a subsequent tool call succeeded (error was recovered) */
recovery_successful: boolean
/** Tool that succeeded after the error (if recovered) */
recovery_tool: string
}
// tool chain effectiveness — aggregated tool sequence + outcome at session end
| {
type: "tool_chain_outcome"
timestamp: number
session_id: string
/** JSON-encoded ordered tool names (capped at 50) */
chain: string
/** Number of tools in the chain */
chain_length: number
/** Whether any tool call errored */
had_errors: boolean
/** Number of errors followed by successful tool calls */
error_recovery_count: number
/** Final session outcome */
final_outcome: string
/** Total session duration in ms */
total_duration_ms: number
/** Total LLM cost */
total_cost: number
}
// altimate_change end
/** SHA256 hash a masked error message for anonymous grouping. */
export function hashError(maskedMessage: string): string {
return createHash("sha256").update(maskedMessage).digest("hex").slice(0, 16)
}
/** Classify user intent from the first message text.
* Pure regex/keyword matcher — zero LLM cost, <1ms. */
export function classifyTaskIntent(
text: string,
): { intent: string; confidence: number } {
const lower = text.slice(0, 2000).toLowerCase()
// Order matters: more specific patterns first
const patterns: Array<{ intent: string; strong: RegExp[]; weak: RegExp[] }> = [
{
intent: "debug_dbt",
strong: [/dbt\s+.*?(error|fail|bug|issue|broken|fix|debug|not\s+work)/],
weak: [/dbt\s+(run|build|test|compile|parse)/, /dbt_project/, /ref\s*\(/, /source\s*\(/],
},
{
intent: "build_model",
strong: [/(?:create|build|write|add|new)\s+.*?(?:dbt\s+)?model/, /(?:create|build)\s+.*?(?:staging|mart|dim|fact)/],
weak: [/\bmodel\b/, /materialization/, /incremental/],
},
{
intent: "optimize_query",
strong: [/optimiz|performance|slow\s+query|speed\s+up|make.*faster|too\s+slow|query\s+cost/],
weak: [/index|partition|cluster|explain\s+plan/],
},
{
intent: "write_sql",
strong: [/(?:write|create|build|generate)\s+(?:a\s+)?(?:sql|query)/, /(?:write|create)\s+(?:a\s+)?(?:select|insert|update|delete)/],
weak: [/\bsql\b/, /\bquery\b/, /\bjoin\b/, /\bwhere\b/],
},
{
intent: "analyze_lineage",
strong: [/lineage|upstream|downstream|dependency|depends\s+on|impact\s+analysis/],
weak: [/dag|graph|flow|trace/],
},
{
intent: "explore_schema",
strong: [/(?:show|list|describe|inspect|explore)\s+.*?(?:schema|tables?|columns?|database)/, /what\s+.*?(?:tables|columns|schemas)/],
weak: [/\bschema\b/, /\btable\b/, /\bcolumn\b/, /introspect/],
},
{
intent: "migrate_sql",
strong: [/migrat|convert.*(?:to|from)\s+.*?(?:snowflake|bigquery|postgres|redshift|databricks)/, /translate.*(?:sql|dialect)/],
weak: [/dialect|transpile|port\s+(?:to|from)/],
},
{
intent: "manage_warehouse",
strong: [/(?:connect|setup|configure|add|test)\s+.*?(?:warehouse|connection|database)/, /warehouse.*(?:config|setting)/],
weak: [/\bwarehouse\b/, /connection\s+string/, /\bcredentials\b/],
},
{
intent: "finops",
strong: [/cost|spend|bill|credits|usage|expensive\s+quer|warehouse\s+size/],
weak: [/resource|utilization|idle/],
},
]
for (const { intent, strong, weak } of patterns) {
if (strong.some((r) => r.test(lower))) return { intent, confidence: 1.0 }
}
for (const { intent, weak } of patterns) {
if (weak.some((r) => r.test(lower))) return { intent, confidence: 0.5 }
}
return { intent: "general", confidence: 1.0 }
}
/** Derive a quality signal from the agent outcome.
* Exported so tests can verify the derivation logic without
* duplicating the implementation. */
export function deriveQualitySignal(
outcome: "completed" | "abandoned" | "aborted" | "error",
): "accepted" | "error" | "abandoned" | "cancelled" {
switch (outcome) {
case "abandoned":
return "abandoned"
case "aborted":
return "cancelled"
case "error":
return "error"
case "completed":
return "accepted"
}
}
// altimate_change start — expanded error classification patterns for better triage
// Order matters: earlier patterns take priority. Use specific phrases, not
// single words, to avoid false positives (e.g., "connection refused" not "connection").
const ERROR_PATTERNS: Array<{
class: Telemetry.Event & { type: "core_failure" } extends { error_class: infer C } ? C : never
keywords: string[]
}> = [
{ class: "parse_error", keywords: ["parse", "syntax", "binder", "unexpected token", "sqlglot"] },
{
class: "connection",
keywords: [
"econnrefused",
"enotfound",
"econnreset",
"connection refused",
"connection reset",
"connection closed",
"connect failed",
"connect etimedout",
"socket hang up",
"sasl",
"scram",
"password must be",
],
},
// altimate_change start — split not_configured out of connection for clearer triage
{
class: "not_configured",
keywords: [
"no warehouse configured",
"driver not installed",
"not found. available:",
"unsupported database type",
"warehouse not configured",
"connection not configured",
],
},
// altimate_change end
// altimate_change start — file_not_found class for file system errors
{
class: "file_not_found",
keywords: [
"file not found",
"no such file",
"enoent",
"directory not found",
"path not found",
"file does not exist",
],
},
// altimate_change end
// altimate_change start — edit_mismatch class for edit tool failures
{
class: "edit_mismatch",
keywords: [
"could not find oldstring",
"no changes to apply",
"oldstring and newstring are identical",
],
},
// altimate_change end
{ class: "timeout", keywords: ["timeout", "etimedout", "bridge timeout", "timed out"] },
{ class: "permission", keywords: ["permission", "access denied", "permission denied", "unauthorized", "forbidden", "authentication"] },
{
class: "validation",
keywords: [
"invalid params",
"invalid",
"missing",
"required",
"must read file",
"has been modified since",
"does not exist",
"before overwriting",
],
},
{ class: "internal", keywords: ["internal", "assertion"] },
// altimate_change start — resource_exhausted class for OOM/quota errors
{
class: "resource_exhausted",
keywords: [
"out of memory",
"resource limit",
"quota exceeded",
"disk i/o",
"enomem",
"heap out of memory",
],
},
// altimate_change end
{
class: "http_error",
keywords: ["status code: 4", "status code: 5", "request failed with status"],
},
]
// altimate_change end
export function classifyError(
message: string,
): Telemetry.Event & { type: "core_failure" } extends { error_class: infer C } ? C : never {
const lower = message.toLowerCase()
for (const { class: cls, keywords } of ERROR_PATTERNS) {
if (keywords.some((kw) => lower.includes(kw))) return cls
}
return "unknown"
}
export function computeInputSignature(args: Record<string, unknown>): string {
const sig: Record<string, string> = {}
for (const [k, v] of Object.entries(args)) {
// altimate_change start — redact sensitive keys in input signatures
if (isSensitiveKey(k)) {
sig[k] = "****"
continue
}
// altimate_change end
if (v === null || v === undefined) {
sig[k] = "null"
} else if (typeof v === "string") {
sig[k] = `string:${v.length}`
} else if (typeof v === "number") {
sig[k] = "number"
} else if (typeof v === "boolean") {
sig[k] = "boolean"
} else if (Array.isArray(v)) {
sig[k] = `array:${v.length}`
} else if (typeof v === "object") {
sig[k] = `object:${Object.keys(v).length}`
} else {
sig[k] = typeof v
}
}
const result = JSON.stringify(sig)
if (result.length <= 1000) return result
// Drop keys from the end until the JSON fits, preserving valid JSON structure
const keys = Object.keys(sig)
while (keys.length > 0) {
keys.pop()
const truncated: Record<string, string> = {}
for (const k of keys) truncated[k] = sig[k]
truncated["..."] = `${Object.keys(sig).length - keys.length} more`
const out = JSON.stringify(truncated)
if (out.length <= 1000) return out
}
return JSON.stringify({ "...": `${Object.keys(sig).length} keys` })
}
// Mirrors altimate-sdk (Rust) SENSITIVE_KEYS — keep in sync.
const SENSITIVE_KEYS: string[] = [
"key",
"api_key",
"apikey",
"apiKey",
"token",
"access_token",
"refresh_token",
"secret",
"secret_key",
"password",
"passwd",
"pwd",
"credential",
"credentials",
"authorization",
"auth",
"signature",
"sig",
"private_key",
"connection_string",
// camelCase variants not caught by prefix/suffix matching
"authtoken",
"accesstoken",
"refreshtoken",
"bearertoken",
"jwttoken",
"jwtsecret",
"clientsecret",
"appsecret",
]
function isSensitiveKey(key: string): boolean {
const lower = key.toLowerCase()
return SENSITIVE_KEYS.some((k) => lower === k || lower.endsWith(`_${k}`) || lower.startsWith(`${k}_`))
}
export function maskString(s: string): string {
return s
.replace(/'(?:[^'\\]|\\.)*'/g, "?")
.replace(/"(?:[^"\\]|\\.)*"/g, "?")
.replace(/\s+/g, " ")
.trim()
}
function maskValue(value: unknown, key?: string): unknown {
if (key && isSensitiveKey(key)) return "****"
if (typeof value === "string") return maskString(value)
if (Array.isArray(value)) return value.map((v) => maskValue(v, key))
if (value !== null && typeof value === "object") {
const masked: Record<string, unknown> = {}
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
masked[k] = maskValue(v, k)
}
return masked
}
return value
}
/** PII-mask tool arguments for failure telemetry.
* Mirrors altimate-sdk mask_value: sensitive keys → "****",
* string literals in SQL → ?, whitespace collapsed. Truncates to 2000 chars. */
export function maskArgs(args: Record<string, unknown>): string {
const masked: Record<string, unknown> = {}
for (const [k, v] of Object.entries(args)) {
masked[k] = maskValue(v, k)
}
const result = JSON.stringify(masked)
if (result.length <= 2000) return result
// Drop keys from the end until valid JSON fits, same approach as computeInputSignature
const keys = Object.keys(masked)
while (keys.length > 0) {
keys.pop()
const truncated: Record<string, unknown> = {}
for (const k of keys) truncated[k] = masked[k]
truncated["..."] = `${Object.keys(masked).length - keys.length} more`
const out = JSON.stringify(truncated)
if (out.length <= 2000) return out
}
return JSON.stringify({ "...": `${Object.keys(masked).length} keys` })
}
const FILE_TOOLS = new Set(["read", "write", "edit", "glob", "grep", "bash"])
// Order matters: more specific patterns (e.g. "warehouse_usage") are checked
// before broader ones (e.g. "warehouse") to avoid miscategorization.
const CATEGORY_PATTERNS: Array<{ category: string; keywords: string[] }> = [
{ category: "finops", keywords: ["cost", "finops", "warehouse_usage"] },
{ category: "sql", keywords: ["sql", "query"] },
{ category: "schema", keywords: ["schema", "column", "table"] },
{ category: "dbt", keywords: ["dbt"] },
{ category: "warehouse", keywords: ["warehouse", "connection"] },
{ category: "lineage", keywords: ["lineage", "dag"] },
{ category: "memory", keywords: ["memory"] },
]
export function categorizeToolName(name: string, type: "standard" | "mcp"): string {
if (type === "mcp") return "mcp"
const n = name.toLowerCase()
if (FILE_TOOLS.has(n)) return "file"
for (const { category, keywords } of CATEGORY_PATTERNS) {
if (keywords.some((kw) => n.includes(kw))) return category
}
return "standard"
}
// altimate_change start — classify how a skill was triggered for discovery analytics
export function classifySkillTrigger(extra?: { [key: string]: any }): "user_command" | "llm_selected" | "auto_suggested" | "unknown" {
if (!extra) return "llm_selected"
if (extra.trigger === "user_command") return "user_command"
if (extra.trigger === "auto_suggested") return "auto_suggested"
if (extra.trigger === "llm_selected") return "llm_selected"
return "unknown"
}
// altimate_change end
export function bucketCount(n: number): string {
if (n <= 0) return "0"
if (n <= 10) return "1-10"
if (n <= 50) return "10-50"
if (n <= 200) return "50-200"
return "200+"
}
type AppInsightsConfig = {
iKey: string
endpoint: string // e.g. https://xxx.applicationinsights.azure.com/v2/track
}
let enabled = false
let buffer: Event[] = []
let flushTimer: ReturnType<typeof setInterval> | undefined
let userEmail = ""
let machineId = ""
let sessionId = ""
let projectId = ""
let appInsights: AppInsightsConfig | undefined
let droppedEvents = 0
let initPromise: Promise<void> | undefined
let initDone = false
function parseConnectionString(cs: string): AppInsightsConfig | undefined {
const parts: Record<string, string> = {}
for (const segment of cs.split(";")) {
const idx = segment.indexOf("=")
if (idx === -1) continue
parts[segment.slice(0, idx).trim()] = segment.slice(idx + 1).trim()
}
const iKey = parts["InstrumentationKey"]
const ingestionEndpoint = parts["IngestionEndpoint"]
if (!iKey || !ingestionEndpoint) return undefined
const base = ingestionEndpoint.endsWith("/") ? ingestionEndpoint : ingestionEndpoint + "/"