Repository navigation
Expand file tree
/
Copy pathremote_api.lua
More file actions
1317 lines (1204 loc) · 63.2 KB
/
Copy pathremote_api.lua
File metadata and controls
1317 lines (1204 loc) · 63.2 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
-- Multi-Team Support - scripts/remote_api.lua
-- Author: bits-orio
-- License: MIT
--
-- Public remote interface ("mts-v1") + custom events for third-party mods
-- that need to integrate with multi-team-support (e.g. chunk-gen mods like
-- dangOreus, VoidBlock that need to know about team surfaces).
--
-- Stability contract: the interface name "mts-v1" and every function /
-- event listed below is frozen for the v1 lifetime. Adding new
-- functions/events is safe; renaming/removing is not. When breaking
-- changes are needed, register a new "mts-v2" interface alongside.
--
-- ─── Subscribing as a third-party mod ─────────────────────────────────
--
-- -- Look the id up every session from on_init, on_configuration_changed
-- -- and on_load (remote.call is legal in all three; only the control.lua
-- -- main chunk refuses it). Never cache the id in storage: it shifts when
-- -- the mod set changes, and a stale id can stop a save from loading.
-- local function subscribe()
-- if not remote.interfaces["mts-v1"] then return end
-- local id = remote.call("mts-v1", "get_event_id", "on_team_surface_created")
-- script.on_event(id, function(event)
-- -- event.surface_name, event.force_name
-- end)
-- end
-- script.on_init(subscribe)
-- script.on_configuration_changed(subscribe)
-- script.on_load(subscribe)
--
-- ─── Querying state ───────────────────────────────────────────────────
--
-- if remote.interfaces["mts-v1"] then
-- local owner = remote.call("mts-v1", "get_surface_owner", "team-3-nauvis")
-- -- → "team-3" or nil
-- end
local surface_utils = require("scripts.surface_utils")
local helpers = require("scripts.helpers")
local team_clock = require("scripts.team_clock")
local spawn_labels = require("scripts.spawn_labels")
local pop_text = require("scripts.pop_text")
local chat_channel = require("scripts.chat_channel")
local chat_tag = require("scripts.chat_tag")
local team_incarnation = require("scripts.team_incarnation")
-- AI Agent Bridge tools; each owns its manifest entry and its function.
local reply = require("scripts.agent_tools.reply")
local team_lookup = require("scripts.agent_tools.team_lookup")
local records_tool = require("scripts.agent_tools.records")
local record_chase_tool = require("scripts.agent_tools.record_chase")
local player_team_history = require("scripts.player_team_history")
-- pause/control has no require cycle (it pulls only pause/power|wires|state),
-- so it is required directly here.
local pause_control = require("scripts.pause.control")
local pause_state = require("scripts.pause.state")
local pause_notify = require("scripts.pause.notify")
local team_pins = require("scripts.team_pins")
-- team_surfaces -> team_slots -> remote_api IS a require cycle. Factorio forbids
-- require() at runtime, so it also can't be lazy-loaded inside the interface
-- functions; control.lua injects it at parse time via set_deferred_deps().
local team_surfaces
local remote_api = {}
-- Parse-time dependency injection from control.lua, breaking the team_surfaces
-- require cycle described above. Must be called once during control.lua parsing.
function remote_api.set_deferred_deps(deps)
team_surfaces = deps.team_surfaces
end
-- ═══ Custom event IDs ═════════════════════════════════════════════════
--
-- Generated at module load — Factorio re-runs this file every session
-- (both on first init and on save load), so the IDs are stable for the
-- duration of each session. Third-party mods retrieve them via
-- remote.call("mts-v1", "get_event_id", "<name>") rather than hard-coding
-- numeric values, since the integers themselves may differ across
-- sessions.
remote_api.events = {
on_team_created = script.generate_event_name(),
on_team_released = script.generate_event_name(),
on_player_joined_team = script.generate_event_name(),
on_player_left_team = script.generate_event_name(),
on_team_surface_created = script.generate_event_name(),
-- Raised once per registered custom tab each time a player's Team Settings
-- panel is (re)built. Payload: { player_index, tab_name, element }, where
-- `element` is the empty content frame the registering mod should populate.
on_team_tab_built = script.generate_event_name(),
-- Raised once per registered welcome tab each time the welcome screen is
-- (re)built. Payload: { player_index, tab_name, element }, where `element`
-- is the empty content frame the registering mod should populate. Registered
-- (downstream-mod) tabs are shown FIRST, before MTS's own About/Discord, and
-- the first one is selected by default -- so a scenario like Expanse leads.
on_welcome_tab_built = script.generate_event_name(),
-- Raised once per registered widget each time a player opens a space
-- platform hub. Payload: { player_index, widget_name, element, entity },
-- where `element` is the empty content frame anchored into the hub GUI for
-- the registering mod to fill, and `entity` is the platform hub being
-- opened (use entity.surface.platform for the platform / its location).
on_platform_hub_gui_built = script.generate_event_name(),
-- Raised when an admin adds entries to the starter-items list while a
-- delivery override is registered (see register_starter_item_delivery).
-- Payload: { items = { {name=, count=}, ... } }. The registering mod is then
-- responsible for delivering them (e.g. into team logistic chests) since MTS
-- skips the default character-inventory grant while an override is active.
on_starter_items_added = script.generate_event_name(),
-- Raised when a team is renamed. Payload: { force_name, new_name }. (Not
-- `name` -- that key is reserved in event tables for the event id.) Lets a
-- mod refresh anything that shows the team name.
on_team_renamed = script.generate_event_name(),
-- Raised the instant a team's clock starts -- i.e. when the team has
-- "started playing". Fired once, at the same site that assigns
-- storage.team_clock_start[force_name]: on direct claim (team_slots) and on
-- the staged-start "Start Playing" commit (pre_start). Payload:
-- { force_name, start_tick }. Lets a mod begin per-team timed mechanics
-- (countdowns, grace periods) from the exact birth tick MTS uses.
on_team_clock_started = script.generate_event_name(),
-- Raised when a team is paused / resumed -- by the /mts-pause and
-- /mts-resume admin commands or the mts-v1 pause_team / unpause_team
-- actions. Payload: { force_name, source } where source is "admin" or
-- "script". Fires on actual transitions only (a re-pause of an already
-- paused team is silent), and regardless of the team_alerts_enabled admin
-- flag -- that flag gates only the in-game alert presentation.
on_team_paused = script.generate_event_name(),
on_team_resumed = script.generate_event_name(),
-- ── v2 candidates (uncomment to enable) ──────────────────────────
-- on_team_leader_changed = script.generate_event_name(),
-- on_friendship_activated = script.generate_event_name(),
-- on_friendship_broken = script.generate_event_name(),
-- on_team_surfaces_cleaned = script.generate_event_name(),
}
-- ═══ Custom Team Settings tabs ════════════════════════════════════════
--
-- Other mods can add their own tab to the Team Settings panel. They register
-- ONCE, in their on_init / on_configuration_changed (where remote.call is
-- legal) via:
-- remote.call("mts-v1", "register_team_tab",
-- { name = "my-mod", caption = "My Mod", order = "z" })
-- and listen to the on_team_tab_built event to populate the content frame they
-- are handed.
--
-- The registry lives in `storage` so it survives save/load and is identical on
-- every peer. This is what makes the API multiplayer-safe: a client joining
-- mid-game (or any reload) can't remote.call in on_load to re-register, so a
-- session-scoped registry would be empty on the joiner while populated on the
-- host -- a handler-identity mismatch / desync risk. Persisting it sidesteps
-- that: the spec is plain data and rides along in the save.
local function tab_registry()
storage.mts_custom_tabs = storage.mts_custom_tabs or {}
return storage.mts_custom_tabs
end
-- Validate a registration spec at the trust boundary (AT-2/AT-3): name must be a
-- string; order is coerced to a string/number (a mixed number-vs-string `order`
-- across two mods otherwise crashes the sort, and it recurs every session since
-- the registry persists); an unusable caption type is dropped (it would crash
-- pane.add); and the owning mod is captured so the entry can be swept when that
-- mod is removed (see validate_registry). Returns a sanitized entry or nil.
local function sanitize_spec(spec)
if type(spec) ~= "table" or type(spec.name) ~= "string" then return nil end
local order = spec.order
if type(order) ~= "string" and type(order) ~= "number" then order = spec.name end
local caption = spec.caption
if caption ~= nil and type(caption) ~= "string"
and type(caption) ~= "number" and type(caption) ~= "table" then
caption = nil
end
return {
name = spec.name,
caption = caption,
order = order,
mod = type(spec.mod) == "string" and spec.mod or nil,
}
end
-- Sort by order then name, coercing order to string so a legacy mixed-type entry
-- can never crash the comparator (defense behind sanitize_spec).
local function by_order_then_name(a, b)
local ao, bo = tostring(a.order), tostring(b.order)
if ao ~= bo then return ao < bo end
return a.name < b.name
end
-- Drop registry entries whose owning mod is no longer active (AT-3). Only
-- entries registered WITH a `mod` field are sweepable; entries without one
-- persist (a documented requirement for consumers).
function remote_api.validate_registry(storage_key)
local t = storage[storage_key]
if not t then return end
for k, def in pairs(t) do
if def.mod and not script.active_mods[def.mod] then t[k] = nil end
end
end
function remote_api.register_team_tab(spec)
local e = sanitize_spec(spec)
if not e then return end
e.caption = e.caption or e.name
tab_registry()[e.name] = e
end
--- Registered custom tabs, sorted by order then name.
function remote_api.get_team_tabs()
local list = {}
for _, def in pairs(tab_registry()) do list[#list + 1] = def end
table.sort(list, by_order_then_name)
return list
end
-- ═══ Custom welcome-screen tabs ═══════════════════════════════════════
--
-- Same contract as the team tabs above, for the centered welcome screen. A
-- downstream mod (e.g. a scenario like Expanse) registers ONCE in its on_init /
-- on_configuration_changed via:
-- remote.call("mts-v1", "register_welcome_tab",
-- { name = "my-mod", caption = "My Mod", order = "a" })
-- and listens to on_welcome_tab_built to fill the content frame it is handed.
-- Registered tabs render BEFORE MTS's own About/Discord and the first is
-- selected by default, so the host scenario leads the welcome screen. Registry
-- lives in storage for the same multiplayer-safe reason as the team tabs.
local function welcome_tab_registry()
storage.mts_welcome_tabs = storage.mts_welcome_tabs or {}
return storage.mts_welcome_tabs
end
function remote_api.register_welcome_tab(spec)
local e = sanitize_spec(spec)
if not e then return end
e.caption = e.caption or e.name
welcome_tab_registry()[e.name] = e
end
--- Registered welcome tabs, sorted by order then name.
function remote_api.get_welcome_tabs()
local list = {}
for _, def in pairs(welcome_tab_registry()) do list[#list + 1] = def end
table.sort(list, by_order_then_name)
return list
end
-- Space platform hub widgets: any mod can anchor its own UI into the native
-- space-platform-hub GUI (e.g. an "establish base" action). Register ONCE in
-- on_init / on_configuration_changed; the registry persists in storage so it
-- survives reloads/joins and is identical on every peer (same multiplayer-safe
-- design as the team tabs above). Listen to on_platform_hub_gui_built to fill
-- the anchored frame each time a player opens a hub.
local function hub_widget_registry()
storage.mts_hub_widgets = storage.mts_hub_widgets or {}
return storage.mts_hub_widgets
end
function remote_api.register_platform_hub_widget(spec)
local e = sanitize_spec(spec)
if not e then return end
-- caption stays optional for hub widgets (no default to name); position is a
-- relative_gui_position key, default "right".
e.position = (type(spec.position) == "string" and spec.position) or "right"
hub_widget_registry()[e.name] = e
end
--- Registered platform-hub widgets, sorted by order then name.
function remote_api.get_platform_hub_widgets()
local list = {}
for _, def in pairs(hub_widget_registry()) do list[#list + 1] = def end
table.sort(list, by_order_then_name)
return list
end
-- ═══ Open Discord Bridge forwarding ═══════════════════════════════════
--
-- Mirror MTS events to the Open Discord Bridge (interface open-discord-bridge-v1)
-- when it is installed. The remote.interfaces guard keeps the bridge an OPTIONAL
-- dependency of MTS — nothing breaks if it isn't present.
local BRIDGE_INTERFACE = "open-discord-bridge-v1"
-- Emoji shown in the bridge's "[mts → …]" category tag, keyed by mts.* event suffix.
-- Applied by emit_to_bridge unless the caller passes its own data.label. Emoji rules
-- (the bridge sends these to Discord verbatim from a bot):
-- • Unicode emoji (🔬, 🚀, …) always render — simplest, no setup.
-- • A bare :shortcode: does NOT render from a bot; it shows literally.
-- • A CUSTOM emoji must be its raw form <:name:id> AND live on a server the bot is in
-- (your own). Other servers' emoji (e.g. the official Factorio server's) won't render,
-- regardless of bot permissions — it's server membership, not a permission. Same-server
-- custom emoji need no special permission.
-- • Get the raw <:name:id>: type "\:lab:" (backslash first) in Discord and send it.
local BRIDGE_LABELS = {
research_finished = "<:lab:1507982217102753962>", -- a :lab: uploaded to our own server
player_joined = "📥",
player_left = "📤",
player_joined_team = "➕",
player_left_team = "➖",
player_switched_team = "🔀",
team_created = "🏁",
team_released = "🏳️",
team_surface_created = "🌎",
milestone_first = "🥇",
milestone_record = "⏱️",
rocket_launched = "🚀",
team_paused = "⏸️",
team_resumed = "▶️",
chat = "💬",
}
--- Emit an arbitrary event to the bridge (no-op if the bridge isn't installed). Fills in
--- the category-tag emoji from BRIDGE_LABELS unless the caller already set data.label.
function remote_api.emit_to_bridge(event, data)
if remote.interfaces[BRIDGE_INTERFACE] then
data = data or {}
if data.label == nil then
data.label = BRIDGE_LABELS[(event:gsub("^mts%.", ""))]
end
remote.call(BRIDGE_INTERFACE, "emit", { event = event, data = data })
end
end
--- Declare the mts.* event catalog so the bridge / control plane can offer
--- routable toggles without hardcoding MTS. Mutates the bridge's storage, so
--- call only from on_init / on_configuration_changed (never from on_load).
function remote_api.register_with_bridge()
if not remote.interfaces[BRIDGE_INTERFACE] then return end
remote.call(BRIDGE_INTERFACE, "register_source", {
namespace = "mts",
events = {
{ key = "team_created", description = "A team was created" },
{ key = "team_released", description = "A team was released" },
{ key = "player_joined_team", description = "A player joined a team" },
{ key = "player_left_team", description = "A player left a team" },
{ key = "team_surface_created", description = "A team surface was created" },
{ key = "milestone_first", description = "A team set a first-to-produce record" },
{ key = "milestone_record", description = "A team set a production speed record" },
{ key = "research_finished", description = "A team finished a technology" },
{ key = "player_joined", description = "A player joined the game (team-aware)" },
{ key = "player_left", description = "A player left the game (team-aware)" },
{ key = "player_switched_team", description = "A player switched teams mid-game" },
{ key = "rocket_launched", description = "A team launched a rocket" },
{ key = "team_paused", description = "A team was paused by an admin" },
{ key = "team_resumed", description = "A team was resumed by an admin" },
{ key = "chat", description = "A chat message (global channel only)" },
},
})
-- We announce these ourselves with team info, so turn off the bridge's team-less
-- baseline versions. The bridge only suppresses a baseline event while we're loaded.
-- "chat" is here for privacy, not enrichment: the bridge's baseline captures EVERY
-- message, but team-only channel messages (scripts/chat_channel.lua) must never
-- reach Discord — events/chat.lua emits the bridge copy for global messages only.
for _, key in ipairs({ "research_finished", "player_joined", "player_left", "rocket_launched", "chat" }) do
remote.call(BRIDGE_INTERFACE, "set_baseline", { event = key, enabled = false })
end
end
-- ensure_bridge_registered re-applies register_with_bridge once per session. on_init /
-- on_configuration_changed don't fire on a plain save reload (no version/mod-list change),
-- so a save that was running before the bridge existed — or a content-only mod edit during
-- development — would otherwise never (re)disable the baselines. Driving it from on_tick
-- (storage mutation is allowed there) makes the registration self-healing every session.
-- The flag is a module-load local, so it resets to false on each load.
local bridge_registered_this_session = false
function remote_api.ensure_bridge_registered()
if bridge_registered_this_session then return end
bridge_registered_this_session = true
remote_api.register_with_bridge()
end
--- Enrich a raise payload with Discord-friendly names (player + team display name)
--- without mutating the original event payload.
local function bridge_payload(payload)
local data = {}
for k, v in pairs(payload) do data[k] = v end
if payload.player_index then
local p = game.get_player(payload.player_index)
if p then data.player = p.name end
end
if payload.force_name then
data.team = (storage.team_names or {})[payload.force_name] or payload.force_name
end
return data
end
--- Build a human-readable sentence for the bridge to show. MTS owns this phrasing;
--- the bridge just displays the `text` field. Returns nil for unknown events (the
--- bridge then falls back to a key=value summary).
local function bridge_text(name, d)
local team = d.team or d.force_name
local who = d.player or (d.player_index and ("player " .. d.player_index))
if name == "on_team_created" then
return who and string.format("%s created %s", who, team)
or string.format("%s was created", team)
elseif name == "on_team_released" then
return string.format("%s was released", team)
elseif name == "on_player_joined_team" then
return string.format("%s joined %s", who or "A player", team)
elseif name == "on_player_left_team" then
return string.format("%s left %s", who or "A player", team)
elseif name == "on_team_surface_created" then
return string.format("Surface %s was created for %s", d.surface_name, team)
elseif name == "on_team_paused" then
-- Only admin-source pauses reach the bridge (see raise_team_paused).
return string.format("%s was paused by an admin", team)
elseif name == "on_team_resumed" then
return string.format("%s was resumed by an admin", team)
end
return nil
end
-- ═══ Internal raise helpers ═══════════════════════════════════════════
--
-- Called from mts code at the points where the corresponding state
-- transition completes. Guarded against missing IDs so commenting an
-- event out of `remote_api.events` doesn't crash the callers. Each raise also
-- mirrors to the bridge under the mts.* namespace (with the on_ prefix stripped).
-- raise() fires the frozen mts-v1 script event for third-party mods and (unless
-- opts.no_bridge) mirrors it to the Open Discord Bridge. The force-change events set
-- no_bridge because their bridge presentation is handled specially in
-- on_player_changed_force (deduped against the connect/disconnect messages).
local function raise(name, payload, opts)
opts = opts or {}
payload = payload or {}
local id = remote_api.events[name]
if id then script.raise_event(id, payload) end
if opts.no_bridge then return end
local data = bridge_payload(payload)
data.text = bridge_text(name, data)
remote_api.emit_to_bridge("mts." .. name:gsub("^on_", ""), data)
end
function remote_api.raise_team_created(force_name, leader_player_index)
raise("on_team_created", {
force_name = force_name,
player_index = leader_player_index,
})
end
function remote_api.raise_team_released(force_name)
raise("on_team_released", { force_name = force_name })
end
function remote_api.raise_player_joined_team(player_index, force_name)
raise("on_player_joined_team", {
player_index = player_index,
force_name = force_name,
}, { no_bridge = true })
end
function remote_api.raise_player_left_team(player_index, force_name)
raise("on_player_left_team", {
player_index = player_index,
force_name = force_name,
}, { no_bridge = true })
end
function remote_api.raise_team_surface_created(surface_name, force_name)
raise("on_team_surface_created", {
surface_name = surface_name,
force_name = force_name,
})
end
function remote_api.raise_starter_items_added(items)
raise("on_starter_items_added", { items = items or {} }, { no_bridge = true })
end
function remote_api.raise_team_renamed(force_name, new_name)
raise("on_team_renamed", { force_name = force_name, new_name = new_name }, { no_bridge = true })
end
--- Raised at the exact tick a team's clock starts (team has started playing).
--- Called from the two clock-start sites: direct claim (team_slots) and the
--- staged-start commit (pre_start). no_bridge: this is a fine-grained engine
--- signal for mods, not a Discord-worthy headline (team_created already covers
--- the social announcement).
function remote_api.raise_team_clock_started(force_name, start_tick)
raise("on_team_clock_started", {
force_name = force_name,
start_tick = start_tick,
}, { no_bridge = true })
end
-- ═══ Starter-item delivery override ═══════════════════════════════════
--
-- A consumer mod (e.g. Brave New MTS, whose teams have no player character to
-- receive items) can take over delivery of the admin-configured starter items.
-- While an override is registered, MTS stops inserting starter items into player
-- inventories and instead raises on_starter_items_added for live additions; the
-- consumer reads the persisted list via get_starter_items for teams that spawn
-- later. The registering mod name is stored so the override self-clears if that
-- mod is later removed (checked in on_configuration_changed).
function remote_api.register_starter_item_delivery(mod_name)
-- Reject a non-string mod name rather than coercing to an "unknown" sentinel,
-- which validate_delivery_override can never clear (it skips "unknown"), so a
-- bad call would suppress the default starter grant forever (AT-4).
if type(mod_name) ~= "string" then return end
storage.mts_starter_delivery = mod_name
end
function remote_api.starter_delivery_override()
return storage.mts_starter_delivery ~= nil
end
--- Drop a stale override if the mod that registered it is no longer loaded, so
--- removing the consumer restores the default character-inventory delivery.
function remote_api.validate_delivery_override()
local mod = storage.mts_starter_delivery
if mod and mod ~= "unknown" and not script.active_mods[mod] then
storage.mts_starter_delivery = nil
end
end
function remote_api.raise_team_paused(force_name, source)
-- Discord hears ADMIN pauses only: script pauses are routine gameplay for
-- consumers (e.g. a docking mod pausing on every dock cycle) and would
-- spam the channel. The mts-v1 event itself always fires.
raise("on_team_paused", { force_name = force_name, source = source or "script" },
{ no_bridge = source ~= "admin" })
end
function remote_api.raise_team_resumed(force_name, source)
raise("on_team_resumed", { force_name = force_name, source = source or "script" },
{ no_bridge = source ~= "admin" })
end
-- ── v2 candidates (uncomment alongside the matching event ID) ────────
-- function remote_api.raise_team_leader_changed(force_name, old_player_index, new_player_index)
-- raise("on_team_leader_changed", {
-- force_name = force_name,
-- old_leader_player_index = old_player_index,
-- new_leader_player_index = new_player_index,
-- })
-- end
--
-- function remote_api.raise_friendship_activated(force_name_a, force_name_b)
-- raise("on_friendship_activated", {
-- force_name_a = force_name_a,
-- force_name_b = force_name_b,
-- })
-- end
--
-- function remote_api.raise_friendship_broken(force_name_a, force_name_b)
-- raise("on_friendship_broken", {
-- force_name_a = force_name_a,
-- force_name_b = force_name_b,
-- })
-- end
--
-- function remote_api.raise_team_surfaces_cleaned(force_name, surface_names)
-- raise("on_team_surfaces_cleaned", {
-- force_name = force_name,
-- surface_names = surface_names,
-- })
-- end
-- ═══ on_player_changed_force adapter ══════════════════════════════════
--
-- Called from control.lua's on_player_changed_force handler. Translates
-- a single Factorio event into the appropriate join/leave raises so the
-- buddy-join flow, /mts-rejoin, and admin force moves are all covered
-- automatically — callers don't have to remember to fire these.
-- The type()-guarded team-force predicate now lives in helpers (AT-1 boundary
-- safety travels with it). Aliased locally so this module's many call sites and
-- the trust-boundary intent read unchanged.
local is_team_force_name = helpers.is_team_force
function remote_api.on_player_changed_force(event)
local old_name = event.force and event.force.name
local player = game.get_player(event.player_index)
local new_name = player and player.force and player.force.name
local old_team = is_team_force_name(old_name)
local new_team = is_team_force_name(new_name)
-- Always fire the frozen mts-v1 script events for third-party mods (both halves of a
-- switch). These no longer auto-bridge; the bridge presentation is decided below.
if old_team then remote_api.raise_player_left_team(event.player_index, old_name) end
if new_team then remote_api.raise_player_joined_team(event.player_index, new_name) end
-- Suppress bridge messages when the player is temporarily on the spectator force due to
-- the spectate-another-surface feature. spectator_real_force is set before the force
-- change and cleared after restore, so its presence here reliably identifies a
-- spectate hop vs. a real landing-pen join/leave.
local sf = storage.spectator_real_force
local is_spectator_hop = sf and sf[event.player_index] ~= nil
and (new_name == "spectator" or old_name == "spectator")
if is_spectator_hop then return end
-- Team pins ride this same funnel by direct dispatch (never via the mts-v1
-- events). Placed after the hop early-return so a spectate round-trip can
-- never churn pins; pcall-contained because this adapter runs inside the
-- engine force-change event for every join/leave path.
if old_team and player then pcall(team_pins.on_team_left, player, old_name) end
if new_team and player then pcall(team_pins.on_team_joined, player) end
-- Bridge presentation: one deduped sentence per force change.
local who = player and player.name or ("player " .. event.player_index)
if old_team and new_team then
-- Mid-game switch between two teams → a single "switched" line.
remote_api.emit_to_bridge("mts.player_switched_team", {
player = who,
from = helpers.team_display(old_name),
to = helpers.team_display(new_name),
text = string.format("%s switched to %s", who, helpers.team_display(new_name)),
})
elseif new_team then
-- Joined a team from a non-team force. The initial auto-claim on connect
-- coincides with the mts.player_joined connect message, so it's suppressed
-- (flag set by the lifecycle handler); deliberate later joins still announce.
local suppress = storage.odb_suppress_claim
if suppress and suppress[event.player_index] then
suppress[event.player_index] = nil
else
remote_api.emit_to_bridge("mts.player_joined_team", {
player = who,
team = helpers.team_display(new_name),
text = string.format("%s joined %s", who, helpers.team_display(new_name)),
})
end
elseif old_team then
-- Left a team to a non-team force (e.g. spectator). Disconnects don't reach
-- here (disconnecting doesn't change force) — those go through mts.player_left.
remote_api.emit_to_bridge("mts.player_left_team", {
player = who,
team = helpers.team_display(old_name),
text = string.format("%s left %s", who, helpers.team_display(old_name)),
})
end
end
-- ═══ Server connect/disconnect (team-aware) ═══════════════════════════
--
-- Called from the player-lifecycle handlers. These replace the bridge's team-less
-- baseline player_joined/player_left (which register_with_bridge disables), tagging the
-- player's current team when they're on one.
-- Resolve the player's real team even mid-spectate: a spectating player is on
-- the "spectator" force, but storage.spectator_real_force remembers their team.
-- Read inline (no spectator require) to match the existing get_effective_force
-- implementation and avoid a circular require.
local function effective_fn(player)
return (storage.spectator_real_force or {})[player.index]
or (player.force and player.force.name)
end
local function connection_text(verb, player)
local fn = effective_fn(player)
if is_team_force_name(fn) then
return string.format("%s %s — %s", player.name, verb, helpers.team_display(fn))
end
return string.format("%s %s", player.name, verb)
end
--- Bridge copy of a chat message. The bridge's baseline chat capture is
--- disabled (register_with_bridge) so team-only messages never reach
--- Discord; every message that SHOULD bridge — global channel, "!" shouts,
--- spectator and server-console chatter — flows through here instead.
--- force_name is the author's team (nil for spectators / the server).
function remote_api.emit_chat(author_name, message, force_name)
local team = is_team_force_name(force_name)
and helpers.team_display(force_name) or nil
remote_api.emit_to_bridge("mts.chat", {
player = author_name,
team = team,
text = (team and (author_name .. " [" .. team .. "]") or author_name)
.. ": " .. message,
})
end
function remote_api.emit_player_joined(player)
if not (player and player.valid) then return end
local fn = player.force and player.force.name
remote_api.emit_to_bridge("mts.player_joined", {
player = player.name,
team = is_team_force_name(fn) and helpers.team_display(fn) or nil,
online_count = #game.connected_players,
text = connection_text("joined the game", player),
})
end
function remote_api.emit_player_left(player)
if not (player and player.valid) then return end
-- A member disconnecting mid-spectate is still on the "spectator" force here
-- (spectator.on_player_left restores it one line later), so resolve the real
-- team to avoid reporting them team-less to the bridge.
local fn = effective_fn(player)
remote_api.emit_to_bridge("mts.player_left", {
player = player.name,
team = is_team_force_name(fn) and helpers.team_display(fn) or nil,
online_count = #game.connected_players,
text = connection_text("left the game", player),
})
end
-- ═══ Query implementations ════════════════════════════════════════════
local function team_slot_status(force_name)
local slot = helpers.team_slot(force_name)
if not slot then return nil end
return (storage.team_pool or {})[slot]
end
local function team_member_count(force)
if not (force and force.valid) then return 0 end
local n = 0
for _ in pairs(force.players) do n = n + 1 end
return n
end
local function get_team_info_impl(force_name)
if not is_team_force_name(force_name) then return nil end
local force = game.forces[force_name]
if not force or not force.valid then return nil end
local status = team_slot_status(force_name)
local leader_index = (storage.team_leader or {})[force_name]
local clock_start = (storage.team_clock_start or {})[force_name]
local display_name = (storage.team_names or {})[force_name] or force_name
local is_paused = (storage.paused_forces or {})[force_name] and true or false
return {
force_name = force_name,
display_name = display_name,
status = status,
is_occupied = status == "occupied",
leader_player_index = leader_index,
member_count = team_member_count(force),
is_paused = is_paused,
clock_start_tick = clock_start,
online_ticks = team_clock.online_ticks(force_name),
}
end
local function get_team_list_impl()
local list = {}
local pool = storage.team_pool or {}
-- Iterate slot indices in order so output is deterministic.
local n = 0
for slot in pairs(pool) do if slot > n then n = slot end end
for slot = 1, n do
local force_name = "team-" .. slot
local info = get_team_info_impl(force_name)
if info then list[#list + 1] = info end
end
return list
end
local function is_team_surface_impl(surface_name)
if type(surface_name) ~= "string" then return false end
local surface = game.surfaces[surface_name]
if not surface then return false end
return surface_utils.get_owner(surface) ~= nil
end
local function get_surface_owner_impl(surface_name)
if type(surface_name) ~= "string" then return nil end
local surface = game.surfaces[surface_name]
if not surface then return nil end
return surface_utils.get_owner(surface)
end
--- The admin-configured starter items ({name=, count=} list). Used by a
--- delivery-override consumer to seed teams that spawn after items were added.
local function get_starter_items_impl()
return storage.starter_items or {}
end
local function list_team_surfaces_impl(force_name)
if not is_team_force_name(force_name) then return {} end
local out = {}
for _, surface in pairs(game.surfaces) do
if surface.valid and surface_utils.get_owner(surface) == force_name then
out[#out + 1] = surface.name
end
end
return out
end
-- ── Passive radar (spectate liveness) ────────────────────────────────
-- Ensure a hidden, powerless, non-charting passive radar exists at `position`
-- on `surface` (name, index, or LuaSurface) owned by `force_name`, so the
-- surface stays live-viewable for spectators even when no team member stands on
-- it. The radar's constantly-revealed ring belongs to the team force, so it is
-- shared to chart-sharing spectators with no power draw and no map charting
-- (see prototypes/entities/passive-radar.lua). Idempotent per (surface,
-- position): a repeat call returns the existing radar rather than stacking
-- duplicates -- so consumers safely re-call it after every surface clone (which
-- gives the radar a new unit_number on a new surface) and place several at
-- different coordinates to cover a base larger than one ring. Returns the
-- LuaEntity (all mods share one Lua state, so the reference is valid for the
-- caller) or nil if the surface/force is invalid.
local PASSIVE_RADAR_NAME = "mts-passive-radar"
local function resolve_surface(surface_ref)
local t = type(surface_ref)
if t == "string" or t == "number" then
return game.surfaces[surface_ref]
end
-- LuaSurface passed directly (same Lua state across mods). A LuaObject's type()
-- is engine-dependent (table or userdata), so don't gate on it -- just probe
-- object_name behind a pcall in case it's some unrelated value.
if t == "table" or t == "userdata" then
local ok, on = pcall(function() return surface_ref.object_name end)
if ok and on == "LuaSurface" then return surface_ref end
end
return nil
end
local function ensure_passive_radar_impl(force_name, surface_ref, position)
local force = type(force_name) == "string" and game.forces[force_name]
if not (force and force.valid) then return nil end
local surface = resolve_surface(surface_ref)
if not (surface and surface.valid) then return nil end
-- Shape-guard position: a non-table (number/string) would error in the engine
-- find_entities_filtered / create_entity calls below (AT-5).
if type(position) ~= "table" then position = {x = 0, y = 0} end
-- Re-assert ownership + the inert flags on every call. A radar carried across
-- a surface clone can come back with default flags (destructible true), so we
-- harden on the found path too, not just on create.
local function harden(radar)
if not (radar and radar.valid) then return nil end
if radar.force ~= force then radar.force = force end
radar.destructible = false
radar.operable = false
radar.minable_flag = false
-- 2.1: also stop automated weapons targeting it -- the radar is
-- team-owned (at war with biters) and destructible=false only blocks
-- the damage, not the aggro/ammo waste.
radar.protected = true
return radar
end
-- Idempotent: reuse a passive radar already at this spot. find_entity is
-- unreliable here (the radar has a zero collision box), so match by position.
local found = surface.find_entities_filtered{name = PASSIVE_RADAR_NAME, position = position, radius = 1}
if found[1] and found[1].valid then return harden(found[1]) end
return harden(surface.create_entity{name = PASSIVE_RADAR_NAME, position = position, force = force})
end
-- ── v2 candidates (uncomment to enable) ──────────────────────────────
-- local function get_team_home_surface_impl(force_name)
-- if not is_team_force_name(force_name) then return nil end
-- local force = game.forces[force_name]
-- if not force then return nil end
-- local s = surface_utils.get_home_surface(force, nil)
-- return s and s.valid and s.name or nil
-- end
--
-- local function is_team_paused_impl(force_name)
-- return (storage.paused_forces or {})[force_name] and true or false
-- end
--
-- local function are_teams_friends_impl(a, b)
-- local fa, fb = game.forces[a], game.forces[b]
-- if not (fa and fb) then return false end
-- return fa.get_friend(fb) and fb.get_friend(fa) or false
-- end
--
-- local function get_team_members_impl(force_name)
-- local force = game.forces[force_name]
-- if not (force and force.valid) then return {} end
-- local leader_idx = (storage.team_leader or {})[force_name]
-- local out = {}
-- for _, p in pairs(force.players) do
-- out[#out + 1] = {
-- player_index = p.index,
-- player_name = p.name,
-- is_leader = p.index == leader_idx,
-- is_connected = p.connected,
-- }
-- end
-- return out
-- end
--
-- local function get_landing_pen_count_impl()
-- local n = 0
-- local pen = game.surfaces["landing-pen"]
-- if not pen then return 0 end
-- for _, p in pairs(game.players) do
-- if p.connected and p.surface and p.surface.index == pen.index then
-- n = n + 1
-- end
-- end
-- return n
-- end
-- ═══ Remote interface registration ════════════════════════════════════
--- Who may hear an AI assistant's reply to this player's question. This is
--- the chat scope probe AI Agent Bridge's companion scans every remote
--- interface for (its README, "Chat scope by probe, chat_scope_v1"); that
--- mod never names MTS, and MTS never names it beyond this comment. The
--- answer follows the player's chat channel exactly: team-only chat means a
--- private reply to the team, carrying the same [TEAM] badge the player's
--- own lines carry; global chat, a "!" shout, a pen spectator or a player
--- with no team means a reply to everyone with the [GLOBAL] badge.
---
--- The audience is the team's connected members by index rather than the
--- force, because a member force-swapped into spectator mode is still on
--- the team and must hear the reply too (chat_channel.peers has the same
--- rule for channel announcements).
---
--- The key names the team, not just its slot: the force name plus the tick
--- the team claimed the slot, "team-4@81234" (scripts/team_incarnation.lua).
--- MTS reuses slots, and the bridge keeps chat history longer than a team
--- lasts, so a key that was only the force name would let the next team in
--- this slot read this team's private chat. Nothing in MTS reads the key.
---
--- Only a claimed slot has a team. A player on a released slot's force (an
--- admin's console move, say) gets the global scope, never a team key.
local function chat_scope_v1(player_index, text)
local player = type(player_index) == "number" and game.get_player(player_index) or nil
if not (player and player.valid) then return nil end
local fn = effective_fn(player)
local shout = type(text) == "string" and text:sub(1, 1) == "!"
local team = is_team_force_name(fn) and team_slot_status(fn) == "occupied"
if not team or shout or not chat_channel.is_local_for(player) then
return { key = "global", private = false, tag = chat_tag.GLOBAL_BADGE }
end
local members = {}
for _, p in pairs(game.connected_players) do
if effective_fn(p) == fn then members[#members + 1] = p.index end
end
return {
key = team_incarnation.key(fn),
private = true,
audience = { players = members },
label = helpers.team_display(fn),
tag = chat_tag.LOCAL_BADGE,
}
end
--- The force a player's questions are about, for the same assistant: its
--- companion scans for `home_force_v1`. A member watching another team sits
--- on the spectator force but is still on their team, and "how about our
--- team?" asked from there is about that team. Asked on the live server, it
--- was answered for the spectator force instead.
local function home_force_v1(player_index)
local player = type(player_index) == "number" and game.get_player(player_index) or nil
if not (player and player.valid) then return nil end
return effective_fn(player)
end
--- The team whose base a spectating player is looking at, for the same
--- assistant (`watching_force_v1`); nil when they spectate nobody. Asked
--- "are we making repair packs here?" while watching another team, it
--- searched the asker's own machines and said nothing there made any.
local function watching_force_v1(player_index)
local player = type(player_index) == "number" and game.get_player(player_index) or nil
if not (player and player.valid) then return nil end
return (storage.spectating_target or {})[player.index]
end
--- What players call each claimed team, for the same assistant: its
--- companion scans for `force_labels_v1` and tells the model, so an answer
--- says "Team Ace" and never "team-1". The label carries the team's colour,
--- the same tag announcements use: the companion keeps a label's colour and
--- font tags when it prints a team name (and strips any other tag), so a
--- team reads the same in the assistant's answers as it does everywhere
--- else. Plain text was sent while the companion stripped every tag, and
--- team names came out uncoloured in every answer for it.
local function force_labels_v1()
local labels = {}
for _, info in ipairs(get_team_list_impl()) do
labels[info.force_name] = helpers.team_tag(info.force_name)
end
return labels
end
--- Tools for an AI assistant (AI Agent Bridge's agent_tools_v1 seam: its
--- companion scans every interface for this probe and offers the tools to
--- the model; `force` is injected into every call). All reads. Two are about
--- the thing the server's own clock cannot tell: each team keeps its own
--- clock, running only while a member is online, so comparing teams means
--- comparing these, never game time. The rest read what MTS alone keeps:
--- records, and how often a player started over. Doubles leave through
--- reply.hours as short strings.
---
--- The functions are frozen like the rest of mts-v1, but their replies are
--- shaped for the model and may change in any release (docs/MTS_API.md). A
--- mod that needs team data calls get_team_list or get_team_info instead.
--- Ticks on a team's own clock. It starts at the claim, or under Staged
--- Start when the leader clicks Start Playing; nil until then.
local function elapsed_of(info)
return info.clock_start_tick and (game.tick - info.clock_start_tick) or nil
end
local function clock_row(info)
local elapsed = elapsed_of(info)
return {
force = info.force_name,