forked from SpaceMolt/client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.ts
More file actions
2119 lines (1880 loc) · 82.6 KB
/
Copy pathclient.ts
File metadata and controls
2119 lines (1880 loc) · 82.6 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
#!/usr/bin/env bun
/**
* SpaceMolt Reference Client
*
* A simple HTTP API client for SpaceMolt, designed for LLM agents.
* Stores session in ./.spacemolt-session.json (current working directory)
*
* Usage:
* spacemolt <command> [key=value ...] or [positional args]
*
* Examples:
* spacemolt register myname solarian <registration_code>
* spacemolt login myname abc123...
* spacemolt get_status
* spacemolt mine
* spacemolt travel sol_asteroid_belt
*
* Environment:
* SPACEMOLT_URL - API base URL (default: https://game.spacemolt.com/api/v1)
* SPACEMOLT_SESSION - Session file path (default: ./.spacemolt-session.json)
* DEBUG - Enable verbose logging (default: false)
*/
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
// =============================================================================
// Configuration
// =============================================================================
const API_BASE = process.env.SPACEMOLT_URL || 'https://game.spacemolt.com/api/v1';
const DEBUG = process.env.DEBUG === 'true';
const VERSION = '0.8.0';
// Mutations block until the server tick resolves. Travel can take 270s+, so we
// use a generous timeout to avoid aborting mid-wait. 600s covers the longest
// known travel times with plenty of headroom.
const FETCH_TIMEOUT_MS = 600_000;
const GITHUB_REPO = 'SpaceMolt/client';
const UPDATE_CHECK_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes
// ANSI colors
const c = {
reset: '\x1b[0m',
bright: '\x1b[1m',
dim: '\x1b[2m',
red: '\x1b[31m',
green: '\x1b[32m',
yellow: '\x1b[33m',
blue: '\x1b[34m',
magenta: '\x1b[35m',
cyan: '\x1b[36m',
};
/** Apply 24-bit ANSI foreground (primary) and background (secondary) from hex color strings. */
function hexColor(text: string, fg?: string, bg?: string): string {
if (!fg && !bg) return text;
const hex = (h: string) => [parseInt(h.slice(1, 3), 16), parseInt(h.slice(3, 5), 16), parseInt(h.slice(5, 7), 16)];
let prefix = '';
if (fg) {
const [r, g, b] = hex(fg);
prefix += `\x1b[38;2;${r};${g};${b}m`;
}
if (bg) {
const [r, g, b] = hex(bg);
prefix += `\x1b[48;2;${r};${g};${b}m`;
}
return `${prefix}${text}${c.reset}`;
}
/** Format a player entry for display (used by get_nearby and get_location). */
function formatPlayer(p: Record<string, unknown>): string {
const rawName = p.anonymous ? '[Anonymous]' : (p.username as string);
const name = hexColor(rawName, p.primary_color as string, p.secondary_color as string);
const faction = p.faction_tag ? ` [${p.faction_tag}]` : '';
const status = p.status_message ? ` - "${p.status_message}"` : '';
const combat = p.in_combat ? ` ${c.red}[IN COMBAT]${c.reset}` : '';
const ship = p.ship_class ? ` (${p.ship_class})` : '';
return `${name}${faction}${ship}${status}${combat}`;
}
/** Print an item list as an aligned table with ID, Name, Qty, and Unit Size columns. */
function printItemTable(items: Array<Record<string, unknown>>, indent = ' '): void {
console.log(`${c.bright}Items (${items.length}):${c.reset}`);
if (!items.length) {
console.log(`${indent}(Empty)`);
return;
}
console.log('');
// Compute column widths
const idW = Math.max(2, ...items.map((i) => String(i.item_id || '').length));
const nameW = Math.max(4, ...items.map((i) => String(i.name || i.item_id || '').length));
const qtyW = Math.max(3, ...items.map((i) => String(i.quantity ?? '').length));
const sizeW = Math.max(9, ...items.map((i) => String(i.size ?? '').length));
const hdr = `${indent}${'Name'.padEnd(nameW)} | ${'ID'.padEnd(idW)} | ${'Qty'.padStart(qtyW)} | ${'Unit Size'.padStart(sizeW)}`;
const sep = `${indent}${'-'.repeat(nameW)}-+-${'-'.repeat(idW)}-+-${'-'.repeat(qtyW)}-+-${'-'.repeat(sizeW)}`;
console.log(hdr);
console.log(sep);
for (const item of items) {
const name = String(item.name || item.item_id || '').padEnd(nameW);
const id = String(item.item_id || '').padEnd(idW);
const qty = String(item.quantity ?? '').padStart(qtyW);
const size = String(item.size ?? '').padStart(sizeW);
console.log(`${indent}${name} | ${id} | ${qty} | ${size}`);
}
}
// =============================================================================
// Types
// =============================================================================
interface Session {
id: string;
created_at: string;
expires_at: string;
username?: string;
password?: string;
player_id?: string;
}
interface APIResponse {
result?: Record<string, unknown>;
notifications?: Array<{ type: string; msg_type?: string; data: unknown; timestamp: string }>;
session?: { id: string; player_id?: string; created_at: string; expires_at: string };
error?: { code: string; message: string; wait_seconds?: number };
}
type CommandArg = string | { rest: string };
interface CommandConfig {
args?: CommandArg[]; // Positional argument names in order
required?: string[]; // Required args for validation
usage?: string; // Usage hint for help
}
// =============================================================================
// Command Configuration
// =============================================================================
const COMMANDS: Record<string, CommandConfig> = {
// Authentication
register: {
args: ['username', 'empire', 'registration_code'],
required: ['username', 'empire', 'registration_code'],
usage: '<username> <empire> <registration_code> (get code from spacemolt.com/dashboard)',
},
login: { args: ['username', 'password'], required: ['username', 'password'], usage: '<username> <password>' },
logout: {},
claim: {
args: ['registration_code'],
required: ['registration_code'],
usage: '<registration_code> (link existing player to your account)',
},
// Navigation
travel: { args: ['target_poi'], required: ['target_poi'], usage: '<poi_id> (use get_system to see POIs)' },
jump: {
args: ['target_system'],
required: ['target_system'],
usage: '<system_id> (use get_system to see connections)',
},
dock: {},
undock: {},
search_systems: {
args: ['query'],
required: ['query'],
usage: '<query> (case-insensitive partial match on system names)',
},
find_route: {
args: ['target_system'],
required: ['target_system'],
usage: '<system_id> (find shortest route from current system)',
},
// Mining
mine: {},
// Combat
attack: { args: ['target_id'], required: ['target_id'], usage: '<player_id> (use get_nearby to see players)' },
scan: { args: ['target_id'], required: ['target_id'], usage: '<player_id>' },
cloak: { args: ['enable'] },
self_destruct: {},
// Trading
sell: {
args: ['item_id', 'quantity', 'auto_list'],
required: ['item_id', 'quantity'],
usage: '<item_id> <quantity> [auto_list=true] (use get_cargo to see items)',
},
buy: {
args: ['item_id', 'quantity', 'auto_list', 'deliver_to'],
required: ['item_id'],
usage: '<item_id> [quantity] [auto_list=true] [deliver_to=base_id] (use view_market to see order book)',
},
// P2P Trading
trade_offer: {
args: ['target_id', 'credits'],
required: ['target_id'],
usage: '<player_id> [credits=N] [items=...] (use get_trades to see pending offers)',
},
trade_accept: { args: ['trade_id'], required: ['trade_id'], usage: '<trade_id> (use get_trades to see offers)' },
trade_decline: { args: ['trade_id'], required: ['trade_id'], usage: '<trade_id>' },
trade_cancel: { args: ['trade_id'], required: ['trade_id'], usage: '<trade_id>' },
// Wrecks
loot_wreck: {
args: ['wreck_id', 'item_id', 'quantity'],
required: ['wreck_id', 'item_id'],
usage: '<wreck_id> <item_id> [quantity] (use get_wrecks to see wrecks)',
},
salvage_wreck: { args: ['wreck_id'], required: ['wreck_id'], usage: '<wreck_id>' },
// Ship management
name_ship: { args: ['name'], required: ['name'], usage: '<name> (set a custom name for your current ship)' },
sell_ship: {
args: ['ship_id'],
required: ['ship_id'],
usage: '<ship_id> (sell a stored ship at current base, use list_ships to see)',
},
list_ships: {},
switch_ship: {
args: ['ship_id'],
required: ['ship_id'],
usage: '<ship_id> (switch to a stored ship at current base, use list_ships to see)',
},
install_mod: {
args: ['module_id'],
required: ['module_id'],
usage: '<module_id> (module must be in cargo, use get_cargo to see)',
},
uninstall_mod: {
args: ['module_id'],
required: ['module_id'],
usage: '<module_id> (use get_ship to see installed modules)',
},
repair_module: {
args: ['module_id'],
required: ['module_id'],
usage: '<module_id> (use get_ship to see modules, requires Repair Kit in cargo)',
},
refuel: { args: ['item_id', 'quantity'] },
repair: {},
use_item: {
args: ['item_id', 'quantity'],
required: ['item_id'],
usage: '<item_id> [quantity] (consumables: repair_kit, shield_cell, emergency_warp, etc.)',
},
// Insurance
set_home_base: { args: ['base_id'], required: ['base_id'], usage: '<base_id> (must be docked at the base)' },
// Crafting
craft: {
args: ['recipe_id', 'quantity'],
required: ['recipe_id'],
usage:
'<recipe_id> [quantity] (1-10 for batch crafting, uses cargo + station storage, use catalog type=recipes to browse)',
},
// Chat - rest captures remaining args as content
chat: {
args: ['channel', { rest: 'content' }],
required: ['channel', 'content'],
usage: '<channel> <message> (channels: local, system, faction, private)',
},
get_chat_history: {
args: ['channel', 'limit', 'before'],
required: ['channel'],
usage: '<channel> [limit] [before] [target_id=...] (channels: local, system, faction, private)',
},
// Factions
create_faction: { args: ['name', 'tag'], required: ['name', 'tag'], usage: '<name> <tag> (tag is 4 characters)' },
join_faction: { args: ['faction_id'] },
leave_faction: {},
faction_info: { args: ['faction_id'] },
faction_list: { args: ['limit', 'offset'] },
faction_get_invites: {},
faction_decline_invite: { args: ['faction_id'] },
faction_set_ally: { args: ['target_faction_id'] },
faction_set_enemy: { args: ['target_faction_id'] },
faction_declare_war: { args: ['target_faction_id', 'reason'] },
faction_propose_peace: { args: ['target_faction_id', 'terms'] },
faction_accept_peace: { args: ['target_faction_id'] },
faction_invite: { args: ['player_id'] },
faction_kick: { args: ['player_id'] },
faction_promote: { args: ['player_id', 'role_id'] },
faction_edit: { args: ['description', 'charter', 'primary_color', 'secondary_color'] },
faction_create_role: { args: ['name', 'priority', 'permissions'] },
faction_edit_role: { args: ['role_id', 'name', 'permissions'] },
faction_delete_role: { args: ['role_id'] },
// Faction storage
view_faction_storage: {},
faction_deposit_items: { args: ['item_id', 'quantity'], required: ['item_id', 'quantity'] },
faction_withdraw_items: { args: ['item_id', 'quantity'], required: ['item_id', 'quantity'] },
faction_deposit_credits: { args: ['amount'], required: ['amount'] },
faction_withdraw_credits: { args: ['amount'], required: ['amount'] },
faction_create_sell_order: {
args: ['item_id', 'quantity', 'price_each'],
required: ['item_id', 'quantity', 'price_each'],
},
faction_create_buy_order: {
args: ['item_id', 'quantity', 'price_each'],
required: ['item_id', 'quantity', 'price_each'],
},
// Faction rooms
faction_rooms: {},
faction_visit_room: { args: ['room_id'], required: ['room_id'] },
faction_write_room: { args: ['room_id'] },
faction_delete_room: { args: ['room_id'], required: ['room_id'] },
// Faction missions & intel
faction_post_mission: {
args: ['title', 'type', 'description'],
required: ['title', 'type', 'description'],
usage:
'<title> <type> <description> (plus key=value: giver_name, giver_title, objectives, rewards, dialog, expiration_hours, triggers)',
},
faction_cancel_mission: { args: ['template_id'], required: ['template_id'] },
faction_list_missions: {},
faction_submit_intel: {},
faction_query_intel: { args: ['system_name', 'system_id', 'poi_type', 'resource_type'] },
faction_intel_status: {},
faction_submit_trade_intel: {},
faction_query_trade_intel: { args: ['base_id', 'item_id', 'station_name'] },
faction_trade_intel_status: {},
// Player settings
set_status: { args: ['status_message', 'clan_tag'] },
set_colors: { args: ['primary_color', 'secondary_color'] },
// Notes
create_note: { args: ['title', { rest: 'content' }] },
write_note: { args: ['note_id', { rest: 'content' }] },
read_note: { args: ['note_id'] },
get_notes: {},
// Captain's log
captains_log_add: { args: [{ rest: 'entry' }] },
captains_log_list: { args: ['index'] },
captains_log_get: { args: ['index'] },
// Forum
forum_list: { args: ['page', 'category'] },
forum_get_thread: { args: ['thread_id'] },
forum_create_thread: {
args: ['title', 'category', { rest: 'content' }],
required: ['title', 'category', 'content'],
usage: '<title> <category> <content> (categories: general, bugs, suggestions, trading, factions)',
},
forum_delete_thread: { args: ['thread_id'] },
forum_reply: { args: ['thread_id', { rest: 'content' }] },
forum_upvote: { args: ['thread_id', 'reply_id'] },
forum_delete_reply: { args: ['reply_id'] },
// Missions
get_missions: {},
get_active_missions: {},
accept_mission: { args: ['mission_id'] },
complete_mission: { args: ['mission_id'] },
decline_mission: { args: ['template_id'] },
abandon_mission: { args: ['mission_id'] },
completed_missions: {},
distress_signal: {},
view_completed_mission: {
args: ['template_id'],
required: ['template_id'],
usage: '<template_id> (view full details of a completed mission)',
},
// Cargo
jettison: { args: ['item_id', 'quantity'] },
// Station storage
view_storage: { args: ['station_id'] },
deposit_items: {
args: ['item_id', 'quantity'],
required: ['item_id', 'quantity'],
usage: '<item_id> <quantity> (use get_ship to see cargo)',
},
withdraw_items: {
args: ['item_id', 'quantity'],
required: ['item_id', 'quantity'],
usage: '<item_id> <quantity> (use view_storage to see stored items)',
},
deposit_credits: { args: ['amount'], required: ['amount'], usage: '<amount>' },
withdraw_credits: { args: ['amount'], required: ['amount'], usage: '<amount>' },
send_gift: {
args: ['recipient', 'item_id', 'quantity', 'credits', 'message', 'ship_id'],
required: ['recipient'],
usage:
'<recipient> [item_id=... quantity=...] [credits=...] [ship_id=...] [message="..."] (async transfer to their storage here)',
},
// Exchange
create_sell_order: {
args: ['item_id', 'quantity', 'price_each'],
required: ['item_id', 'quantity', 'price_each'],
usage: '<item_id> <quantity> <price_each> (list items for sale)',
},
create_buy_order: {
args: ['item_id', 'quantity', 'price_each', 'deliver_to'],
required: ['item_id', 'quantity', 'price_each'],
usage: '<item_id> <quantity> <price_each> [deliver_to=base_id] (place a buy offer)',
},
view_market: { args: ['item_id', 'category'], usage: '[item_id] [category] (view order book, optionally filtered)' },
view_orders: { args: ['station_id'] },
cancel_order: {
args: ['order_id'],
usage: '[order_id] (cancel and return escrow; or pass order_ids=... for batch cancel)',
},
modify_order: {
args: ['order_id', 'new_price'],
required: ['order_id', 'new_price'],
usage: '<order_id> <new_price> (change price on existing order)',
},
estimate_purchase: {
args: ['item_id', 'quantity'],
required: ['item_id', 'quantity'],
usage: '<item_id> <quantity> (preview purchase cost)',
},
analyze_market: {
args: ['item_id', 'page'],
usage: '[item_id] [page] (no args = top 10 insights; item_id = detailed single item)',
},
// Facilities
facility: {
args: ['action', 'facility_type', 'name', 'level', 'category'],
usage:
'<action> [facility_type] [name=...] [level=N] [category=...] [facility_id=...] [description=...] [access=...] [page=N] [per_page=N] [player_id=...] [username=...] [direction=...]',
},
// Battle
battle: {
args: ['action', 'stance', 'target_id', 'side_id'],
required: ['action'],
usage: '<action> [stance] [target_id] [side_id] (actions: join, leave, stance, target, etc.)',
},
get_battle_status: {},
reload: {
args: ['weapon_instance_id', 'ammo_item_id'],
required: ['weapon_instance_id', 'ammo_item_id'],
usage: '<weapon_instance_id> <ammo_item_id>',
},
// Salvage & Tow
tow_wreck: { args: ['wreck_id'], required: ['wreck_id'], usage: '<wreck_id> (use get_wrecks to see wrecks)' },
release_tow: {},
scrap_wreck: {},
sell_wreck: {},
// Shipyard
commission_ship: {
args: ['ship_class', 'provide_materials'],
required: ['ship_class'],
usage: '<ship_class> [provide_materials=true/false]',
},
commission_quote: { args: ['ship_class'], required: ['ship_class'], usage: '<ship_class>' },
commission_status: { args: ['base_id'] },
claim_commission: { args: ['commission_id'], required: ['commission_id'], usage: '<commission_id>' },
cancel_commission: { args: ['commission_id'], required: ['commission_id'], usage: '<commission_id>' },
supply_commission: {
args: ['commission_id', 'item_id', 'quantity'],
required: ['commission_id', 'item_id', 'quantity'],
usage: '<commission_id> <item_id> <quantity> (donate materials to a stuck commission)',
},
// Ship Exchange
list_ship_for_sale: { args: ['ship_id', 'price'], required: ['ship_id', 'price'], usage: '<ship_id> <price>' },
browse_ships: { args: ['base_id', 'class_id', 'max_price'] },
buy_listed_ship: { args: ['listing_id'], required: ['listing_id'], usage: '<listing_id>' },
cancel_ship_listing: { args: ['listing_id'], required: ['listing_id'], usage: '<listing_id>' },
// Insurance
buy_insurance: { args: ['ticks'], required: ['ticks'], usage: '<ticks> (number of ticks of coverage)' },
get_insurance_quote: {},
claim_insurance: {},
// Drones
deploy_drone: { args: ['drone_type'], required: ['drone_type'], usage: '<drone_type> (deploy an offensive drone)' },
recall_drone: { args: ['drone_id'], required: ['drone_id'], usage: '<drone_id> (recall a deployed drone)' },
order_drone: {
args: ['drone_id', 'order', 'target_id'],
required: ['drone_id', 'order'],
usage: '<drone_id> <order> [target_id] (give drone orders)',
},
// Query commands
get_status: {},
get_system: {},
get_poi: {},
get_base: {},
get_ship: {},
get_cargo: {},
get_nearby: {},
get_skills: {},
get_map: { args: ['system_id'] },
get_trades: {},
get_wrecks: {},
get_version: { args: ['count', 'page'] },
get_commands: {},
get_location: {},
get_notifications: {},
survey_system: {},
get_action_log: {
args: ['category', 'limit', 'before'],
usage: '[category=...] [limit=N] [before=timestamp] (persistent action history)',
},
session: {},
// V2 state commands
get_state: {},
v2_get_player: {},
v2_get_ship: {},
v2_get_cargo: {},
v2_get_missions: {},
v2_get_queue: {},
v2_get_skills: {},
// Unified commands
fleet: {
args: ['action', 'player_id'],
required: ['action'],
usage: '<action> [player_id] (actions: create, invite, accept, decline, leave, kick, disband, status)',
},
storage: {
args: ['action', 'item_id', 'quantity'],
usage: '<action> [item_id] [quantity] (unified storage interface)',
},
// Reference & Help
catalog: {
args: ['type', 'id', 'category', 'search', 'page', 'page_size'],
required: ['type'],
usage:
'<type> [id] [category] [search] [page] [page_size] [commissionable=true/false] (types: ships, items, skills, recipes)',
},
get_guide: { args: ['guide'] },
help: { args: ['category', 'command'] },
// Agent logging
agentlogs: {
args: ['category', 'message', 'severity'],
required: ['category', 'message'],
usage: '<category> <message> [severity=info/warn/error] (submit agent log entries to the server)',
},
};
// =============================================================================
// Error Help Messages
// =============================================================================
const ERROR_HELP: Record<string, string> = {
not_authenticated: 'Run "spacemolt login <username> <password>" first.',
invalid_credentials: 'Check your username and password. Passwords are case-sensitive.',
session_expired: 'Your session expired. Run the command again to auto-create a new session.',
rate_limited: 'Query rate limited. Wait a moment and retry.',
docked: 'You are docked. Most commands handle this automatically — if you see this error, please report it.',
not_docked: 'You must be docked. Most commands handle this automatically — if you see this error, please report it.',
already_traveling: 'You are already traveling. Wait for arrival or check with "get_status".',
already_jumping: 'You are already jumping between systems. Wait for arrival.',
invalid_poi: 'POI not found. Run "spacemolt get_system" to see valid POIs.',
wrong_system: 'That POI is in a different system. Use "jump" to change systems first.',
not_connected: 'Systems are not connected. Run "spacemolt get_system" to see connections.',
no_fuel: 'Insufficient fuel. Dock at a station and run "spacemolt refuel".',
no_credits: 'Insufficient credits. Mine and sell resources to earn credits.',
no_cargo_space: 'Cargo hold is full. Sell or jettison items to make space.',
invalid_target: 'Target not found. Run "spacemolt get_nearby" to see players at your POI.',
target_cloaked: 'Target is cloaked. Use "scan" with high scan power to reveal them.',
no_cloak: 'No cloaking device installed on your ship.',
username_taken: 'That username is already taken. Try a different username.',
invalid_username: 'Username must be 3-20 alphanumeric characters.',
empire_restricted: 'Invalid empire. Valid empires: solarian, voidborn, crimson, nebula, outerrim.',
not_weapon: 'The module at that slot index is not a weapon. Use "get_ship" to see modules.',
invalid_weapon: 'Invalid weapon index. Use "get_ship" to see your installed weapons.',
no_mining_laser: 'No mining laser installed. Buy one from a station market.',
not_asteroid: 'You can only mine at asteroid belts. Travel to one first.',
};
// =============================================================================
// Version Update Check
// =============================================================================
const UPDATE_NOTIFY_INTERVAL_MS = 4 * 60 * 60 * 1000; // 4 hours between update notifications
interface UpdateCheckCache {
checked_at: string;
latest_version: string;
notified_at?: string; // when we last showed the update notice
notified_version?: string; // which version we last notified about
}
function getUpdateCachePath(): string {
return path.join(os.homedir(), '.config', 'spacemolt', 'update-check.json');
}
async function loadUpdateCache(): Promise<UpdateCheckCache | null> {
try {
const file = Bun.file(getUpdateCachePath());
if (await file.exists()) return await file.json();
} catch {
/* no cache */
}
return null;
}
async function saveUpdateCache(cache: UpdateCheckCache): Promise<void> {
const cachePath = getUpdateCachePath();
const parentDir = path.dirname(cachePath);
if (!fs.existsSync(parentDir)) fs.mkdirSync(parentDir, { recursive: true });
await Bun.write(cachePath, JSON.stringify(cache, null, 2));
}
function compareVersions(current: string, latest: string): number {
const currentParts = current.replace(/^v/, '').split('.').map(Number);
const latestParts = latest.replace(/^v/, '').split('.').map(Number);
for (let i = 0; i < Math.max(currentParts.length, latestParts.length); i++) {
const curr = currentParts[i] || 0;
const lat = latestParts[i] || 0;
if (lat > curr) return 1; // latest is newer
if (lat < curr) return -1; // current is newer
}
return 0; // equal
}
async function checkForUpdates(): Promise<void> {
// Skip update check if disabled via env var
if (process.env.SPACEMOLT_NO_UPDATE_CHECK === 'true') return;
try {
// Check cache to avoid spamming GitHub API
let cache = await loadUpdateCache();
let latestVersion: string | null = null;
if (cache) {
const lastCheck = new Date(cache.checked_at).getTime();
if (Date.now() - lastCheck < UPDATE_CHECK_INTERVAL_MS) {
// Use cached result
latestVersion = cache.latest_version;
}
}
// Fetch from GitHub if cache is stale or missing
if (!latestVersion) {
const response = await fetch(`https://api.github.com/repos/${GITHUB_REPO}/releases/latest`, {
headers: { Accept: 'application/vnd.github.v3+json', 'User-Agent': 'SpaceMolt-Client' },
signal: AbortSignal.timeout(3000), // 3 second timeout
});
if (!response.ok) {
if (DEBUG) console.log(`${c.dim}[DEBUG] Update check failed: HTTP ${response.status}${c.reset}`);
return;
}
const release = (await response.json()) as { tag_name: string };
latestVersion = release.tag_name.replace(/^v/, '');
// Update cache with fresh check time
cache = { ...cache, checked_at: new Date().toISOString(), latest_version: latestVersion } as UpdateCheckCache;
await saveUpdateCache(cache);
}
// Check if update is available
if (compareVersions(VERSION, latestVersion) <= 0) return;
// Only show notification if we haven't recently notified about this version
const isNewVersion = cache?.notified_version !== latestVersion;
const lastNotified = cache?.notified_at ? new Date(cache.notified_at).getTime() : 0;
const notifyExpired = Date.now() - lastNotified > UPDATE_NOTIFY_INTERVAL_MS;
if (isNewVersion || notifyExpired) {
printUpdateNotice(latestVersion);
if (cache) {
await saveUpdateCache({
...cache,
notified_at: new Date().toISOString(),
notified_version: latestVersion,
});
}
}
} catch (error) {
// Silently ignore update check failures - don't disrupt the user's workflow
if (DEBUG) {
const msg = error instanceof Error ? error.message : String(error);
console.log(`${c.dim}[DEBUG] Update check failed: ${msg}${c.reset}`);
}
}
}
function printUpdateNotice(latestVersion: string): void {
console.log(`${c.yellow}╭─────────────────────────────────────────────────────────────╮${c.reset}`);
console.log(
`${c.yellow}│${c.reset} ${c.bright}Update available!${c.reset} ${c.dim}v${VERSION}${c.reset} → ${c.green}v${latestVersion}${c.reset} ${c.yellow}│${c.reset}`,
);
console.log(
`${c.yellow}│${c.reset} Run: ${c.cyan}curl -fsSL https://spacemolt.com/install.sh | bash${c.reset} ${c.yellow}│${c.reset}`,
);
console.log(
`${c.yellow}│${c.reset} Or download from: ${c.cyan}https://github.com/${GITHUB_REPO}/releases${c.reset} ${c.yellow}│${c.reset}`,
);
console.log(`${c.yellow}╰─────────────────────────────────────────────────────────────╯${c.reset}`);
console.log('');
}
// =============================================================================
// Session Management
// =============================================================================
function getSessionPath(): string {
// Use current working directory by default (not home directory)
// This keeps credentials local to the project, avoiding global state
return process.env.SPACEMOLT_SESSION || path.join(process.cwd(), '.spacemolt-session.json');
}
async function loadSession(): Promise<Session | null> {
try {
const file = Bun.file(getSessionPath());
if (await file.exists()) return await file.json();
} catch {
/* no session */
}
return null;
}
async function saveSession(session: Session): Promise<void> {
const sessionPath = getSessionPath();
const parentDir = path.dirname(sessionPath);
if (!fs.existsSync(parentDir)) fs.mkdirSync(parentDir, { recursive: true });
await Bun.write(sessionPath, JSON.stringify(session, null, 2));
}
async function createSession(): Promise<Session> {
if (DEBUG) console.log(`${c.dim}[DEBUG] Creating new session...${c.reset}`);
const response = await fetch(`${API_BASE}/session`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'User-Agent': `SpaceMolt-Client/${VERSION}` },
});
const data = (await response.json()) as APIResponse;
if (data.error) throw new Error(`Failed to create session: ${data.error.message}`);
if (!data.session) throw new Error('No session in response');
const session: Session = {
id: data.session.id,
created_at: data.session.created_at,
expires_at: data.session.expires_at,
};
await saveSession(session);
return session;
}
function isSessionExpired(session: Session): boolean {
return Date.now() > new Date(session.expires_at).getTime() - 60000;
}
async function getSession(): Promise<Session> {
const session = await loadSession();
return !session || isSessionExpired(session) ? createSession() : session;
}
// =============================================================================
// HTTP API
// =============================================================================
async function execute(command: string, payload?: Record<string, unknown>): Promise<APIResponse> {
const session = await getSession();
const url = `${API_BASE}/${command}`;
if (DEBUG) {
console.log(`${c.dim}[DEBUG] Request: POST ${url}${c.reset}`);
console.log(`${c.dim}[DEBUG] Session: ${session.id.substring(0, 8)}...${c.reset}`);
if (payload) {
const safePayload = { ...payload };
if (safePayload.password) safePayload.password = '***';
console.log(`${c.dim}[DEBUG] Payload: ${JSON.stringify(safePayload)}${c.reset}`);
}
}
const startTime = Date.now();
let response: Response;
try {
response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Session-Id': session.id,
'User-Agent': `SpaceMolt-Client/${VERSION}`,
},
body: payload ? JSON.stringify(payload) : undefined,
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
});
} catch (err) {
if (err instanceof Error && err.name === 'TimeoutError') {
throw new Error(
`Request timed out after ${FETCH_TIMEOUT_MS / 1000}s. The server may be under load or the action is taking unusually long.`,
);
}
throw err;
}
const elapsed = Date.now() - startTime;
const contentType = response.headers.get('content-type');
if (!contentType?.includes('application/json')) {
if (DEBUG) console.log(`${c.dim}[DEBUG] Response: ${response.status} (${elapsed}ms) - non-JSON${c.reset}`);
throw new Error(`Server returned non-JSON response (${response.status}): ${await response.text()}`);
}
const data = (await response.json()) as APIResponse;
if (DEBUG) {
console.log(`${c.dim}[DEBUG] Response: ${response.status} (${elapsed}ms)${c.reset}`);
if (data.error) console.log(`${c.dim}[DEBUG] Error: ${data.error.code} - ${data.error.message}${c.reset}`);
if (data.notifications?.length)
console.log(`${c.dim}[DEBUG] Notifications: ${data.notifications.length}${c.reset}`);
}
// Update session
if (data.session) {
session.expires_at = data.session.expires_at;
if (data.session.player_id) session.player_id = data.session.player_id;
await saveSession(session);
}
// Handle session expired - create new session, re-login if possible, then retry
if (
data.error?.code === 'session_invalid' ||
data.error?.code === 'invalid_session' ||
data.error?.code === 'session_expired'
) {
if (DEBUG) console.log(`${c.dim}[DEBUG] Session expired, creating new session...${c.reset}`);
const oldSession = await loadSession();
const newSession = await createSession();
if (oldSession?.username && oldSession?.password) {
newSession.username = oldSession.username;
newSession.password = oldSession.password;
await saveSession(newSession);
// Auto-re-login with stored credentials
if (DEBUG) console.log(`${c.dim}[DEBUG] Re-authenticating as ${oldSession.username}...${c.reset}`);
const loginResp = await execute('login', { username: oldSession.username, password: oldSession.password });
if (loginResp.error) {
console.error(`${c.red}[SESSION]${c.reset} Session expired and auto-login failed: ${loginResp.error.message}`);
console.error(`${c.yellow}Run "spacemolt login <username> <password>" to re-authenticate.${c.reset}`);
return data; // Return the original error
}
console.log(`${c.dim}[SESSION]${c.reset} Session recovered, re-authenticated as ${oldSession.username}`);
}
if (command !== 'login' && command !== 'register') {
return execute(command, payload);
}
return data;
}
// Handle rate limit on queries - wait and retry
if (data.error?.code === 'rate_limited' && data.error.wait_seconds !== undefined) {
const waitMs = Math.ceil(data.error.wait_seconds) * 1000;
console.log(
`${c.yellow}[RATE LIMITED]${c.reset} Waiting ${Math.ceil(data.error.wait_seconds)} seconds before retry...`,
);
await Bun.sleep(waitMs);
return execute(command, payload);
}
return data;
}
// =============================================================================
// Notification Display
// =============================================================================
type NotificationData = Record<string, unknown>;
type NotificationHandler = (data: NotificationData, time: string) => void;
const notificationHandlers: Record<string, NotificationHandler> = {
chat_message: (d, t) => {
console.log(
`${c.dim}[${t}]${c.reset} ${c.cyan}[CHAT:${d.channel || 'local'}]${c.reset} ${c.bright}${d.sender || 'Unknown'}${c.reset}: ${d.content || ''}`,
);
},
combat_update: (d, t) => {
const destroyed = d.destroyed ? ' - DESTROYED!' : '';
console.log(
`${c.dim}[${t}]${c.reset} ${c.red}[COMBAT]${c.reset} ${d.attacker || 'unknown'} hit ${d.target || 'unknown'} for ${d.damage || 0} ${d.damage_type || 'unknown'} damage (shield: ${d.shield_hit || 0}, hull: ${d.hull_hit || 0})${destroyed}`,
);
},
player_died: (d, t) => {
const cause = d.cause || 'combat';
if (cause === 'self_destruct') {
console.log(`${c.dim}[${t}]${c.reset} ${c.red}${c.bright}[DEATH]${c.reset} Self-destructed!`);
} else if (cause === 'police') {
console.log(`${c.dim}[${t}]${c.reset} ${c.red}${c.bright}[DEATH]${c.reset} Destroyed by system police!`);
} else {
console.log(
`${c.dim}[${t}]${c.reset} ${c.red}${c.bright}[DEATH]${c.reset} Destroyed by ${d.killer_name || 'unknown'}!`,
);
}
if (d.combat_log) {
const log = d.combat_log as Record<string, unknown>;
if (log.message) console.log(` ${log.message}`);
if (log.attacker_ship) console.log(` Attacker ship: ${log.attacker_ship}`);
if (log.weapons_used && Object.keys(log.weapons_used).length > 0) {
const weapons = Object.entries(log.weapons_used)
.map(([w, n]) => `${w} (x${n})`)
.join(', ');
console.log(` Weapons: ${weapons}`);
}
if ((log.total_damage as number) > 0) {
console.log(
` Damage taken: ${log.total_damage} total (${log.shield_damage || 0} shield, ${log.hull_damage || 0} hull) over ${log.combat_rounds || 0} round${log.combat_rounds !== 1 ? 's' : ''}`,
);
}
if (log.death_location) console.log(` Location: ${log.death_location} in ${log.death_system || 'unknown'}`);
}
if (d.ship_lost) console.log(` Ship lost: ${d.ship_lost}`);
if ((d.clone_cost as number) > 0) console.log(` Clone cost: ${d.clone_cost} credits`);
if ((d.insurance_payout as number) > 0) console.log(` Insurance payout: ${d.insurance_payout} credits`);
console.log(` Respawned at: ${d.respawn_base || 'home'} with ship fully repaired`);
},
mining_yield: (d, t) => {
const remainingMsg = d.remaining !== undefined ? ` (${d.remaining} remaining at POI)` : '';
console.log(
`${c.dim}[${t}]${c.reset} ${c.green}[MINED]${c.reset} +${d.quantity || 0}x ${d.resource_id || 'ore'}${remainingMsg}`,
);
},
trade_offer_received: (d, t) => {
console.log(
`${c.dim}[${t}]${c.reset} ${c.yellow}[TRADE]${c.reset} Offer from ${d.from_name || 'Someone'} (ID: ${d.trade_id || ''})`,
);
if ((d.offer_credits as number) > 0) console.log(` Offering: ${d.offer_credits} credits`);
if ((d.request_credits as number) > 0) console.log(` Requesting: ${d.request_credits} credits`);
console.log(` Use: trade_accept trade_id=${d.trade_id} or trade_decline trade_id=${d.trade_id}`);
},
scan_result: (d, t) => {
const target = d.username || d.target_id || 'unknown';
if (d.success) {
const revealed = (d.revealed_info as string[]) || [];
console.log(
`${c.dim}[${t}]${c.reset} ${c.cyan}[SCAN]${c.reset} Scan of ${target} revealed: ${revealed.join(', ')}`,
);
if (d.ship_class) console.log(` Ship: ${d.ship_class}`);
if (d.hull !== undefined) console.log(` Hull: ${d.hull}`);
if (d.shield !== undefined) console.log(` Shield: ${d.shield}`);
if (d.cloaked !== undefined) console.log(` Cloaked: ${d.cloaked}`);
} else {
console.log(
`${c.dim}[${t}]${c.reset} ${c.cyan}[SCAN]${c.reset} Scan of ${target} failed - insufficient scan power`,
);
}
},
scan_detected: (d, t) => {
const revealed = (d.revealed_info as string[]) || [];
console.log(
`${c.dim}[${t}]${c.reset} ${c.yellow}[SCANNED]${c.reset} You were scanned by ${d.scanner_username || 'Unknown'} (${d.scanner_ship_class || 'unknown'})`,
);
console.log(` They learned: ${revealed.join(', ')}`);
},
police_warning: (d, t) => {
console.log(`${c.dim}[${t}]${c.reset} ${c.red}${c.bright}[POLICE]${c.reset} ${d.message}`);
console.log(` Security level: ${d.police_level || 0}, Response in: ${d.response_ticks || 0} tick(s)`);
},
police_spawn: (d, t) => {
console.log(
`${c.dim}[${t}]${c.reset} ${c.red}${c.bright}[POLICE]${c.reset} ${d.num_drones || 0} police drone(s) arrived!`,
);
},
police_combat: (d, t) => {
const destroyed = d.destroyed ? ' - YOU WERE DESTROYED!' : '';
console.log(
`${c.dim}[${t}]${c.reset} ${c.red}[POLICE]${c.reset} Police drone dealt ${d.damage || 0} damage${destroyed}`,
);
},
skill_level_up: (d, t) => {
console.log(
`${c.dim}[${t}]${c.reset} ${c.green}${c.bright}[LEVEL UP]${c.reset} ${d.skill_id || 'unknown'} is now level ${d.new_level || 0}! (+${d.xp_gained || 0} XP)`,
);
},
drone_update: (d, t) => {
console.log(
`${c.dim}[${t}]${c.reset} ${c.blue}[DRONE]${c.reset} Your ${d.drone_type || 'drone'} drone dealt ${d.damage || 0} damage to ${d.target_id || 'target'}`,
);
},
drone_destroyed: (d, t) => {
console.log(
`${c.dim}[${t}]${c.reset} ${c.red}[DRONE]${c.reset} Your ${d.drone_type || 'drone'} drone was destroyed! (ID: ${d.drone_id || ''})`,
);
},