-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_dialectic_pipeline.php
More file actions
2948 lines (2485 loc) · 130 KB
/
Copy pathmain_dialectic_pipeline.php
File metadata and controls
2948 lines (2485 loc) · 130 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
<?php
/* Definitions and main includes */
error_reporting(E_ALL);
ini_set('display_errors', '0');
ini_set('log_errors', '1');
@define("STOPALL_MAGIC_WORD", "/wake up/i");
@define("MAXIMUM_SENTENCE_SIZE", 125);
@define("MINIMUM_SENTENCE_SIZE", 75);
date_default_timezone_set('America/Los_Angeles');
if (!function_exists('mb_scrub')) {
function mb_scrub($string, $encoding = null)
{
return is_string($string) ? $string : '';
}
}
$GLOBALS["AVOID_TTS_CACHE"]=true;
$GLOBALS["DIALECTIC_NO_EXAMPLES"]=true; // Keep prompt examples disabled for the Dialectic runtime.
$GLOBALS["MEMORY_THRESHOLD_MODIFIER"]=0; // POST MEMORY
$GLOBALS["fallout_start_date"] = '2281-10-19 00:00:00'; // Fallout: New Vegas start period used for in-game date conversion.
$GLOBALS["DIALECTIC_GAME_ID"] = "fnv";
$GLOBALS["DIALECTIC_WORLD_NAME"] = "Mojave Wasteland";
$GLOBALS["SEMAPHORES_TIMEOUT"] = 300;
$GLOBALS["TTS_INJECT_NONVERBAL_VOCALIZATION"] = true; // Spice the TTS with non-verbal vocalization when expressing strong emotion.
$GLOBALS['use_emotions_expression'] = true;
// Cooldown for some actions
$COOLDOWNMAP=[];
$path = dirname((__FILE__)) . DIRECTORY_SEPARATOR;
$GLOBALS["ENGINE_PATH"]=$path;
require_once($path . "lib/runtime_bootstrap.php");
require_once($path . "lib/request.php");
require_once($path . "lib/response.php");
require_once($path . "lib/player_tts_helpers.php");
dialecticRuntimeBootstrap($path, [
'load_general_settings' => true,
'load_stt_connector' => true,
'load_player_name' => true,
'load_narrator' => true,
'run_db_updates' => false,
]);
require_once($path . "lib/player2_health.php");
require_once($path . "lib/auditing.php");
require_once($path . "lib/model_dynmodel.php");
require_once($path . "lib/minimet5_service.php");
require_once($path . "lib/data_functions.php");
require_once($path . "lib/chat_helper_functions.php");
require_once($path . "lib/lazy_xml.php");
require_once($path . "lib/memory_helper_vectordb.php");
require_once($path . "lib/llm_randomizer.php");
require_once($path . "lib/utils_game_timestamp.php");
require_once($path . "lib/logger.php");
require_once($path . "lib/save_rollback.php");
require_once($path . "processor/captured_dialogue.php");
// New profile system
require_once($path . "lib/core/api_badge.class.php");
require_once($path . "lib/core/llm_connector.class.php");
require_once($path . "lib/core/tts_connector.class.php");
require_once($path . "lib/core/npc_master.class.php");
require_once($path . "lib/core/core_profiles.class.php");
require_once($path . "lib/semaphore_manager.class.php");
// Normalize the structured JSON request into the internal $gameRequest tuple.
$cooldownPeriod = 600;
if (php_sapi_name()=="cli" && !getenv('PHPUNIT_TEST')) {
// You can run this script directly with php: main.php "Player text"
$GLOBALS["db"] = new sql();
$db = $GLOBALS["db"];
$latsRid=$db->fetchAll("select * from eventlog order by rowid desc LIMIT 1 OFFSET 0");
$res=$db->fetchAll("select max(gamets)+1 as gamets,max(ts)+1 as ts from eventlog where rowid={$latsRid[0]["rowid"]}");
$res[0]["ts"]=$res[0]["ts"]+1;
$res[0]["gamets"]=$res[0]["gamets"]+1;
$dialecticRequestEvent = dialectic_normalize_json_event([
"schema" => "dialectic.input.v1",
"type" => "inputtext",
"ts" => $res[0]["ts"],
"gamets" => $res[0]["gamets"],
"player" => [
"name" => $GLOBALS["PLAYER_NAME"] ?? "Player",
],
"target" => [
"name" => $GLOBALS["DIALECTIC_NAME"] ?? "The Narrator",
],
"text" => $argv[1] ?? "",
"game" => "fnv",
"response_format" => "json",
]);
$receivedData = dialectic_event_to_received_data($dialecticRequestEvent);
$GLOBALS["DIALECTIC_REQUEST_EVENT"] = $dialecticRequestEvent;
$GLOBALS["DIALECTIC_RESPONSE_FORMAT"] = "json";
dialecticRuntimeSetActiveProfile($argv[2] ?? '');
$GLOBALS["FUNCTIONS_ARE_ENABLED"]=true;
unset($GLOBALS["db"]);
} else {
$dialecticRequestEvent = dialectic_decode_event_from_request();
if (!empty($dialecticRequestEvent["request_id"])) {
Logger::setRequestId((string)$dialecticRequestEvent["request_id"]);
} elseif (!empty($dialecticRequestEvent["payload"]["request_id"])) {
Logger::setRequestId((string)$dialecticRequestEvent["payload"]["request_id"]);
} else {
Logger::bootstrapRequestId("main");
}
$receivedData = mb_scrub(dialectic_event_to_received_data($dialecticRequestEvent));
$GLOBALS["DIALECTIC_REQUEST_EVENT"] = $dialecticRequestEvent;
$GLOBALS["DIALECTIC_RESPONSE_FORMAT"] = "json";
$acceptHeader = strtolower((string)($_SERVER["HTTP_ACCEPT"] ?? ""));
$streamHeader = strtolower((string)($_SERVER["HTTP_X_DIALECTIC_STREAM"] ?? ""));
$GLOBALS["DIALECTIC_RESPONSE_STREAMING"] = dialectic_should_stream_json_response(
$dialecticRequestEvent,
$acceptHeader,
$streamHeader
);
// Runtime profile is resolved from JSON payload data later in the pipeline.
}
if (!isset($FUNCTIONS_ARE_ENABLED)) {
$FUNCTIONS_ARE_ENABLED=false;
}
if (!function_exists('dialecticSummarizePlayerConsumedPayload')) {
function dialecticSummarizePlayerConsumedPayload(string $rawPayload): string
{
$payload = json_decode($rawPayload, true);
if (!is_array($payload)) {
return $rawPayload;
}
$text = trim((string)($payload["text"] ?? ""));
if ($text !== "") {
return $text;
}
$playerName = trim((string)($payload["player"] ?? ($GLOBALS["PLAYER_NAME"] ?? "The Courier")));
$itemNames = [];
foreach (($payload["items"] ?? []) as $item) {
if (!is_array($item)) {
continue;
}
$name = trim((string)($item["name"] ?? ""));
if ($name !== "") {
$itemNames[] = $name;
}
}
if (empty($itemNames) && isset($payload["item"]) && is_array($payload["item"])) {
$name = trim((string)($payload["item"]["name"] ?? ""));
if ($name !== "") {
$itemNames[] = $name;
}
}
if (empty($itemNames)) {
return $rawPayload;
}
if (count($itemNames) === 1) {
$itemText = $itemNames[0];
} elseif (count($itemNames) === 2) {
$itemText = $itemNames[0] . " and " . $itemNames[1];
} else {
$last = array_pop($itemNames);
$itemText = implode(", ", $itemNames) . ", and " . $last;
}
return $playerName . " consumed " . $itemText;
}
}
while (!getenv('PHPUNIT_TEST') && ob_get_length() && ob_end_clean()) ;
if (!getenv('PHPUNIT_TEST')) {
dialectic_start_json_response_buffer();
}
ignore_user_abort(true);
set_time_limit(1200);
$momentum=time();
$GLOBALS["runid"]=uniqid("run_",false);
// Array with sentences talked so far
$talkedSoFar = array();
// Array with sentences sent so far
$alreadysent = array();
// Array with parameters to override
$overrideParameters=array();
$ERROR_TRIGGERED=false;
$LAST_ROLE="user";
// SCRIPT LINE QUEUE
$GLOBALS["SCRIPTLINE_EXPRESSION"]="";
$GLOBALS["SCRIPTLINE_LISTENER"]="";
$GLOBALS["SCRIPTLINE_ANIMATION"]="";
$GLOBALS["TTS_FFMPEG_FILTERS"]=[];
/**********************
MAIN FLOW
***********************/
if (isset($GLOBALS["DIALECTIC_REQUEST_EVENT"]) && is_array($GLOBALS["DIALECTIC_REQUEST_EVENT"])) {
$gameRequest = dialectic_event_to_game_request($GLOBALS["DIALECTIC_REQUEST_EVENT"]);
} else {
$gameRequest = ["", "", "", ""];
}
$GLOBALS["gameRequest"] = &$gameRequest;
unset($GLOBALS["DIALECTIC_TURN_PEOPLE_SNAPSHOT"]);
$startTime = microtime(true);
$GLOBALS["DIALECTIC_TURN_START_TIME"] = $startTime;
//error_log("Audit run ID: " . $GLOBALS["AUDIT_RUNID"]. " ({$gameRequest[0]}) started: ".$startTime);
$GLOBALS["AUDIT_RUNID_REQUEST"]=$gameRequest[0];
$gameRequest[0] = strtolower($gameRequest[0]); // Who put 'diary' uppercase?
if (PHP_SAPI !== 'cli' && !getenv('PHPUNIT_TEST') && $gameRequest[0] !== 'request') {
dialecticPlayer2HealthMarkGameActivity();
}
Logger::phaseStart("turn", [
"type" => $gameRequest[0],
"gamets" => $gameRequest[2] ?? "",
"payload_preview" => isset($gameRequest[3]) ? Logger::summarizePayload((string)$gameRequest[3], 180) : "",
]);
Logger::info("[main] Request start" . Logger::formatContext([
"type" => $gameRequest[0],
"ts" => $gameRequest[1] ?? "",
"gamets" => $gameRequest[2] ?? "",
"streaming" => !empty($GLOBALS["DIALECTIC_RESPONSE_STREAMING"]),
]));
if (($gameRequest[0] ?? '') !== 'init') {
dialecticMaybeHandleIncomingGametsRollback($gameRequest[2] ?? 0, 'main:' . ($gameRequest[0] ?? 'unknown'), false);
}
if (in_array($gameRequest[0], ["conversation_start", "conversation_end"], true)) {
$conversationSpeaker = function_exists('dialectic_extract_conversation_target')
? dialectic_extract_conversation_target((string)($gameRequest[3] ?? ""))
: "The Narrator";
if ($gameRequest[0] === "conversation_start") {
// Conversation start is state-only. Speaking a greeting here blocks the
// first real player response when chat opens and inputtext is sent.
} else {
dialectic_buffer_response_close();
}
if (dialectic_json_response_enabled()) {
dialectic_emit_buffered_json_response();
}
@flush();
exit;
}
// Database Connection
$db = $GLOBALS["db"] ?? new sql();
$GLOBALS["db"] = $db;
if (isset($gameRequest[3]) && is_string($gameRequest[3]) && in_array($gameRequest[0], [
'infoplayer',
'playerinfo',
'newgame',
'conversation_start',
'inputtext',
'inputtext_s',
'narrator_inputtext',
'cheatmode',
], true)) {
dialecticMaybeSyncPlayerNameFromGamePayload($gameRequest[3]);
}
if ($gameRequest[0] === "captured_dialogue") {
dialecticHandleCapturedDialogueEvent($gameRequest);
if (dialectic_json_response_enabled()) {
dialectic_emit_buffered_json_response();
}
@flush();
exit;
}
require_once($path . "processor" .DIRECTORY_SEPARATOR."dialectic_modes.php");
if (function_exists("dialectic_adapt_json_input_payload_for_pipeline")) {
$normalizedInputPayload = dialectic_adapt_json_input_payload_for_pipeline($gameRequest);
if (!empty($normalizedInputPayload["changed"])) {
Logger::info("[main] Adapted structured JSON input payload for dialogue pipeline" . Logger::formatContext([
"player" => $normalizedInputPayload["player"] ?? "",
"target" => $normalizedInputPayload["target"] ?? "",
"chars" => strlen((string)($normalizedInputPayload["text"] ?? "")),
"skip_player_tts" => !empty($normalizedInputPayload["skip_player_tts"]) ? "true" : "false",
]));
}
}
if (function_exists("dialectic_adapt_json_vision_payload_for_pipeline")) {
$normalizedVisionPayload = dialectic_adapt_json_vision_payload_for_pipeline($gameRequest);
if (!empty($normalizedVisionPayload["changed"])) {
Logger::info("[main] Adapted structured PipVision payload for vision pipeline" . Logger::formatContext([
"target" => $normalizedVisionPayload["target"] ?? "",
"chars" => strlen((string)($normalizedVisionPayload["description"] ?? "")),
]));
}
}
// In directed DIALECTIC modes, normalize incoming dialogue tags so logs/prompts stay aligned
// with the active speaking style.
$dialecticExecutionMode = strtoupper((string)($GLOBALS["DIALECTIC_EXECUTION_MODE"] ?? ""));
if (isset($gameRequest[3]) && is_string($gameRequest[3]) &&
in_array($gameRequest[0], ["inputtext", "inputtext_s", "narrator_inputtext", "chat", "prechat", "rechat", "continue"], true)) {
if ($dialecticExecutionMode === "WHISPER") {
$gameRequest[3] = convertTalkingTagsToWhispering($gameRequest[3]);
} elseif ($dialecticExecutionMode === "SHOUT") {
$gameRequest[3] = convertTalkingTagsToShouting($gameRequest[3]);
}
}
if (in_array($gameRequest[0],["inputtext","inputtext_s","narrator_inputtext","cheatmode","instruction","init"])) {
// This is just a mark that user has made an input request. We will check later when waiting for LLm response
// if user has made input after initial request, so we can abort it.
// $db = new sql();
$db->insert(
'eventlog',
array(
'ts' => $gameRequest[1],
'gamets' => $gameRequest[2],
'type' => "user_input",
'data' => $gameRequest[0],
'sess' => 'pending',
'localts' => time(),
'people'=> '',
'location'=>'',
'party'=>''
)
);
// unset($db);
}
$fast_commands = ["updateprofile","updateprofile_narrator","diary","diary_narrator","diary_player","setconf","request","_speech","captured_dialogue",
"infoaction","status_msg","delete_event","itemfound","chat","goodnight","waitstart","waitstop",
"updateprofiles_batch_async","core_profile_assign","switchrace","combatbark",
"region"];
$GLOBALS["all_fast_commands"] = $fast_commands;
$semaphore_timeout = $GLOBALS["SEMAPHORES_TIMEOUT"] ?? 300;
// Use logical id "MAIN" so other code can still find $GLOBALS["SEMAPHORES"]["MAIN"]
if (!in_array($gameRequest[0],$fast_commands)) {
if (!SemaphoreWait("MAIN", $semaphore_timeout, 1003, null)) {
Logger::warn("[main] main semaphore wait failed for {$gameRequest[0]}");
terminate();
}
Logger::info("Audit:Lock acquired by {$gameRequest[0]}");
}
if (($gameRequest[0]=="playerinfo")||(($gameRequest[0]=="newgame"))) {
sleep(1); // Give time to populate data
}
// Misc events, some of them can terminate the request
// delete_event and other fast event-only handlers
require(__DIR__."/processor/misc.php");
// Player rewrite
// Will change $gameRequest[3] with the rewritten LLM request.
$player_rewrite_speech = "";
if (in_array($gameRequest[0],["inputtext","inputtext_s","narrator_inputtext"]) && isset($GLOBALS["PLAYER_RESPEECH"]) && $GLOBALS["PLAYER_RESPEECH"]) {
// Use preg_replace to remove the name and colon before the dialogue
$cleaned_player_dialogue = addcslashes(preg_replace('/^[^:]+:/', '', $gameRequest[3]),'"');
error_log($cleaned_player_dialogue);
if (strpos($gameRequest[3],"**")===0 || strpos($cleaned_player_dialogue,"**")===0 ) {
// If player speech starts with **
error_log("Overwritting user prompt $cleaned_player_dialogue");
// Profile isn't loaded yet at this point, so derive the NPC name from the DB using the profile MD5
$npcTarget = '';
$activeProfileForRewrite = dialecticRuntimeGetActiveProfile();
if ($activeProfileForRewrite !== null && $activeProfileForRewrite !== md5('The Narrator')) {
$npcRow = $db->fetchOne("SELECT npc_name FROM core_npc_master WHERE md5='" . $db->escape($activeProfileForRewrite) . "' LIMIT 1");
if ($npcRow && !empty($npcRow['npc_name'])) {
$npcTarget = $npcRow['npc_name'];
}
}
$escapedDialogue = escapeshellarg($cleaned_player_dialogue);
$escapedNpc = escapeshellarg($npcTarget);
$player_rewrite_speech=`php player_rewrite.php $escapedDialogue $escapedNpc`;
$player_rewrite_speech=cleanResponse($player_rewrite_speech);
$player_rewrite_speech=sanitizePlayerRespeechText($player_rewrite_speech, $GLOBALS["PLAYER_NAME"] ?? null);
$gameRequest[3]="{$GLOBALS["PLAYER_NAME"]}:$player_rewrite_speech";
$GLOBALS["DIALECTIC_EXECUTION_MODE"] = "AUTOCHAT"; //required when using STANDARD/WHISPER and ** prefix triggers speech database fix
}
}
// Narrator inititalization
// Note: We should check if we need to load Narrator profile in all type of requests.
require(__DIR__."/processor/narrator_init.php");
// maybeQueueNpcVoiceRefresh function moved to misc.php.
// If function is called only in one place,and seems has no other uses elsewhere, then there is no point of having a function, write the code in place.
// Also, we must not declare functions on this file (main.php).
// Profile loading
if (!isset($GLOBALS["NARRATOR_BORED_EVENT_ACTIVE"])) {
$GLOBALS["NARRATOR_BORED_EVENT_ACTIVE"] = false;
}
if (in_array(($gameRequest[0] ?? ''), ['bored', 'auto_greeting'], true) && dialecticRuntimeGetActiveProfile() === null) {
$boredTarget = function_exists('dialectic_extract_conversation_target')
? dialectic_extract_conversation_target((string)($gameRequest[3] ?? ""))
: "";
if ($boredTarget !== "" &&
strcasecmp($boredTarget, "The Narrator") !== 0) {
$boredNpcMaster = new NpcMaster();
$boredNpcData = $boredNpcMaster->getByName($boredTarget);
if (is_array($boredNpcData) && !empty($boredNpcData["md5"])) {
dialecticRuntimeSetActiveProfile($boredNpcData["md5"]);
Logger::info("[GAME_EVENT_PROFILE] Bound {$gameRequest[0]} event to NPC profile {$boredTarget}");
} else {
Logger::warn("[GAME_EVENT_PROFILE] Could not bind {$gameRequest[0]} event to NPC profile {$boredTarget}");
}
}
}
if (in_array(($gameRequest[0] ?? ''), ['rpg_lvlup', 'combatend', 'combatendmighty', 'combatbark', 'lockpicked', 'goodmorning', 'player_consumed', 'location_changed', 'quest_updated'], true) && dialecticRuntimeGetActiveProfile() === null) {
$rpgTarget = function_exists('dialectic_extract_conversation_target')
? dialectic_extract_conversation_target((string)($gameRequest[3] ?? ""))
: "";
if ($rpgTarget !== "" &&
strcasecmp($rpgTarget, "The Narrator") !== 0) {
$rpgNpcMaster = new NpcMaster();
$rpgNpcData = $rpgNpcMaster->getByName($rpgTarget);
if (is_array($rpgNpcData) && !empty($rpgNpcData["md5"])) {
dialecticRuntimeSetActiveProfile($rpgNpcData["md5"]);
Logger::info("[GAME_EVENT_PROFILE] Bound {$gameRequest[0]} event to NPC profile {$rpgTarget}");
} else {
Logger::warn("[GAME_EVENT_PROFILE] Could not bind {$gameRequest[0]} event to NPC profile {$rpgTarget}");
}
}
}
$inputRequestType = $gameRequest[0] ?? '';
if (in_array($inputRequestType, ["inputtext", "inputtext_s", "cheatmode", "vision"], true)) {
Logger::phaseStart("input_profile_bind", [
"type" => $inputRequestType,
]);
$inputTarget = ($gameRequest[0] ?? '') === "cheatmode"
? trim((string)($GLOBALS["DIALECTIC_CHEATMODE_TARGET"] ?? ""))
: "";
if ($inputTarget === "") {
$inputTarget = trim((string)($GLOBALS["DIALECTIC_INPUT_TARGET"] ?? ""));
}
if ($inputTarget === "") {
$inputTarget = function_exists('dialectic_extract_conversation_target')
? dialectic_extract_conversation_target((string)($gameRequest[3] ?? ""))
: "";
}
if ($inputTarget !== "" &&
strcasecmp($inputTarget, "The Narrator") !== 0) {
$inputProfileFields = function_exists('dialectic_extract_npc_profile_fields')
? dialectic_extract_npc_profile_fields((string)($gameRequest[3] ?? ""))
: [];
if (empty($inputProfileFields) && isset($GLOBALS["DIALECTIC_REQUEST_EVENT"]["payload"])) {
$inputProfileFields = function_exists('dialectic_extract_npc_profile_fields')
? dialectic_extract_npc_profile_fields((string)$GLOBALS["DIALECTIC_REQUEST_EVENT"]["payload"])
: [];
}
$inputRefid = function_exists('dialectic_extract_npc_refid')
? dialectic_extract_npc_refid((string)($gameRequest[3] ?? ""), $inputProfileFields)
: "";
if ($inputRefid === "" && isset($GLOBALS["DIALECTIC_REQUEST_EVENT"]["payload"])) {
$inputRefid = function_exists('dialectic_extract_npc_refid')
? dialectic_extract_npc_refid((string)$GLOBALS["DIALECTIC_REQUEST_EVENT"]["payload"], $inputProfileFields)
: "";
}
dialectic_ensure_npc($db, $inputTarget, $inputRefid, $inputProfileFields);
$inputNpcMaster = new NpcMaster();
$inputNpcData = $inputNpcMaster->getByName($inputTarget);
if (is_array($inputNpcData) && !empty($inputNpcData["md5"])) {
dialecticRuntimeSetActiveProfile($inputNpcData["md5"]);
Logger::info("[INPUT_PROFILE] Bound {$gameRequest[0]} request to NPC profile {$inputTarget}");
} else {
Logger::warn("[INPUT_PROFILE] Could not bind {$gameRequest[0]} request to NPC profile {$inputTarget}");
}
}
Logger::phaseEnd("input_profile_bind", [
"type" => $inputRequestType,
"target" => $inputTarget,
"active_profile" => dialecticRuntimeGetActiveProfile() ?? "",
], "info");
}
// Bored
if (($gameRequest[0] ?? '') === 'bored') {
require_once(__DIR__ . DIRECTORY_SEPARATOR . "lib" . DIRECTORY_SEPARATOR . "core" . DIRECTORY_SEPARATOR . "narrator.class.php");
$narratorSettings = new Narrator();
if ($narratorSettings->getBool('bored_enabled', false)) {
$boredChance = max(1, min(100, $narratorSettings->getInt('bored_chance', 25)));
$boredRoll = random_int(1, 100);
if ($boredRoll <= $boredChance) {
dialecticRuntimeSetActiveProfile(md5('The Narrator'));
$GLOBALS["NARRATOR_BORED_EVENT_ACTIVE"] = true;
Logger::info("[NARRATOR_BORED] Routing bored event through The Narrator runtime (roll {$boredRoll}/{$boredChance})");
} else {
Logger::info("[NARRATOR_BORED] Keeping bored event on NPC runtime (roll {$boredRoll}/{$boredChance})");
}
}
}
if (($activeProfile = dialecticRuntimeGetActiveProfile()) !== null) {
Logger::phaseStart("profile_runtime_load", [
"type" => $gameRequest[0] ?? "",
"profile" => $activeProfile,
]);
// Initialize OVERRIDES array for all profile types
$OVERRIDES["MINIME_T5"] = isset($GLOBALS["MINIME_T5"]) ? $GLOBALS["MINIME_T5"] : false;
$OVERRIDES["STTFUNCTION"] = isset($GLOBALS["STTFUNCTION"]) ? $GLOBALS["STTFUNCTION"] : "";
$OVERRIDES["TTSFUNCTION_PLAYER"] = isset($GLOBALS["TTSFUNCTION_PLAYER"]) ? $GLOBALS["TTSFUNCTION_PLAYER"] : "";
$OVERRIDES["TTSFUNCTION_PLAYER_VOICE"] = isset($GLOBALS["TTSFUNCTION_PLAYER_VOICE"]) ? $GLOBALS["TTSFUNCTION_PLAYER_VOICE"] : "";
$OVERRIDES["TTSFUNCTION_PLAYER_VOICE_ID"] = isset($GLOBALS["TTSFUNCTION_PLAYER_VOICE_ID"]) ? $GLOBALS["TTSFUNCTION_PLAYER_VOICE_ID"] : "";
$OVERRIDES["TTSFUNCTION_PLAYER_LANGUAGE"] = isset($GLOBALS["TTSFUNCTION_PLAYER_LANGUAGE"]) ? $GLOBALS["TTSFUNCTION_PLAYER_LANGUAGE"] : "";
// Direct narrator requests must load the narrator runtime profile even if the
// inbound request still carries the current NPC profile hash.
$isNarratorRequest = in_array($gameRequest[0], [
"narrator_inputtext",
"narration",
"narrator_welcome",
"narrator_quest_comment"
], true);
// Check if this is The Narrator (by MD5) or an explicit narrator request.
$isNarratorProfile = $isNarratorRequest || ($activeProfile === md5('The Narrator'));
// If this is The Narrator, use Narrator class instead of NpcMaster
if ($isNarratorProfile) {
require_once(__DIR__ . DIRECTORY_SEPARATOR . "lib" . DIRECTORY_SEPARATOR . "core" . DIRECTORY_SEPARATOR . "narrator.class.php");
$narrator = new Narrator();
$narratorData = $narrator->getNarratorData();
// Load narrator settings into GLOBALS (includes NARRATOR_DIARY_ENABLED, etc.)
$narrator->loadIntoGlobals();
if ($narratorData && isset($narratorData["profile_id"])) {
$profile = new CoreProfile();
$currentProfileData = $profile->getById($narratorData["profile_id"]);
$GLOBALS["DIALECTIC_CORE_CURRENT_PROFILE_DATA"] = $currentProfileData;
$connector = new LLMConnector();
$npcMaster = new NpcMaster(); // LLMRandomizer persists connector state through NPC metadata
$connectorSlot = LLMRandomizer::getConnectorSlot($currentProfileData, $narratorData, $npcMaster);
$connectorId = LLMRandomizer::getConnectorIdForSlot($currentProfileData, $connectorSlot);
$currentConnectorData = $connector->getById($connectorId);
$connector->setOldGlobals($currentConnectorData);
$profile->setOldGlobals($currentProfileData);
// Load narrator character data into GLOBALS (this sets PROMPT_HEAD and all character fields)
$narrator->loadCharacterIntoGlobals();
$GLOBALS["DIALECTIC_CORE_CURRENT_CONNECTOR_DATA"] = $currentConnectorData;
error_log("[CORE SYSTEM] Using Narrator profile from core_narrator table, profile: {$currentProfileData["label"]}");
} else {
error_log("[CORE SYSTEM] Narrator profile not found, using defaults");
}
} else {
// Regular NPC profile loading
//$OVERRIDES["PROMPT_HEAD"]=$GLOBALS["PROMPT_HEAD"];
$npcMaster=new NpcMaster();
Logger::phaseStart("profile_npc_lookup", [
"profile" => $activeProfile,
]);
$currentNpcData=$npcMaster->getByMD5($activeProfile);
Logger::phaseEnd("profile_npc_lookup", [
"found" => $currentNpcData ? "yes" : "no",
"npc" => $currentNpcData["npc_name"] ?? "",
], "info");
if (!$currentNpcData) {
error_log(__FILE__.". Using default profile because the requested active profile does not exist");
// Recovery path: when a stale/unknown profile hash is passed, we still need
// a valid profile + connector context or call_llm_internal() will terminate.
$profile = new CoreProfile();
$requestText = isset($gameRequest[3]) ? trim((string)$gameRequest[3]) : "";
$fallbackNpcName = null;
$fallbackNpcData = null;
$currentProfileData = null;
// Highest-confidence target extraction from player text payload.
if ($requestText !== "" && preg_match('/\(\s*(?:(?:talking|whispering|shouting|speaking\s+privately)\s+to|speaking\s+loudly\s+to)\s+([^()]+?)(?:\s+from\s+far\s+away)?\s*\)/i', $requestText, $matches)) {
$candidate = trim($matches[1]);
if ($candidate !== "") {
$fallbackNpcName = $candidate;
}
}
$isNarratorScopedRequest = in_array($gameRequest[0], ["narrator_inputtext", "narration", "narrator_welcome"], true)
|| stripos($requestText, '(Talking to The Narrator)') !== false
|| stripos($requestText, '(Whispering to The Narrator)') !== false
|| stripos($requestText, '(Speaking privately to The Narrator)') !== false
|| stripos($requestText, '(Shouting to The Narrator)') !== false
|| ($fallbackNpcName !== null && strcasecmp($fallbackNpcName, "The Narrator") === 0);
if ($fallbackNpcName !== null && strcasecmp($fallbackNpcName, "The Narrator") !== 0) {
$escapedNpcName = $db->escape($fallbackNpcName);
$fallbackNpcData = $db->fetchOne("SELECT * FROM core_npc_master WHERE lower(npc_name)=lower('{$escapedNpcName}') LIMIT 1");
if ($fallbackNpcData) {
$npcMaster->setOldGlobalsFromCurrentNpcData($fallbackNpcData, false);
$GLOBALS["DIALECTIC_CORE_CURRENT_NPC_DATA"] = $fallbackNpcData;
error_log("[CORE SYSTEM] Resolved unknown profile hash to NPC '{$fallbackNpcData["npc_name"]}' from request payload");
} else {
error_log("[CORE SYSTEM] Could not resolve NPC '{$fallbackNpcName}' for unknown profile hash");
}
}
// Prefer the resolved NPC profile when available.
if ($fallbackNpcData) {
if (empty($fallbackNpcData["profile_id"])) {
$defProfile = $profile->getDefaultNpc();
if ($defProfile) {
$fallbackNpcData["profile_id"] = (int)$defProfile["id"];
$npcMaster->updateByArray($fallbackNpcData);
error_log("[CORE SYSTEM] Resolved NPC '{$fallbackNpcData["npc_name"]}' had no profile, assigned default profile #{$defProfile["id"]}");
}
}
if (!empty($fallbackNpcData["profile_id"])) {
$currentProfileData = $profile->getById((int)$fallbackNpcData["profile_id"]);
}
}
if (!$currentProfileData) {
// NPC/default profile should win for normal requests; narrator only for narrator-scoped requests.
$fallbackProfile = $isNarratorScopedRequest ? $profile->getDefaultNarrator() : $profile->getDefaultNpc();
if (!$fallbackProfile) {
$fallbackProfile = $isNarratorScopedRequest ? $profile->getDefaultNpc() : $profile->getDefaultNarrator();
}
if (!$fallbackProfile) {
$fallbackProfile = $profile->getById(1);
}
if ($fallbackProfile) {
// Ensure we have the full profile row (id/label/connectors/metadata).
$currentProfileData = isset($fallbackProfile["id"])
? $profile->getById((int)$fallbackProfile["id"])
: $fallbackProfile;
}
}
if ($currentProfileData) {
$GLOBALS["DIALECTIC_CORE_CURRENT_PROFILE_DATA"] = $currentProfileData;
Logger::phaseStart("profile_connector_select", [
"npc" => $fallbackNpcData["npc_name"] ?? "",
"profile_label" => $currentProfileData["label"] ?? "",
]);
$connector = new LLMConnector();
// Respect current in-game mode when selecting active connector slot.
$result = $GLOBALS["db"]->fetchOne("SELECT value FROM conf_opts WHERE id='dialectic_profile_model'");
$connectorSlot = (isset($result['value']) && $result['value'] >= 1 && $result['value'] <= 4)
? (int)$result['value']
: 1;
$connectorId = LLMRandomizer::getConnectorIdForSlot($currentProfileData, $connectorSlot);
$currentConnectorData = $connector->getById($connectorId);
Logger::phaseEnd("profile_connector_select", [
"slot" => $connectorSlot,
"connector_id" => $connectorId,
"driver" => $currentConnectorData["driver"] ?? "",
"model" => $currentConnectorData["model"] ?? "",
], "info");
if ($currentConnectorData) {
$connector->setOldGlobals($currentConnectorData);
$profile->setOldGlobals($currentProfileData);
$GLOBALS["DIALECTIC_CORE_CURRENT_CONNECTOR_DATA"] = $currentConnectorData;
if ($fallbackNpcData) {
$npcMaster->setOldGlobalsFromCurrentNpcData($fallbackNpcData, false);
error_log("[CORE SYSTEM] Loaded fallback NPC profile '{$currentProfileData["label"]}' for '{$fallbackNpcData["npc_name"]}'");
} else {
error_log("[CORE SYSTEM] Loaded fallback profile '{$currentProfileData["label"]}' for unknown profile hash");
}
} else {
Logger::error("[CORE SYSTEM] Fallback profile loaded but no connector found for slot {$connectorSlot}");
}
} else {
Logger::error("[CORE SYSTEM] No fallback profile available for unknown profile hash");
}
} else {
error_log("[DIALECTIC CORE] USING CORE PROFILE {$currentNpcData["npc_name"]}") ;
// Profile has been migrated
$npcMaster->setOldGlobalsFromCurrentNpcData($currentNpcData, false);
$GLOBALS["DIALECTIC_CORE_CURRENT_NPC_DATA"] = $currentNpcData;
$profile=new CoreProfile();
// Fallback: assign default profile if NPC has none (orphaned by profile deletion)
if (empty($currentNpcData["profile_id"])) {
$defProfile = $profile->getDefaultNpc();
if ($defProfile) {
$currentNpcData["profile_id"] = (int)$defProfile['id'];
$npcMaster->updateByArray($currentNpcData);
error_log("[CORE SYSTEM] NPC '{$currentNpcData["npc_name"]}' had no profile, assigned default profile #{$defProfile['id']}");
}
}
$currentProfileData=$profile->getById($currentNpcData["profile_id"]);
$GLOBALS["DIALECTIC_CORE_CURRENT_PROFILE_DATA"]=$currentProfileData;
if (!empty($GLOBALS['AUTOFILL_CUSTOM_PROFILES'])) {
require_once __DIR__ . DIRECTORY_SEPARATOR . "ui" . DIRECTORY_SEPARATOR . "cmd" . DIRECTORY_SEPARATOR . "ai_profile_generation_service.php";
require_once __DIR__ . DIRECTORY_SEPARATOR . "lib" . DIRECTORY_SEPARATOR . "profile_autofill_async.php";
if (aiProfileShouldAttemptAutofill($currentNpcData, $npcMaster)) {
$trigger = aiProfileGetAutofillTrigger($currentNpcData, $npcMaster);
$queuedProfileJob = dialecticSpawnProfileAutofillWorker([
'name' => $currentNpcData["npc_name"],
'event_limit' => $trigger,
'source' => 'auto',
]);
if ($queuedProfileJob) {
aiProfileStampAutofillQueued($currentNpcData, $npcMaster);
Logger::info("[PROFILE_AUTOFILL] Queued async profile generation for {$currentNpcData["npc_name"]}; continuing dialogue turn");
} else {
Logger::warn("[PROFILE_AUTOFILL] Failed to queue async profile generation for {$currentNpcData["npc_name"]}; continuing dialogue turn");
}
}
}
Logger::phaseStart("profile_connector_select", [
"npc" => $currentNpcData["npc_name"] ?? "",
"profile_label" => $currentProfileData["label"] ?? "",
]);
$connector=new LLMConnector();
// Use randomizer to determine which connector slot to use
$connectorSlot = LLMRandomizer::getConnectorSlot($currentProfileData, $currentNpcData, $npcMaster);
$connectorId = LLMRandomizer::getConnectorIdForSlot($currentProfileData, $connectorSlot);
$currentConnectorData = $connector->getById($connectorId);
Logger::phaseEnd("profile_connector_select", [
"slot" => $connectorSlot,
"connector_id" => $connectorId,
"driver" => $currentConnectorData["driver"] ?? "",
"model" => $currentConnectorData["model"] ?? "",
], "info");
$connector->setOldGlobals($currentConnectorData);
$profile->setOldGlobals($currentProfileData);
$npcMaster->setOldGlobalsFromCurrentNpcData($currentNpcData, false);
$GLOBALS["DIALECTIC_CORE_CURRENT_NPC_DATA"] = $currentNpcData;
$GLOBALS["DIALECTIC_CORE_CURRENT_CONNECTOR_DATA"]=$currentConnectorData;
$debugLang = $GLOBALS["LLM_LANG"] ?? "unset";
$debugOverrideTtsLang = $GLOBALS["PATCH_OVERRIDE_TTS_LANGUAGE"] ?? "unset";
error_log("[CORE SYSTEM] Using new profile system , GLOBALS['LLM_LANG']:{$debugLang} profile: {$currentProfileData["label"]}");
error_log("[CORE SYSTEM] GLOBALS['LLM_LANG']:{$debugLang} GLOBALS['PATCH_OVERRIDE_TTS_LANGUAGE']:{$debugOverrideTtsLang}");
}
}
Logger::phaseEnd("profile_runtime_load", [
"npc" => $GLOBALS["DIALECTIC_NAME"] ?? "",
"profile_label" => $currentProfileData["label"] ?? "",
"connector" => $currentConnectorData["driver"] ?? "",
"model" => $currentConnectorData["model"] ?? "",
], "info");
//$GLOBALS["MINIME_T5"]=$OVERRIDES["MINIME_T5"];
$GLOBALS["STTFUNCTION"]=$OVERRIDES["STTFUNCTION"];
$GLOBALS["TTSFUNCTION_PLAYER"]=$OVERRIDES["TTSFUNCTION_PLAYER"];
$GLOBALS["TTSFUNCTION_PLAYER_VOICE"]=$OVERRIDES["TTSFUNCTION_PLAYER_VOICE"];
$GLOBALS["TTSFUNCTION_PLAYER_VOICE_ID"]=$OVERRIDES["TTSFUNCTION_PLAYER_VOICE_ID"];
$GLOBALS["TTSFUNCTION_PLAYER_LANGUAGE"]=$OVERRIDES["TTSFUNCTION_PLAYER_LANGUAGE"];
// $GLOBALS["PROMPT_HEAD"]=$OVERRIDES["PROMPT_HEAD"];
} else {
$isNarratorRequestWithoutProfile = in_array($gameRequest[0], [
"narrator_inputtext",
"narration",
"narrator_welcome",
"narrator_quest_comment"
], true);
if ($isNarratorRequestWithoutProfile) {
require_once(__DIR__ . DIRECTORY_SEPARATOR . "lib" . DIRECTORY_SEPARATOR . "core" . DIRECTORY_SEPARATOR . "narrator.class.php");
$narrator = new Narrator();
$narratorData = $narrator->getNarratorData();
if ($narratorData && isset($narratorData["profile_id"])) {
$profile = new CoreProfile();
$currentProfileData = $profile->getById($narratorData["profile_id"]);
if ($currentProfileData) {
$GLOBALS["DIALECTIC_CORE_CURRENT_PROFILE_DATA"] = $currentProfileData;
$connector = new LLMConnector();
$npcMaster = new NpcMaster(); // LLMRandomizer persists connector state through NPC metadata
$connectorSlot = LLMRandomizer::getConnectorSlot($currentProfileData, $narratorData, $npcMaster);
$connectorId = LLMRandomizer::getConnectorIdForSlot($currentProfileData, $connectorSlot);
$currentConnectorData = $connector->getById($connectorId);
if ($currentConnectorData) {
$connector->setOldGlobals($currentConnectorData);
$profile->setOldGlobals($currentProfileData);
$narrator->loadCharacterIntoGlobals();
$GLOBALS["DIALECTIC_CORE_CURRENT_CONNECTOR_DATA"] = $currentConnectorData;
error_log("[CORE SYSTEM] Using Narrator profile without explicit profile hash, profile: {$currentProfileData["label"]}");
} else {
Logger::error("[CORE SYSTEM] Narrator request without profile hash could not resolve connector");
$GLOBALS["USING_DEFAULT_PROFILE"] = true;
}
} else {
Logger::error("[CORE SYSTEM] Narrator request without profile hash could not resolve profile");
$GLOBALS["USING_DEFAULT_PROFILE"] = true;
}
} else {
Logger::error("[CORE SYSTEM] Narrator request without profile hash has no narrator profile configured");
$GLOBALS["USING_DEFAULT_PROFILE"] = true;
}
} else {
//error_log(__FILE__.". Using default profile because no active profile was resolved");
$GLOBALS["USING_DEFAULT_PROFILE"]=true;
}
}
if (isset($GLOBALS["DIALECTIC_CORE_CURRENT_NPC_DATA"]) && $GLOBALS["DIALECTIC_CORE_CURRENT_NPC_DATA"] && ($GLOBALS["DIALECTIC_NAME"] ?? "") !== "The Narrator") {
$npcMasterForVoiceRefresh = isset($npcMaster) && ($npcMaster instanceof NpcMaster)
? $npcMaster
: new NpcMaster();
Logger::phaseStart("profile_voice_refresh_check", [
"npc" => $GLOBALS["DIALECTIC_CORE_CURRENT_NPC_DATA"]["npc_name"] ?? "",
"voiceid" => $GLOBALS["DIALECTIC_CORE_CURRENT_NPC_DATA"]["voiceid"] ?? "",
]);
$refreshedNpcData = maybeQueueNpcVoiceRefresh($GLOBALS["DIALECTIC_CORE_CURRENT_NPC_DATA"], $npcMasterForVoiceRefresh);
Logger::phaseEnd("profile_voice_refresh_check", [
"npc" => $refreshedNpcData["npc_name"] ?? "",
"voiceid" => $refreshedNpcData["voiceid"] ?? "",
], "info");
if ($refreshedNpcData) {
$GLOBALS["DIALECTIC_CORE_CURRENT_NPC_DATA"] = $refreshedNpcData;
}
}
if (in_array($gameRequest[0],["inputtext","inputtext_s","narrator_inputtext","cheatmode"]) ) {
// Empty request
if (empty($gameRequest[3]) || trim($gameRequest[3])=="{$GLOBALS["PLAYER_NAME"]}:") {
error_log("[MAIN] Empty request... aborting");
terminate();
} else {
error_log("[MAIN] Request: {$gameRequest[3]}");
}
}
dialecticRuntimeSetActiveProfile(md5($GLOBALS["DIALECTIC_NAME"]));
// End of profile selection
foreach ($gameRequest as $i => $ele) {
$gameRequest[$i] = trim(preg_replace('/\s\s+/', ' ', preg_replace('/\'/m', "'", $ele)));
//$gameRequest[$i] = trim(preg_replace('/\s\s+/', ' ', preg_replace('/\'/m', "''", $ele)));
$gameRequest[$i]=strtr($gameRequest[$i],["#DIALECTIC_NPC1#"=>$GLOBALS["DIALECTIC_NAME"]]);
}
// $gameRequest = type of message|localts|gamets|data
if ($gameRequest[0]=="diary") {
$resolvedDiaryConnector = function_exists('dialecticResolveDiaryConnectorName')
? dialecticResolveDiaryConnectorName()
: ($GLOBALS["CONNECTORS_DIARY"] ?? '');
if (!empty($resolvedDiaryConnector)) {
$GLOBALS["CURRENT_CONNECTOR"] = $resolvedDiaryConnector;
}
// Add configurable cooldown for diary events to prevent spam (per NPC)
$diaryCooldownPeriod = isset($GLOBALS["DIARY_COOLDOWN"]) ? intval($GLOBALS["DIARY_COOLDOWN"]) : 30;
// Create a per-NPC cooldown key using the current NPC's name
$npcName = preg_replace('/[^a-zA-Z0-9_]/', '_', $GLOBALS["DIALECTIC_NAME"]);
$cooldownKey = "DIARY_LAST_TIMESTAMP_" . $npcName;
// Fetch the last diary trigger timestamp for this specific NPC
$diaryRecord = $GLOBALS["db"]->fetchAll("SELECT value FROM conf_opts WHERE id='" . $GLOBALS["db"]->escape($cooldownKey) . "'");
// Check if the timestamp exists in the database
if (!empty($diaryRecord)) {
$lastTrigger = (int) $diaryRecord[0]['value'];
$timeElapsed = time() - $lastTrigger;
if ($timeElapsed < $diaryCooldownPeriod) {
// Cooldown is still active for this NPC, exit
Logger::info("DIARY is on cooldown for {$GLOBALS["DIALECTIC_NAME"]}. Try again in " . ($diaryCooldownPeriod - $timeElapsed) . " seconds.");
terminate();
}
}
// Update the timestamp in the database for this specific NPC
$currentTimestamp = time();
$GLOBALS["db"]->upsertRowOnConflict(
"conf_opts",
array(
"id" => $cooldownKey,
"value" => $currentTimestamp
),
'id'
);
}
// Exit if only a event info log.
// Optional events
if (in_array($gameRequest[0],["info","chatme","chat","infoaction","death","itemfound",
"travelcancel","infoplayer","status_msg","util_npcname","itempickup"])) {
$gameRequest[3]=isset($gameRequest[3])?$gameRequest[3]:"";
if ($gameRequest[0] == 'infoplayer') {
// infoplayer format: level:{},name:"{}",race:"{}",gender:"{}"
dialecticMaybeSyncPlayerNameFromGamePayload($gameRequest[3]);
}
logEvent($gameRequest);
terminate();
}
// Check if the gameRequest matches specific types
if (in_array($gameRequest[0], ["playerinfo", "newgame"])) {
dialecticMaybeSyncPlayerNameFromGamePayload($gameRequest[3] ?? '');
logEvent($gameRequest);
terminate();
}
// Fake entry to mark time passing when bored event
if (in_array($gameRequest[0],["bored"])) {
//Loggar::trace(" bored event - exec trace"); // debug
if ((($gameRequest[2] ?? 0)-GetLastSpeechTs()) > 416667) { // 1/0.0000024 = 416667
$localGameRequest=$gameRequest;
$localGameRequest[0]="infoaction";
$localGameRequest[3].=". (Time passes without anyone in the group talking) ";
logEvent($localGameRequest);
}
if (!empty($GLOBALS["NARRATOR_BORED_EVENT_ACTIVE"])) {
Logger::info("[NARRATOR_BORED] Using narrator bored flow");
} elseif ((isset($GLOBALS["BORED_EVENT_SERVERSIDE"])&&($GLOBALS["BORED_EVENT_SERVERSIDE"]))) {
$boredPayload = json_decode((string)($gameRequest[3] ?? ''), true);
$boredPayload = is_array($boredPayload) ? $boredPayload : [];
$boredSeedActor = trim((string)($boredPayload['actor_name'] ?? $boredPayload['speaker'] ?? ''));
$boredEligibleActors = is_array($boredPayload['eligible_actors'] ?? null)
? array_values($boredPayload['eligible_actors'])
: [];
Logger::info(
"Redirecting bored event to rolemaster with seed actor '{$boredSeedActor}' and "
. count($boredEligibleActors) . " eligible actor(s)"
);