-
Notifications
You must be signed in to change notification settings - Fork 9.7k
Expand file tree
/
Copy pathvela.ts
More file actions
1248 lines (1169 loc) · 42.4 KB
/
Copy pathvela.ts
File metadata and controls
1248 lines (1169 loc) · 42.4 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 { spawn, type ChildProcess } from 'node:child_process';
import { createHash } from 'node:crypto';
import { existsSync, readFileSync, statSync, writeFileSync } from 'node:fs';
import { homedir } from 'node:os';
import path from 'node:path';
import { createCommandInvocation } from '@open-design/platform';
import type {
AmrEntryAttribution,
TrackingAmrEntrySource,
TrackingPageName,
} from '@open-design/contracts/analytics';
import { resolveAgentLaunch } from '../runtimes/launch.js';
import { spawnEnvForAgent } from '../runtimes/env.js';
import { getAgentDef } from '../runtimes/registry.js';
import { resolveAmrProfile } from './vela-profile.js';
export { resolveAmrProfile } from './vela-profile.js';
const AMR_ENTRY_SOURCES: ReadonlySet<TrackingAmrEntrySource> = new Set([
'onboarding_amr_card',
'onboarding_amr_sign_in_continue',
'inline_model_switcher_amr_row',
'settings_amr_agent_card',
'settings_amr_authorize',
'settings_amr_console',
'settings_amr_install',
'avatar_amr_console',
'handoff_amr_website',
'chat_error_authorize_retry',
'chat_error_recharge',
'chat_error_upgrade',
'chat_balance_gate_upgrade',
'home_balance_gate_upgrade',
'chat_low_balance_warn_recharge',
'home_low_balance_warn_recharge',
'chat_balance_gate_sign_in',
'home_balance_gate_sign_in',
'chat_error_switch_retry_card',
'generation_preview_authorize_retry',
'generation_preview_recharge',
'generation_preview_switch_retry_card',
'settings_amr_upgrade',
'inline_amr_upgrade',
'avatar_amr_upgrade',
'avatar_amr_agent_card',
]);
const AMR_ONBOARDING_PROFILE_SOURCES: ReadonlySet<TrackingAmrEntrySource> = new Set([
'onboarding_amr_card',
'onboarding_amr_sign_in_continue',
]);
type AmrEntrySourcePageName = Extract<
TrackingPageName,
'onboarding' | 'chat_panel' | 'settings' | 'file_manager' | 'artifact' | 'home'
>;
const AMR_ENTRY_SOURCE_PAGES: ReadonlySet<AmrEntrySourcePageName> = new Set([
'onboarding',
'chat_panel',
'settings',
'file_manager',
'artifact',
'home',
]);
const AMR_ENTRY_SOURCE_PAGE_BY_SOURCE: Record<
TrackingAmrEntrySource,
AmrEntrySourcePageName
> = {
onboarding_amr_card: 'onboarding',
onboarding_amr_sign_in_continue: 'onboarding',
inline_model_switcher_amr_row: 'chat_panel',
settings_amr_agent_card: 'settings',
settings_amr_authorize: 'settings',
settings_amr_console: 'settings',
settings_amr_install: 'settings',
avatar_amr_console: 'chat_panel',
handoff_amr_website: 'artifact',
chat_error_authorize_retry: 'chat_panel',
chat_error_recharge: 'chat_panel',
chat_error_upgrade: 'chat_panel',
chat_balance_gate_upgrade: 'chat_panel',
home_balance_gate_upgrade: 'home',
chat_low_balance_warn_recharge: 'chat_panel',
home_low_balance_warn_recharge: 'home',
chat_balance_gate_sign_in: 'chat_panel',
home_balance_gate_sign_in: 'home',
chat_error_switch_retry_card: 'chat_panel',
generation_preview_authorize_retry: 'file_manager',
generation_preview_recharge: 'file_manager',
generation_preview_switch_retry_card: 'file_manager',
settings_amr_upgrade: 'settings',
inline_amr_upgrade: 'chat_panel',
avatar_amr_upgrade: 'chat_panel',
avatar_amr_agent_card: 'chat_panel',
};
const AMR_ANALYTICS_EVENTS_URL =
'https://amr-api.open-design.ai/api/v1/analytics/events';
const AMR_ANALYTICS_TIMEOUT_MS = 1500;
const OD_DEVICE_ID_MAX_LENGTH = 128;
type AmrAnalyticsEnv = 'local' | 'test' | 'staging' | 'production';
const AMR_ANALYTICS_ENVS: ReadonlySet<AmrAnalyticsEnv> = new Set([
'local',
'test',
'staging',
'production',
]);
export interface AmrEntryAnalyticsPayload {
pageName: 'open_design';
sourcePageName: AmrEntrySourcePageName;
area: 'amr_entry';
element: TrackingAmrEntrySource;
action: 'click_amr_entry';
entryId: string;
sourceProduct: 'open_design';
sourceDetail: TrackingAmrEntrySource;
entryOccurredAt: string;
// Optional self-reported onboarding profile, forwarded to AMR for paid-
// conversion segmentation. Open strings (not a union) so a new onboarding
// option never forces a contract bump on either side. useCase is multi-select.
odRole?: string;
odOrgSize?: string;
odUseCase?: string[];
odSource?: string;
}
export interface AmrOnboardingProfileAnalyticsPayload {
pageName: 'open_design';
sourcePageName: 'onboarding';
area: 'onboarding';
element: 'about_you_submit';
action: 'submit_profile';
entryId: string;
sourceProduct: 'open_design';
sourceDetail: TrackingAmrEntrySource;
entryOccurredAt: string;
profileOccurredAt: string;
odDeviceId?: string;
odRole?: string;
odOrgSize?: string;
odUseCase?: string[];
odSource?: string;
}
export interface AmrEntryAnalyticsContext {
deviceId?: string | null;
sessionId?: string | null;
locale?: string | null;
}
interface FetchResponseLike {
ok: boolean;
status: number;
}
type FetchLike = (
input: string,
init: {
method: 'POST';
headers: Record<string, string>;
body: string;
signal?: AbortSignal;
},
) => Promise<FetchResponseLike>;
export interface MirrorAmrEntryAnalyticsDeps {
analyticsContext?: AmrEntryAnalyticsContext | null;
appVersion?: string | null;
env?: NodeJS.ProcessEnv;
fetchImpl?: FetchLike;
}
export interface MirrorAmrEntryAnalyticsResult {
mirrored: boolean;
status?: number;
error?: string;
}
export interface VelaUser {
id: string;
email: string;
name?: string;
image?: string | null;
plan?: string;
/**
* Wallet balance (USD, string), surfaced live from the control-plane
* `/api/v1/me` endpoint. `null` when unknown (lookup failed, not yet warmed,
* or upstream does not return it). Absent on stale config-only reads.
*/
balanceUsd?: string | null;
}
export interface VelaLoginStatus {
loggedIn: boolean;
loginInFlight: boolean;
profile: string;
user: VelaUser | null;
/**
* Live billing projection (plan tier + wallet balance) for the signed-in
* account. Kept SEPARATE from `user` so env-backed sessions (where `user` is
* null) can surface plan/balance without fabricating a blank identity, and so
* `user.id === null` keeps meaning "no account identity available" for
* analytics and other callers. Absent until the live summary resolves;
* absent means unknown / hidden.
*/
account?: VelaLiveAccount;
configPath: string;
/**
* Device-authorization URL parsed from `vela login` stdout, surfaced so the
* user can complete sign-in manually when the browser did not auto-open.
* Present only while a login is in flight and after vela has printed it.
*/
activationUrl?: string;
/** Device-authorization user code printed alongside the activation URL. */
userCode?: string;
/** True when vela warned it could not open the browser automatically. */
browserOpenFailed?: boolean;
}
export interface VelaLoginActivation {
activationUrl: string | null;
userCode: string | null;
browserOpenFailed: boolean;
}
// `vela login` is a device-authorization flow. Before it best-effort opens the
// browser it prints, to stdout, the exact lines:
//
// Open this URL to continue:
// <activation-url>
//
// Code: <user-code>
//
// and, when the auto-open fails, warns on stderr "could not open browser
// automatically: …" (see apps/cli/internal/commands/login.go in the vela repo).
// The daemon spawns vela login headless, so this parser recovers the URL/code/
// warning from the captured streams to surface them to the user. Pure so the
// extraction rules stay unit-testable against vela's literal output format.
export function parseVelaLoginActivation(
stdout: string,
stderr: string,
): VelaLoginActivation {
const urlMatch = /Open this URL to continue:\s*\r?\n\s*(\S+)/i.exec(stdout);
// Anchor on a line start so a `user_code=` query param inside the URL is not
// mistaken for the dedicated `Code:` line.
const codeMatch = /^[^\S\r\n]*Code:\s*(\S+)/im.exec(stdout);
return {
activationUrl: urlMatch?.[1] ?? null,
userCode: codeMatch?.[1] ?? null,
browserOpenFailed: /could not open browser automatically/i.test(stderr),
};
}
export interface VelaCredentialRevision {
authSource: 'env' | 'file' | 'none';
profile: string;
loggedIn: boolean;
userId: string;
userEmail: string;
configMtimeMs: number | null;
/**
* Non-secret fingerprint of the configured AMR env credentials
* (`VELA_RUNTIME_KEY` / `VELA_LINK_URL`, which can come from `agentCliEnv.amr`
* in app-config, not just process env). Env-backed sessions report
* `user: null`, so without this an account switch that only rewrites the
* Settings-backed env (leaving `~/.amr/config.json` untouched) would reuse the
* previous account's cached plan/balance. Empty for non-env auth.
*/
credentialFingerprint: string;
}
export interface VelaControlApiContext {
profile: string;
apiUrl: string;
controlKey: string;
user: VelaUser | null;
configMtimeMs: number | null;
}
export interface VelaControlApiContext {
profile: string;
apiUrl: string;
controlKey: string;
user: VelaUser | null;
configMtimeMs: number | null;
}
interface VelaProfileShape {
controlKey?: string;
runtimeKey?: string;
apiUrl?: string;
linkUrl?: string;
user?: VelaUser | null;
}
interface VelaConfigFileShape {
profiles?: Record<string, VelaProfileShape>;
}
export function mergeVelaEnv(
env: NodeJS.ProcessEnv = process.env,
configuredEnv: Record<string, string> = {},
): NodeJS.ProcessEnv {
return {
...env,
...configuredEnv,
};
}
function configDir(): string {
return path.join(homedir(), '.amr');
}
export function amrConfigPath(): string {
return path.join(configDir(), 'config.json');
}
function readConfigFile(): VelaConfigFileShape | null {
const file = amrConfigPath();
if (!existsSync(file)) return null;
try {
const data = readFileSync(file, 'utf8');
const parsed = JSON.parse(data) as unknown;
if (!parsed || typeof parsed !== 'object') return null;
return parsed as VelaConfigFileShape;
} catch {
return null;
}
}
export function readVelaLoginStatus(
env: NodeJS.ProcessEnv = process.env,
configuredEnv: Record<string, string> = {},
): VelaLoginStatus {
const mergedEnv = mergeVelaEnv(env, configuredEnv);
const profile = resolveAmrProfile(mergedEnv);
const configPath = amrConfigPath();
const loginInFlight = isVelaLoginInFlight();
// Only meaningful while signing in (loggedIn becomes true once vela writes the
// runtime key); empty otherwise so completed sessions don't echo a stale URL.
const activationFields: Partial<VelaLoginStatus> =
loginInFlight && activeLoginActivation
? {
...(activeLoginActivation.activationUrl
? { activationUrl: activeLoginActivation.activationUrl }
: {}),
...(activeLoginActivation.userCode
? { userCode: activeLoginActivation.userCode }
: {}),
...(activeLoginActivation.browserOpenFailed
? { browserOpenFailed: true }
: {}),
}
: {};
const runtimeKey = mergedEnv.VELA_RUNTIME_KEY?.trim() ?? '';
const linkUrl = mergedEnv.VELA_LINK_URL?.trim() ?? '';
if (runtimeKey && linkUrl) {
return { loggedIn: true, loginInFlight, profile, user: null, configPath };
}
const file = readConfigFile();
const stored = file?.profiles?.[profile];
const storedRuntimeKey = stored?.runtimeKey?.trim() ?? '';
if (!storedRuntimeKey) {
return {
loggedIn: false,
loginInFlight,
profile,
user: null,
configPath,
...activationFields,
};
}
const rawUser = stored?.user ?? null;
const user: VelaUser | null = rawUser
? {
id: typeof rawUser.id === 'string' ? rawUser.id : '',
email: typeof rawUser.email === 'string' ? rawUser.email : '',
...(typeof rawUser.name === 'string' ? { name: rawUser.name } : {}),
...(typeof rawUser.image === 'string' ? { image: rawUser.image } : {}),
...(typeof rawUser.plan === 'string' ? { plan: rawUser.plan } : {}),
}
: null;
return { loggedIn: true, loginInFlight, profile, user, configPath };
}
/**
* Live account fields (plan tier + wallet balance) sourced from the vela CLI
* (`vela billing summary`). Cached separately from the config-only
* {@link readVelaLoginStatus} read so the status route can merge live data
* without blocking: the route reads this cache synchronously and triggers a
* background CLI refresh for the next poll. The CLI spawn itself lives in the
* route layer (which already resolves the vela launch path for models).
*/
export interface VelaLiveAccount {
plan?: string;
balanceUsd?: string | null;
}
const liveAccountCache = new Map<string, VelaLiveAccount>();
const liveAccountFetchedAt = new Map<string, number>();
const LIVE_ACCOUNT_TTL_MS = 60_000;
/**
* Cache key for the live account. Derived from the full credential revision
* (auth source + profile + signed-in user + config mtime), NOT just the
* profile — so a logout or an account switch on the same profile produces a
* fresh key and the previous account's plan/balance can never leak into a new
* session before the background refresh completes.
*/
export function velaLiveAccountCacheKey(
revision: VelaCredentialRevision,
): string {
return [
revision.authSource,
revision.profile,
revision.loggedIn ? '1' : '0',
revision.userId,
revision.configMtimeMs ?? '',
revision.credentialFingerprint,
].join('|');
}
/** Synchronous, non-blocking read of the most recent live-account projection. */
export function peekVelaLiveAccount(cacheKey: string): VelaLiveAccount | null {
return liveAccountCache.get(cacheKey) ?? null;
}
/**
* TTL gate for the background refresh. Returns true (and records the attempt)
* at most once per cache key per {@link LIVE_ACCOUNT_TTL_MS}, so concurrent
* status polls don't all spawn the CLI.
*/
export function shouldRefreshVelaLiveAccount(cacheKey: string): boolean {
const last = liveAccountFetchedAt.get(cacheKey) ?? 0;
if (Date.now() - last < LIVE_ACCOUNT_TTL_MS) return false;
liveAccountFetchedAt.set(cacheKey, Date.now());
return true;
}
/** Store a freshly fetched live-account projection. */
export function setVelaLiveAccount(
cacheKey: string,
account: VelaLiveAccount,
): void {
liveAccountCache.set(cacheKey, account);
// Stamp the fetch time so the warm-path TTL gate doesn't immediately trigger
// a redundant refresh right after a (blocking) cold fetch populated the cache.
liveAccountFetchedAt.set(cacheKey, Date.now());
}
/** Clear the refresh throttle so a failed fetch can retry on the next poll. */
export function clearVelaLiveAccountRefreshThrottle(cacheKey: string): void {
liveAccountFetchedAt.delete(cacheKey);
}
/**
* Drop every cached live-account projection + throttle. Call on logout so a
* subsequent login can never surface the signed-out account's plan or balance.
*/
export function clearAllVelaLiveAccounts(): void {
liveAccountCache.clear();
liveAccountFetchedAt.clear();
}
/**
* Attach a fetched live account (plan tier + wallet balance) to a login status
* on the dedicated {@link VelaLoginStatus.account} field. Deliberately does NOT
* touch `status.user`: env-backed sessions keep `user: null` (no fabricated
* blank identity), and the billing projection rides on its own field so every
* surface can read plan/balance uniformly. No-op when signed out or when there
* is no account to apply.
*/
export function applyVelaLiveAccount(
status: VelaLoginStatus,
account: VelaLiveAccount | null,
): void {
if (!status.loggedIn || !account) return;
status.account = account;
}
export function readVelaCredentialRevision(
env: NodeJS.ProcessEnv = process.env,
configuredEnv: Record<string, string> = {},
): VelaCredentialRevision {
const mergedEnv = mergeVelaEnv(env, configuredEnv);
const status = readVelaLoginStatus(env, configuredEnv);
const hasEnvCredentials =
(mergedEnv.VELA_RUNTIME_KEY?.trim() ?? '').length > 0 &&
(mergedEnv.VELA_LINK_URL?.trim() ?? '').length > 0;
// One-way hash (never the raw key) so the cache key distinguishes env-backed
// accounts whose only difference is the configured runtime credential.
const credentialFingerprint = hasEnvCredentials
? createHash('sha256')
.update(
`${mergedEnv.VELA_RUNTIME_KEY ?? ''}\n${mergedEnv.VELA_LINK_URL ?? ''}`,
)
.digest('hex')
.slice(0, 16)
: '';
return {
authSource: hasEnvCredentials ? 'env' : status.loggedIn ? 'file' : 'none',
profile: status.profile,
loggedIn: status.loggedIn,
userId: status.user?.id ?? '',
userEmail: status.user?.email ?? '',
// Include the config mtime even for env-backed auth: the live billing
// summary is fetched with the config profile's controlKey, so a config
// rewrite (account switch) must invalidate the cached plan/balance — even
// when VELA_RUNTIME_KEY is the active runtime credential. Otherwise an
// env-backed session keeps serving the previous account's plan/balance.
configMtimeMs: existsSync(status.configPath)
? statSync(status.configPath).mtimeMs
: null,
credentialFingerprint,
};
}
export function readVelaControlApiContext(
env: NodeJS.ProcessEnv = process.env,
configuredEnv: Record<string, string> = {},
): VelaControlApiContext | null {
const mergedEnv = mergeVelaEnv(env, configuredEnv);
const profile = resolveAmrProfile(mergedEnv);
const envControlKey = mergedEnv.VELA_CONTROL_KEY?.trim() ?? '';
const envApiUrl = mergedEnv.VELA_API_URL?.trim() ?? '';
if (envControlKey) {
const status = readVelaLoginStatus(env, configuredEnv);
return {
profile,
apiUrl: envApiUrl || 'https://amr-api.open-design.ai',
controlKey: envControlKey,
user: status.user,
configMtimeMs: null,
};
}
const file = readConfigFile();
const stored = file?.profiles?.[profile];
const controlKey = stored?.controlKey?.trim() ?? '';
if (!controlKey) return null;
return {
profile,
apiUrl: stored?.apiUrl?.trim() || envApiUrl || 'https://amr-api.open-design.ai',
controlKey,
user: stored?.user ?? null,
configMtimeMs: existsSync(amrConfigPath()) ? statSync(amrConfigPath()).mtimeMs : null,
};
}
export function forgetVelaLogin(env: NodeJS.ProcessEnv = process.env): void {
const file = amrConfigPath();
if (!existsSync(file)) return;
const parsed = readConfigFile();
if (!parsed?.profiles) return;
const profile = resolveAmrProfile(env);
if (!Object.prototype.hasOwnProperty.call(parsed.profiles, profile)) return;
const keptProfileConfig = { ...(parsed.profiles[profile] ?? {}) };
delete keptProfileConfig.controlKey;
delete keptProfileConfig.runtimeKey;
delete keptProfileConfig.user;
const nextProfiles = { ...parsed.profiles };
nextProfiles[profile] = keptProfileConfig;
writeFileSync(
file,
JSON.stringify({ ...parsed, profiles: nextProfiles }, null, 2),
'utf8',
);
}
export interface SpawnedVelaLogin {
pid: number;
startedAt: string;
profile: string;
}
const activeLoginProcs = new Map<number, ChildProcess>();
const LOGIN_STARTUP_GRACE_MS = 250;
const LOGIN_ACTIVATION_GRACE_MS = 10_000;
const LOGIN_CANCEL_KILL_GRACE_MS = 2000;
// How long the login request blocks waiting for the direct attempt's activation
// URL before returning and letting the UI poll /status. Overridable so tests can
// exercise the slow-direct path without a multi-second wait. Never used to kill
// the direct attempt — see waitForLoginActivationSteadyState.
function resolveLoginActivationGraceMs(baseEnv: NodeJS.ProcessEnv): number {
const raw = Number(baseEnv.OD_AMR_LOGIN_ACTIVATION_GRACE_MS);
return Number.isFinite(raw) && raw >= 0 ? raw : LOGIN_ACTIVATION_GRACE_MS;
}
// Cap the captured buffers: the activation URL + code land in the first handful
// of stdout lines, so a few KB is plenty and bounds memory if vela stays chatty.
const LOGIN_CAPTURE_LIMIT_BYTES = 8192;
// Activation details captured from the in-flight `vela login` child. Reset on
// each spawn (one interactive login at a time); `readVelaLoginStatus` only
// surfaces it while a login is actually in flight.
let activeLoginActivation: VelaLoginActivation | null = null;
interface VelaLoginActivationCapture {
activation: VelaLoginActivation;
stdout: string;
stderr: string;
}
// Attach lifetime listeners that accumulate the child's stdout/stderr and keep
// re-parsing the activation URL/code/warning as output streams in. Unlike
// `waitForImmediateLoginFailure` (which only reads the first 250ms), this lives
// for the whole login so a slow CreateDeviceAuthorization round-trip — common on
// constrained networks, exactly where the browser handoff also tends to fail —
// still surfaces the URL once it finally prints.
function beginLoginActivationCapture(child: ChildProcess): VelaLoginActivationCapture {
const activation: VelaLoginActivation = {
activationUrl: null,
userCode: null,
browserOpenFailed: false,
};
const capture: VelaLoginActivationCapture = {
activation,
stdout: '',
stderr: '',
};
activeLoginActivation = activation;
child.stdout?.setEncoding('utf8');
child.stderr?.setEncoding('utf8');
child.stdout?.on('data', (chunk) => {
if (capture.stdout.length < LOGIN_CAPTURE_LIMIT_BYTES) {
capture.stdout += String(chunk);
}
const parsed = parseVelaLoginActivation(capture.stdout, capture.stderr);
if (parsed.activationUrl) activation.activationUrl = parsed.activationUrl;
if (parsed.userCode) activation.userCode = parsed.userCode;
});
child.stderr?.on('data', (chunk) => {
if (capture.stderr.length < LOGIN_CAPTURE_LIMIT_BYTES) {
capture.stderr += String(chunk);
}
if (parseVelaLoginActivation('', capture.stderr).browserOpenFailed) {
activation.browserOpenFailed = true;
}
});
return capture;
}
function isChildRunning(child: ChildProcess): boolean {
return child.exitCode === null && child.signalCode === null;
}
export function isVelaLoginInFlight(): boolean {
for (const [pid, child] of activeLoginProcs) {
if (isChildRunning(child)) return true;
activeLoginProcs.delete(pid);
}
return false;
}
export interface CancelVelaLoginResult {
canceled: boolean;
pids: number[];
}
export function cancelVelaLogin(): CancelVelaLoginResult {
const pids: number[] = [];
for (const [pid, child] of activeLoginProcs) {
if (!isChildRunning(child)) {
activeLoginProcs.delete(pid);
continue;
}
try {
child.kill('SIGTERM');
} catch {
activeLoginProcs.delete(pid);
continue;
}
pids.push(pid);
const killTimer = setTimeout(() => {
try {
if (isChildRunning(child)) child.kill('SIGKILL');
} catch {
activeLoginProcs.delete(pid);
}
}, LOGIN_CANCEL_KILL_GRACE_MS);
killTimer.unref?.();
}
return { canceled: pids.length > 0, pids };
}
export interface SpawnVelaLoginDeps {
configuredEnv?: Record<string, string>;
baseEnv?: NodeJS.ProcessEnv;
attribution?: AmrEntryAttribution | null;
defaultApiUrl?: string | null;
// When set, block until the direct attempt reaches device-auth steady state
// (prints its activation URL) or exits/errors before that, so the login route
// can fall back to the IPv4 proxy on a real pre-activation failure rather than
// only on a sub-250ms startup crash. See waitForLoginActivationSteadyState.
waitForActivation?: boolean;
}
async function waitForImmediateLoginFailure(child: ChildProcess): Promise<void> {
let stderr = '';
let stdout = '';
child.stderr?.setEncoding('utf8');
child.stdout?.setEncoding('utf8');
child.stderr?.on('data', (chunk) => {
if (stderr.length < 4096) stderr += String(chunk);
});
child.stdout?.on('data', (chunk) => {
if (stdout.length < 4096) stdout += String(chunk);
});
const result = await new Promise<
| { kind: 'running' }
| { kind: 'exit'; code: number | null; signal: NodeJS.Signals | null }
| { kind: 'error'; error: Error }
>((resolve) => {
let settled = false;
const finish = (
value:
| { kind: 'running' }
| { kind: 'exit'; code: number | null; signal: NodeJS.Signals | null }
| { kind: 'error'; error: Error },
) => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve(value);
};
const timer = setTimeout(
() => finish({ kind: 'running' }),
LOGIN_STARTUP_GRACE_MS,
);
child.once('exit', (code, signal) => finish({ kind: 'exit', code, signal }));
child.once('error', (error) => finish({ kind: 'error', error }));
});
if (result.kind === 'running') return;
if (result.kind === 'error') {
throw new Error(`vela login failed to start: ${result.error.message}`);
}
if (result.code === 0) return;
const detail = (stderr || stdout).trim();
throw new Error(
detail ||
`vela login exited before authentication completed (code ${result.code ?? 'null'}, signal ${result.signal ?? 'null'})`,
);
}
// Wait for the direct `vela login` attempt to either print its device-auth
// activation URL (healthy — the direct path works even on the transparent-proxy
// networks this fix targets, just possibly slowly) or exit/error BEFORE printing
// it (a real failure the caller can retry through the IPv4 proxy). Crucially, a
// merely slow-but-still-running direct login is NOT killed: once the grace
// elapses we simply stop blocking the request and let it keep running (the UI
// polls /status). Killing a slow-healthy direct login and re-routing it through
// the proxy is exactly the regression this avoids — on a corporate transparent
// proxy the proxy hop loses the client IP and the upstream 502s. Only an
// explicit pre-activation exit/error triggers the proxy fallback.
async function waitForLoginActivationSteadyState(
child: ChildProcess,
capture: VelaLoginActivationCapture,
graceMs: number,
): Promise<void> {
if (capture.activation.activationUrl) return;
if (!isChildRunning(child)) {
if (child.exitCode === 0) return;
const detail = (capture.stderr || capture.stdout).trim();
throw new Error(
detail ||
`vela login exited before device authorization started (code ${child.exitCode ?? 'null'}, signal ${child.signalCode ?? 'null'})`,
);
}
const result = await new Promise<
| { kind: 'activated' }
| { kind: 'exit'; code: number | null; signal: NodeJS.Signals | null }
| { kind: 'error'; error: Error }
| { kind: 'still-running' }
>((resolve) => {
let settled = false;
let poll: NodeJS.Timeout | null = null;
let timer: NodeJS.Timeout | null = null;
const finish = (
value:
| { kind: 'activated' }
| { kind: 'exit'; code: number | null; signal: NodeJS.Signals | null }
| { kind: 'error'; error: Error }
| { kind: 'still-running' },
) => {
if (settled) return;
settled = true;
if (poll) clearInterval(poll);
if (timer) clearTimeout(timer);
resolve(value);
};
poll = setInterval(() => {
if (capture.activation.activationUrl) finish({ kind: 'activated' });
}, 50);
timer = setTimeout(() => finish({ kind: 'still-running' }), graceMs);
timer.unref?.();
child.once('exit', (code, signal) => finish({ kind: 'exit', code, signal }));
child.once('error', (error) => finish({ kind: 'error', error }));
if (capture.activation.activationUrl) finish({ kind: 'activated' });
});
if (result.kind === 'activated') return;
// Slow but still alive: leave the direct attempt running and let the request
// return — do NOT kill it or fall back to the proxy.
if (result.kind === 'still-running') return;
if (result.kind === 'error') {
throw new Error(`vela login failed to start: ${result.error.message}`);
}
if (result.code === 0) return;
const detail = (capture.stderr || capture.stdout).trim();
throw new Error(
detail ||
`vela login exited before device authorization started (code ${result.code ?? 'null'}, signal ${result.signal ?? 'null'})`,
);
}
export async function spawnVelaLogin(
deps: SpawnVelaLoginDeps = {},
): Promise<SpawnedVelaLogin> {
if (isVelaLoginInFlight()) {
throw new Error('vela login already running');
}
const def = getAgentDef('amr');
if (!def) throw new Error('AMR runtime def not registered');
const baseEnv = deps.baseEnv ?? process.env;
const configuredEnv = withDefaultVelaApiUrl(
deps.configuredEnv ?? {},
baseEnv,
deps.defaultApiUrl,
);
const launch = resolveAgentLaunch(def, configuredEnv);
const bin = launch.selectedPath;
if (!bin) {
throw new Error('vela binary not found; install vela or configure VELA_BIN');
}
const env = {
...spawnEnvForAgent('amr', baseEnv, configuredEnv),
...velaLoginAttributionEnv(deps.attribution),
};
// Route through createCommandInvocation so an npm/Node-style `vela.cmd` or
// `vela.bat` shim on Windows gets wrapped under `cmd.exe /d /s /c …` with
// verbatim args, matching what `execAgentFile` / chat-run spawning do. A
// direct `spawn(bin, args)` on a `.cmd` shim quietly fails to find the
// shim's actual entry point. POSIX is unchanged (no wrapping needed).
const invocation = createCommandInvocation({ command: bin, args: ['login'], env });
const child = spawn(invocation.command, invocation.args, {
stdio: ['ignore', 'pipe', 'pipe'],
env,
detached: false,
windowsVerbatimArguments: invocation.windowsVerbatimArguments,
});
if (typeof child.pid !== 'number') {
throw new Error('failed to spawn vela login');
}
activeLoginProcs.set(child.pid, child);
const cleanup = () => {
if (typeof child.pid === 'number') activeLoginProcs.delete(child.pid);
activeLoginActivation = null;
};
child.once('exit', cleanup);
child.once('error', cleanup);
// Capture the activation URL/code/warning for the whole login (not just the
// 250ms startup race) so readVelaLoginStatus can surface them. Start before
// the grace wait so no early stdout is missed.
const activationCapture = beginLoginActivationCapture(child);
await waitForImmediateLoginFailure(child);
if (deps.waitForActivation) {
await waitForLoginActivationSteadyState(
child,
activationCapture,
resolveLoginActivationGraceMs(baseEnv),
);
}
// vela opens the browser itself (OpenBrowser in apps/cli/.../login.go), but it
// also prints the activation URL + code to stdout first and warns on stderr if
// the auto-open failed. We capture those above and expose them via
// readVelaLoginStatus() so the UI can offer a manual link when the browser
// never opened. Callers still poll readVelaLoginStatus() to detect completion.
return {
pid: child.pid,
startedAt: new Date().toISOString(),
profile: resolveAmrProfile(env),
};
}
function withDefaultVelaApiUrl(
configuredEnv: Record<string, string>,
baseEnv: NodeJS.ProcessEnv,
defaultApiUrl: string | null | undefined,
): Record<string, string> {
const trimmed = defaultApiUrl?.trim();
if (!trimmed) return configuredEnv;
if ((configuredEnv.VELA_API_URL ?? '').trim()) return configuredEnv;
if ((baseEnv.VELA_API_URL ?? '').trim()) return configuredEnv;
return { ...configuredEnv, VELA_API_URL: trimmed };
}
export function parseVelaLoginAttribution(input: unknown): AmrEntryAttribution | null {
const raw = input && typeof input === 'object' && 'attribution' in input
? (input as { attribution?: unknown }).attribution
: null;
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
const value = raw as Partial<AmrEntryAttribution>;
if (
typeof value.entryId !== 'string'
|| value.entryId.length === 0
|| value.sourceProduct !== 'open_design'
|| typeof value.sourceDetail !== 'string'
|| !AMR_ENTRY_SOURCES.has(value.sourceDetail as TrackingAmrEntrySource)
|| typeof value.occurredAt !== 'string'
|| !Number.isFinite(Date.parse(value.occurredAt))
) {
return null;
}
const odDeviceId = sanitizeOpenDesignDeviceId(value.odDeviceId);
return {
entryId: value.entryId,
sourceProduct: value.sourceProduct,
sourceDetail: value.sourceDetail as TrackingAmrEntrySource,
occurredAt: value.occurredAt,
...(odDeviceId ? { odDeviceId } : {}),
};
}
export function parseAmrEntryAnalyticsPayload(
input: unknown,
): AmrEntryAnalyticsPayload | null {
const raw = isRecord(input) && 'payload' in input ? input.payload : input;
if (!isRecord(raw)) return null;
const pageName = raw.pageName;
const sourcePageName = raw.sourcePageName;
const area = raw.area;
const element = raw.element;
const action = raw.action;
const entryId = raw.entryId;
const sourceProduct = raw.sourceProduct;
const sourceDetail = raw.sourceDetail;
const entryOccurredAt = raw.entryOccurredAt;
const odRole = sanitizeOptionalProfileValue(raw.odRole);
const odOrgSize = sanitizeOptionalProfileValue(raw.odOrgSize);
const odSource = sanitizeOptionalProfileValue(raw.odSource);
const odUseCase = sanitizeOptionalProfileList(raw.odUseCase);
if (
pageName !== 'open_design'
|| typeof sourcePageName !== 'string'
|| !AMR_ENTRY_SOURCE_PAGES.has(sourcePageName as AmrEntrySourcePageName)
|| area !== 'amr_entry'
|| typeof element !== 'string'
|| !AMR_ENTRY_SOURCES.has(element as TrackingAmrEntrySource)
|| action !== 'click_amr_entry'
|| typeof entryId !== 'string'
|| entryId.length === 0
|| sourceProduct !== 'open_design'
|| typeof sourceDetail !== 'string'
|| !AMR_ENTRY_SOURCES.has(sourceDetail as TrackingAmrEntrySource)
|| sourceDetail !== element
|| sourcePageName
!== AMR_ENTRY_SOURCE_PAGE_BY_SOURCE[sourceDetail as TrackingAmrEntrySource]
|| typeof entryOccurredAt !== 'string'
|| !Number.isFinite(Date.parse(entryOccurredAt))
|| odRole === INVALID_PROFILE_VALUE
|| odOrgSize === INVALID_PROFILE_VALUE
|| odSource === INVALID_PROFILE_VALUE
|| odUseCase === INVALID_PROFILE_VALUE
) {
return null;
}
return {
pageName,
sourcePageName: sourcePageName as AmrEntrySourcePageName,
area,
element: element as TrackingAmrEntrySource,
action,
entryId,
sourceProduct,
sourceDetail: sourceDetail as TrackingAmrEntrySource,
entryOccurredAt,
...(odRole ? { odRole } : {}),
...(odOrgSize ? { odOrgSize } : {}),
...(odUseCase ? { odUseCase } : {}),
...(odSource ? { odSource } : {}),
};
}
export function parseAmrOnboardingProfileAnalyticsPayload(
input: unknown,
): AmrOnboardingProfileAnalyticsPayload | null {
const raw = isRecord(input) && 'payload' in input ? input.payload : input;
if (!isRecord(raw)) return null;
const pageName = raw.pageName;
const sourcePageName = raw.sourcePageName;
const area = raw.area;