载入中...
搜索中...
未找到
DevTool.cpp
浏览该文件的文档.
3
15
16#include "common/Diagnostic.h"
17#include "common/Module.h"
19#include "common/RenderTrace.h"
20#include "common/Runtime.h"
21#include "common/ScriptError.h"
22#include "common/Status.h"
24#include "common/Value.h"
26
27#include <Poco/JSON/Parser.h>
28#include <simplesquirrel/simplesquirrel.hpp>
29#include <squirrel.h>
30
31#include <algorithm>
32#include <cstring>
33#include <sstream>
34#include <string>
35#include <vector>
36
37namespace eve::dev {
38namespace {
39
40thread_local DevTool* g_active = nullptr;
41
42std::string describeSqValue(HSQUIRRELVM vm, SQInteger idx) {
43 const SQObjectType t = sq_gettype(vm, idx);
44 switch (t) {
45 case OT_NULL:
46 return "null";
47 case OT_INTEGER: {
48 SQInteger v = 0;
49 sq_getinteger(vm, idx, &v);
50 return "i:" + std::to_string(static_cast<long long>(v));
51 }
52 case OT_FLOAT: {
53 SQFloat v = 0;
54 sq_getfloat(vm, idx, &v);
55 return "f:" + std::to_string(static_cast<double>(v));
56 }
57 case OT_BOOL: {
58 SQBool v = SQFalse;
59 sq_getbool(vm, idx, &v);
60 return v ? "b:1" : "b:0";
61 }
62 case OT_STRING: {
63 const SQChar* s = nullptr;
64 sq_getstring(vm, idx, &s);
65 return std::string("s:") + (s ? s : "");
66 }
67 case OT_TABLE:
68 return "table";
69 case OT_ARRAY:
70 return "array";
71 case OT_USERDATA:
72 return "userdata";
73 case OT_CLOSURE:
74 return "closure";
75 case OT_NATIVECLOSURE:
76 return "native";
77 case OT_GENERATOR:
78 return "generator";
79 case OT_USERPOINTER:
80 return "userpointer";
81 case OT_THREAD:
82 return "thread";
83 case OT_CLASS:
84 return "class";
85 case OT_INSTANCE:
86 return "instance";
87 case OT_WEAKREF:
88 return "weakref";
89 default:
90 return "other";
91 }
92}
93
94void nativeDebugHook(HSQUIRRELVM v, SQInteger type, const SQChar* sourcename, SQInteger line,
95 const SQChar* funcname) {
96 if (!g_active) return;
97 g_active->handleDebugEvent(v, static_cast<int>(type), sourcename ? sourcename : "",
98 static_cast<int>(line), funcname ? funcname : "");
99}
100
102SQInteger runtimeErrorHook(HSQUIRRELVM v) {
103 if (!g_active) return 0;
104 // Capture while the throw-site stack is still intact (including caught
105 // throws when sq_notifyallexceptions is on).
107 // When attached through Runtime, uncaught errors are reported by the
108 // Runtime error sink after unwind. Notifying here as well would treat
109 // expected catches (file_exists, migrate_instance) as debugger errors.
110 if (g_active->isRuntimeBound()) {
111 eve::script::setLastScriptError(v, std::move(ctx));
112 return 0;
113 }
114 const std::string msg = ctx.empty() ? std::string("script error")
116 try {
117 g_active->notifyError(msg);
118 } catch (...) {
119 }
120 ctx.reported = true;
121 eve::script::setLastScriptError(v, std::move(ctx));
122 return 0;
123}
124
125SourceLoc stackTopLoc(HSQUIRRELVM vm) {
126 SourceLoc loc;
127 SQStackInfos si;
128 if (SQ_SUCCEEDED(sq_stackinfos(vm, 1, &si))) {
129 if (si.source) loc.source = si.source;
130 loc.line = static_cast<int>(si.line);
131 if (si.funcname) loc.function = si.funcname;
132 }
133 return loc;
134}
135
136} // namespace
137
139 static DevTool inst;
140 return inst;
141}
142
143void DevTool::attach(ssq::VM& vm, bool sampleLocals) { attach(vm.getHandle(), sampleLocals); }
144
145void DevTool::attach(eve::Runtime& runtime, bool sampleLocals) {
146 attach(runtime.vm(), sampleLocals);
147 runtime_ = &runtime;
148 // Capture throw-site stacks for try/catch so reportError / lastScriptError
149 // can surface the original site (load.nut pattern). Safe here because the
150 // Runtime-bound error hook only stashes context and does not notify/pause.
151 sq_notifyallexceptions(runtime.handle(), SQTrue);
152 // Route Runtime-boundary errors into the slicer/report. The VM error hook
153 // only captures the stack when this Runtime sink is bound; this handler
154 // reports compile / reflect / unload failures and uncaught execute errors
155 // exactly once.
156 runtime.setErrorHandler([this](const eve::ScriptException& error) {
157 if (error.reported()) return;
158 try {
159 notifyError(error.what());
160 } catch (...) {
161 }
162 });
163}
164
165void DevTool::installRenderTracer() {
166 renderFlow_.clear();
167 eve::debug::setRenderTracer(&renderFlow_);
168 renderTraceEnabled_ = true;
169}
170
171void DevTool::uninstallRenderTracer() {
172 if (eve::debug::renderTracer() == &renderFlow_) eve::debug::setRenderTracer(nullptr);
173 renderTraceEnabled_ = false;
174}
175
177 if (on)
178 installRenderTracer();
179 else
180 uninstallRenderTracer();
181}
182
183void DevTool::attach(HSQUIRRELVM vm, bool sampleLocals) {
184 if (!vm) return;
185 // Drop script tools registered against another VM *before* touching it: if
186 // that VM went away without detach(), its memory is freed and sq_release
187 // into it would corrupt the heap. Passing the incoming VM as the owner means
188 // nothing is released here, only discarded.
190 detach();
191 vm_ = vm;
192 sampleLocals_ = sampleLocals;
193 graph_.clear();
194 localSnap_.clear();
195 lastReport_.clear();
196 lastError_.clear();
197 lastSlice_ = {};
198
201 Debugger::instance().setPump([this]() { pumpWhilePaused(); });
202
203 sq_enabledebuginfo(vm_, SQTrue);
204 // Do not enable sq_notifyallexceptions here. With notify-all + break-on-error,
205 // this hook would pause on every caught throw before script catch/reportError
206 // runs (double pause → hung script thread → flaky teardown SEGFAULT in
207 // devtools.dap.caughtErrorPausesAtReportSite). Runtime::installErrorHandler
208 // already turns notify-all on for production VMs; attach(Runtime&) keeps it.
209 sq_setnativedebughook(vm_, nativeDebugHook);
210 // Route uncaught script errors into the debugger (break-on-error aware).
211 sq_newclosure(vm_, runtimeErrorHook, 0);
212 sq_seterrorhandler(vm_);
213 g_active = this;
214 installRenderTracer();
215
217 ConsolePanel::instance().addLog("info", "DevTools attached");
218}
219
222 // Handlers registered by project scripts live in this VM; drop them while it
223 // is still valid so the references are released, not leaked.
224 clearScriptTools(vm_);
225 if (runtime_) {
226 runtime_->setErrorHandler({});
227 runtime_ = nullptr;
228 }
229 stopDap();
230 stopMcp();
233 if (vm_) {
234 sq_setnativedebughook(vm_, nullptr);
235 // Leave debuginfo enabled; harmless for subsequent runs on same VM.
236 }
237 if (g_active == this) g_active = nullptr;
239 vm_ = nullptr;
240 localSnap_.clear();
241 lastReport_.clear();
242 lastError_.clear();
243 lastSlice_ = {};
244 uninstallRenderTracer();
245}
246
247int DevTool::startDap(uint16_t port) { return DebugAdapter::instance().listen(port); }
248
250
251int DevTool::startMcp(uint16_t port) { return McpServer::instance().listen(port); }
252
254
256
258
260
262
267
269
271
273
275 try {
276 ssq::Table eveTbl = vm.find("eve").toTable();
277 ssq::Table dev = eveTbl.addTable("dev");
278 // Project-script MCP export surface (eve.mcp.tool/remove/tools/clear).
280
281 dev.addFunc("pause", [this]() {
283 dap().notifyStopped(PauseReason::PauseKey, debugger().pauseLocation());
284 });
285 // Note: Squirrel reserves `resume` (generators) and `continue` (loops),
286 // so the script binding cannot be named either of those.
287 dev.addFunc("continueRun", [this]() {
288 debugger().resume();
290 });
291 dev.addFunc("togglePause", [this]() {
292 if (debugger().isPaused()) {
293 debugger().resume();
295 } else {
297 dap().notifyStopped(PauseReason::PauseKey, debugger().pauseLocation());
298 }
299 });
300 dev.addFunc("isPaused", [this]() { return debugger().isPaused(); });
301 dev.addFunc("stepFrame", [this]() {
304 });
305 // stepInto / stepOver / stepOut — primary script stepping (DAP F11 / F10 / Shift+F11).
306 dev.addFunc("stepInto", [this]() {
307 debugger().stepInto();
309 });
310 dev.addFunc("stepOver", [this]() {
311 debugger().stepOver();
313 });
314 dev.addFunc("stepOut", [this]() {
315 debugger().stepOut();
317 });
318 // Historical alias for stepInto.
319 dev.addFunc("stepLine", [this]() {
320 debugger().stepLine();
322 });
323 // Convenience: stepOver when mid-script, else one frame.
324 dev.addFunc("step", [this]() {
325 debugger().step();
327 });
328 dev.addFunc("shouldRunUpdate", [this]() { return debugger().shouldRunUpdate(); });
329 dev.addFunc("notifyFrameDone", [this]() {
330 const bool wasStep = debugger().mode() == RunMode::StepFrame;
332 if (wasStep || debugger().isPaused())
333 dap().notifyStopped(debugger().lastPauseReason(), debugger().pauseLocation());
334 });
335 dev.addFunc("poll", [this]() { poll(); });
336
337 dev.addFunc("setBreakpoint", [this](std::string source, int line, std::string condition) {
338 return debugger().setBreakpoint(std::move(source), line, true, std::move(condition));
339 });
340 dev.addFunc("clearBreakpoint", [this](std::string source, int line) {
341 return debugger().clearBreakpoint(std::move(source), line);
342 });
343 dev.addFunc("clearBreakpoints", [this]() { debugger().clearBreakpoints(); });
344
345 dev.addFunc("addWatch", [this](std::string expr) { debugger().addWatch(std::move(expr)); });
346 dev.addFunc("removeWatch", [this](std::string expr) { return debugger().removeWatch(expr); });
347 dev.addFunc("clearWatches", [this]() { debugger().clearWatches(); });
348 dev.addFunc("eval", [this](std::string expr) {
349 auto info = debugger().evaluate(expr);
350 return info.value;
351 });
352 dev.addFunc("reportError", [this](std::string msg) {
353 return notifyError(msg.empty() ? std::string("script error") : std::move(msg));
354 });
355 dev.addFunc("setBreakOnError", [this](bool on) { debugger().setBreakOnError(on); });
356 dev.addFunc("breakOnError", [this]() { return debugger().breakOnError(); });
357 dev.addFunc("setBreakpointsEnabled", [this](bool on) {
359 });
360 dev.addFunc("breakpointsEnabled", [this]() { return debugger().breakpointsEnabled(); });
361 dev.addFunc("lastError", [this]() { return lastError(); });
362 dev.addFunc("profileReport", [this]() { return formatProfileReport(); });
363 dev.addFunc("profileClear", [this]() { profileClear(); });
364 dev.addFunc("registerSource", [this](std::string name, std::string content) {
365 dap().registerSource(std::move(name), std::move(content));
366 });
367
368 dev.addFunc("markStateRoot",
369 [](std::string name) { Snapshot::instance().markRoot(std::move(name)); });
370 dev.addFunc("unmarkStateRoot",
371 [](std::string name) { Snapshot::instance().unmarkRoot(name); });
372 dev.addFunc("markTransientStateRoot",
373 [](std::string name) { Snapshot::instance().markTransientRoot(std::move(name)); });
374 dev.addFunc("unmarkTransientStateRoot",
375 [](std::string name) { Snapshot::instance().unmarkTransientRoot(name); });
376 dev.addFunc("clearStateRoots", []() { Snapshot::instance().clearRoots(); });
377 dev.addFunc("stateRoots", [this]() { return snapshot().rootsFor(vm_); });
378 dev.addFunc("transientStateRoots", []() { return Snapshot::instance().transientRoots(); });
379 // After scripts initialize configured game systems, publish a runtime
380 // world brief so MCP Discover can report what is live (not on-disk prose).
381 const HSQUIRRELVM handle = vm.getHandle();
382 dev.addFunc("publishWorldContext", [handle](ssq::Object world) {
383 auto value = script::valueFromSquirrel(world);
384 if (!value) return script::projectStatusResult(handle, value.status());
385 return script::projectResult(handle, publishWorldContext(std::move(value).takeValue()));
386 });
387 dev.addFunc("clearWorldContext", []() { clearWorldContext(); });
388 dev.addFunc("hasWorldContext", []() { return hasWorldContext(); });
389 dev.addFunc("worldContext", [handle]() {
390 const Value* world = runtimeWorldContext();
391 if (!world)
394 "worldContext")));
396 });
397 dev.addFunc("gameWorldSnapshot", [handle]() {
399 });
400 auto markSnapshotPause = [this]() {
401 if (!debugger().isPaused()) return;
402 debugger().pauseAt(PauseReason::Snapshot, debugger().pauseLocation());
404 dap().notifyStopped(PauseReason::Snapshot, debugger().pauseLocation(),
405 "snapshot restored");
406 };
407 dev.addFunc("saveSnapshot", [this](std::string path) {
408 std::string err;
409 const bool ok = snapshot().saveFile(vm_, path, &err);
410 if (!ok) return std::string("error:") + err;
411 return std::string("ok");
412 });
413 dev.addFunc("loadSnapshot", [this, markSnapshotPause](std::string path) {
414 std::string err;
415 const bool ok = snapshot().loadFile(vm_, path, &err);
416 if (!ok) return std::string("error:") + err;
417 markSnapshotPause();
418 return std::string("ok");
419 });
420 dev.addFunc("captureSnapshot", [this]() {
421 std::string err;
422 return snapshot().capture(vm_, &err);
423 });
424 dev.addFunc("restoreSnapshot", [this, markSnapshotPause](std::string json) {
425 std::string err;
426 const bool ok = snapshot().restore(vm_, json, &err);
427 if (!ok) return std::string("error:") + err;
428 markSnapshotPause();
429 return std::string("ok");
430 });
431 dev.addFunc("beginStateReload", [this]() {
432 std::string err;
433 if (!ReloadSession::instance().begin(vm_, &err)) return std::string("error:") + err;
434 return std::string("");
435 });
436 dev.addFunc("commitStateReload", [this]() {
437 std::string err;
438 if (!ReloadSession::instance().commit(vm_, &err)) return std::string("error:") + err;
439 return std::string("");
440 });
441 dev.addFunc("abortStateReload", [this]() {
442 std::string err;
443 if (!ReloadSession::instance().abort(vm_, &err)) return std::string("error:") + err;
444 return std::string("");
445 });
446 // Soft restart: reset native providers / re-run init without dropping
447 // ResourceManager. MCP eve_restart is the agent-facing entry; scripts
448 // can also call these helpers from eve_before_restart hooks.
449 dev.addFunc("resetNativeState", []() {
450 return static_cast<int>(resetNativeStateProviders());
451 });
452 dev.addFunc("resourceCacheCount", []() {
453 return static_cast<int>(resourceCacheCount());
454 });
455 // Parameter must not be named args*/argN — binding-contract codegen
456 // treats those as unresolved placeholders and fails the build.
457 dev.addFunc("softRestart", [this](std::string requestJson, bool reloadScripts) {
459 request.reloadScripts = reloadScripts;
460 if (!requestJson.empty()) {
461 try {
462 Poco::JSON::Parser parser;
463 auto parsed = parser.parse(requestJson);
464 request.args = parsed.extract<Poco::JSON::Object::Ptr>();
465 } catch (const std::exception& e) {
466 return std::string("error: invalid request JSON: ") + e.what();
467 } catch (...) {
468 return std::string("error: invalid request JSON");
469 }
470 }
471 auto result = executeSoftRestart(vm_, std::move(request));
472 if (!result) {
473 const auto& status = result.status();
474 const auto* diag = status.primaryDiagnostic();
475 return std::string("error:") +
476 (diag && !diag->message().empty() ? diag->message()
477 : std::string(statusCodeName(status.code())));
478 }
479 const SoftRestartReport& report = result.value();
480 return std::string("ok:resources=") + std::to_string(report.resourceCountAfter) +
481 ":scripts=" + (report.scriptsReloaded ? "1" : "0");
482 });
483
484 // ---- state-driven bug reproduction (baseline snapshot + step replay) ----
485 dev.addFunc("beginScenario", [this]() {
486 std::string err;
487 if (!ScenarioRecorder::instance().begin(vm_, &err))
488 return std::string("error:") + err;
489 return std::string("ok");
490 });
491 dev.addFunc("scenarioFrame", []() { ScenarioRecorder::instance().markFrame(); });
492 dev.addFunc("scenarioRecording",
493 []() { return ScenarioRecorder::instance().recording(); });
494 dev.addFunc("endScenario", [](std::string path) {
495 std::string err;
496 if (!ScenarioRecorder::instance().end(path, &err))
497 return std::string("error:") + err;
498 return std::string("ok");
499 });
500 dev.addFunc("cancelScenario", []() { ScenarioRecorder::instance().cancel(); });
501 dev.addFunc("beginReplay", [this](std::string path) {
502 std::string err;
503 if (!ScenarioRecorder::instance().beginReplay(vm_, path, &err))
504 return std::string("error:") + err;
505 return std::string("ok");
506 });
507 dev.addFunc("replayFrame", []() { return ScenarioRecorder::instance().stageFrame(); });
508 dev.addFunc("replayRemaining",
509 []() { return ScenarioRecorder::instance().framesRemaining(); });
510 dev.addFunc("replayErrorReport",
511 []() { return ScenarioRecorder::instance().errorReport(); });
512 dev.addFunc("gameplay", [](const std::string& requestJson) {
513 auto result = eve::executeGameplayControlJson(requestJson);
514 return result ? std::move(result).takeValue()
515 : std::string("error:") + result.status().describe();
516 });
517
518 // AI / MCP surface (DevTools panel + agent session log).
519 ssq::Table ai = dev.addTable("ai");
520 ai.addFunc("status", []() { return AiPanel::instance().statusLine(); });
521 ai.addFunc("isVisible", []() { return AiPanel::instance().isVisible(); });
522 ai.addFunc("setVisible", [](bool on) { AiPanel::instance().setVisible(on); });
523 ai.addFunc("toggleVisible", []() { AiPanel::instance().toggleVisible(); });
524 ai.addFunc("note", [](std::string text) {
525 AiPanel::instance().addNote(std::move(text));
526 return std::string("ok");
527 });
528 ai.addFunc("log", []() { return AiPanel::instance().formatLog(64); });
529 ai.addFunc("clearLog", []() { AiPanel::instance().clearLog(); });
530 ai.addFunc("mcpPort", []() { return AiPanel::instance().mcpPort(); });
531 ai.addFunc("mcpConnected", []() { return AiPanel::instance().mcpConnected(); });
532 ai.addFunc("draw", [this]() { drawAiPanel(); });
533
534 // Runtime console / log / REPL surface.
535 ssq::Table consoleTbl = dev.addTable("console");
536 consoleTbl.addFunc("log", [](std::string text) {
537 ConsolePanel::instance().addLog("info", std::move(text));
538 return std::string("ok");
539 });
540 consoleTbl.addFunc("info", [](std::string text) {
541 ConsolePanel::instance().addInfo(std::move(text));
542 return std::string("ok");
543 });
544 consoleTbl.addFunc("warn", [](std::string text) {
545 ConsolePanel::instance().addWarn(std::move(text));
546 return std::string("ok");
547 });
548 consoleTbl.addFunc("error", [](std::string text) {
550 return std::string("ok");
551 });
552 consoleTbl.addFunc("debug", [](std::string text) {
553 ConsolePanel::instance().addLog("debug", std::move(text));
554 return std::string("ok");
555 });
556 consoleTbl.addFunc("eval", [this](std::string expr) { return console().eval(std::move(expr)); });
557 consoleTbl.addFunc("clear", []() {
559 return std::string("ok");
560 });
561 consoleTbl.addFunc("recent", [](int n) {
562 const auto lines = ConsolePanel::instance().recent(
563 static_cast<size_t>(n > 0 ? n : 64));
564 std::vector<std::string> out;
565 out.reserve(lines.size());
566 for (const auto& l : lines) out.push_back("[" + l.timestamp + "] " + l.level + " | " + l.text);
567 return out;
568 });
569 consoleTbl.addFunc("format", [](int n) {
570 return ConsolePanel::instance().format(static_cast<size_t>(n > 0 ? n : 64));
571 });
572 consoleTbl.addFunc("isVisible", []() { return ConsolePanel::instance().isVisible(); });
573 consoleTbl.addFunc("setVisible", [](bool on) { ConsolePanel::instance().setVisible(on); });
574 consoleTbl.addFunc("toggleVisible", []() { ConsolePanel::instance().toggleVisible(); });
575 consoleTbl.addFunc("draw", [this]() { drawConsolePanel(); });
576
577 // FPS / frame-time overlay (sampled from load.nut each frame).
578 ssq::Table statsTbl = dev.addTable("stats");
579 statsTbl.addFunc("sample", [](float dt) {
581 return std::string("ok");
582 });
583 statsTbl.addFunc("setEntityCount", [](int n) {
585 return std::string("ok");
586 });
587 statsTbl.addFunc("clearEntityCount", []() {
589 return std::string("ok");
590 });
591 statsTbl.addFunc("fps", []() { return FrameStatsPanel::instance().fps(); });
592 statsTbl.addFunc("frameMs", []() { return FrameStatsPanel::instance().frameMs(); });
593 statsTbl.addFunc("entityCount", []() { return FrameStatsPanel::instance().entityCount(); });
594 statsTbl.addFunc("hasEntityCount", []() { return FrameStatsPanel::instance().hasEntityCount(); });
595 statsTbl.addFunc("format", []() { return FrameStatsPanel::instance().format(); });
596 statsTbl.addFunc("isVisible", []() { return FrameStatsPanel::instance().isVisible(); });
597 statsTbl.addFunc("setVisible", [](bool on) { FrameStatsPanel::instance().setVisible(on); });
598 statsTbl.addFunc("toggleVisible", []() { FrameStatsPanel::instance().toggleVisible(); });
599 statsTbl.addFunc("draw", [this]() { drawFrameStatsPanel(); });
600
601 // Native binding is arity-3; keep `setBreakpoint(file, line)` working.
602 ssq::Script bpWrap = vm.compileSource(
603 "local _setBreakpoint = eve.dev.setBreakpoint\n"
604 "eve.dev.setBreakpoint = function(source, line, condition = \"\") {\n"
605 " return _setBreakpoint(source, line, condition)\n"
606 "}\n");
607 vm.run(bpWrap);
608 } catch (...) {
609 // If eve table missing, skip — attach still useful for C++/DAP/MCP.
610 }
611}
612
614 const char* funcname) {
615 SourceLoc loc;
616 loc.source = source ? source : "";
617 loc.line = line;
618 loc.function = funcname ? funcname : "";
619
620 // Squirrel passes 'l' / 'c' / 'r' as event type characters.
621 switch (type) {
622 case 'c':
624 localSnap_.erase(static_cast<int>(graph_.currentStack().size()));
625 profileCall(loc.function);
626 break;
627 case 'r':
629 // Drop snapshot for the frame that just returned.
630 localSnap_.erase(static_cast<int>(graph_.currentStack().size()) + 1);
631 profileReturn();
632 break;
633 case 'l':
634 graph_.onLine(loc);
635 profileLine(loc.function);
636 if (sampleLocals_) sampleFrameLocals(vm, loc);
637 if (Debugger::instance().onScriptLine(loc)) {
638 dap().notifyStopped(Debugger::instance().lastPauseReason(), loc);
640 Debugger::instance().waitWhilePaused([this]() { pumpWhilePaused(); });
641 }
642 break;
643 default:
644 break;
645 }
646}
647
648void DevTool::handleDebugHotkey(const std::string& key) {
649 if (key.empty()) return;
650 Debugger& dbg = debugger();
651 if (key == "F5") {
652 if (!dbg.isPaused()) return;
653 dbg.resume();
655 return;
656 }
657 if (key == "F10") {
658 if (!dbg.isPaused()) return;
659 dbg.stepOver();
661 return;
662 }
663 if (key == "F11") {
664 if (!dbg.isPaused()) return;
665 dbg.stepInto();
667 return;
668 }
669 if (key == "F8") {
670 if (!dbg.isPaused()) return;
671 dbg.stepFrame();
673 return;
674 }
675 if (key == "Pause") {
676 // Already inside a script pause — Pause resumes (toggle).
677 if (!dbg.isPaused()) return;
678 dbg.resume();
680 }
681}
682
683void DevTool::pumpWhilePaused() {
684 poll(); // DAP continue / next / pause
685
686 auto* ev = eve::ModuleManager::getInstance<eve::platform_event::PlatformEvent>("PlatformEvent");
687 if (!ev) return;
688 ev->pump();
689
690 // Consume debug hotkeys so F5/F8/F10/F11 work while blocked in the line hook;
691 // re-queue everything else for the main loop after resume.
692 std::vector<std::unique_ptr<eve::platform_event::Message>> keep;
693 while (auto msg = ev->pollOwned()) {
694 bool handled = false;
695 if (msg->name == "keypressed" && !msg->args.empty() &&
696 msg->args[0].type == eve::platform_event::Variant::Type::String) {
697 const std::string& key = msg->args[0].s;
698 if (key == "F5" || key == "F8" || key == "F10" || key == "F11" || key == "Pause") {
699 handleDebugHotkey(key);
700 handled = true;
701 }
702 }
703 if (!handled) keep.push_back(std::move(msg));
704 }
705 for (auto& msg : keep) ev->push(std::move(msg));
706}
707
708void DevTool::sampleFrameLocals(HSQUIRRELVM vm, const SourceLoc& loc) {
709 if (!vm) return;
710 const int depth = static_cast<int>(graph_.currentStack().size());
711 auto& prev = localSnap_[depth];
712 std::unordered_map<std::string, std::string> cur;
713
714 // Level 0 = current script frame. The native debug hook is invoked as a
715 // direct C call (no CallInfo pushed), so the top of the Squirrel call
716 // stack is the script frame that triggered the line event.
717 const SQUnsignedInteger level = 0;
718 for (SQUnsignedInteger n = 0;; ++n) {
719 const SQInteger top = sq_gettop(vm);
720 const SQChar* name = sq_getlocal(vm, level, n);
721 if (!name) {
722 sq_settop(vm, top);
723 break;
724 }
725 const std::string key(name);
726 // Skip temporaries / this binding noise if desired; keep "this" for OO flow.
727 const std::string val = describeSqValue(vm, -1);
728 sq_settop(vm, top);
729
730 cur[key] = val;
731 auto it = prev.find(key);
732 if (it == prev.end() || it->second != val) {
733 // First sighting or value change ⇒ definition for the data-flow graph.
734 graph_.onDef(loc, key);
735 }
736 }
737 prev.swap(cur);
738}
739
740SliceResult DevTool::analyzeError(const std::string& errorMessage,
741 const std::vector<std::string>& hintVars) const {
743 c.variables = hintVars;
744
745 if (vm_) {
746 SQStackInfos si;
747 if (SQ_SUCCEEDED(sq_stackinfos(vm_, 1, &si))) {
748 if (si.source) c.loc.source = si.source;
749 c.loc.line = static_cast<int>(si.line);
750 if (si.funcname) c.loc.function = si.funcname;
751 } else {
752 c.loc = stackTopLoc(vm_);
753 }
754 }
755
756 // Prefer last recorded line if stackinfos unavailable.
757 if (c.loc.empty() && !graph_.events().empty()) {
758 const auto ev = graph_.events();
759 for (size_t i = ev.size(); i-- > 0;) {
760 if (ev[i].kind == TraceKind::Line || ev[i].kind == TraceKind::Use ||
761 ev[i].kind == TraceKind::Def) {
762 c.loc = ev[i].loc;
763 break;
764 }
765 }
766 }
767
768 (void)errorMessage;
769 return graph_.sliceBackward(c);
770}
771
772std::string DevTool::formatError(const std::string& errorMessage,
773 const std::vector<std::string>& hintVars) const {
775 c.variables = hintVars;
776 if (vm_) {
777 SQStackInfos si;
778 if (SQ_SUCCEEDED(sq_stackinfos(vm_, 1, &si))) {
779 if (si.source) c.loc.source = si.source;
780 c.loc.line = static_cast<int>(si.line);
781 if (si.funcname) c.loc.function = si.funcname;
782 }
783 }
784 if (c.loc.empty() && !graph_.events().empty()) {
785 const auto ev = graph_.events();
786 for (size_t i = ev.size(); i-- > 0;) {
787 if (!ev[i].loc.empty()) {
788 c.loc = ev[i].loc;
789 break;
790 }
791 }
792 }
793 return graph_.formatErrorReport(errorMessage, c);
794}
795
796void DevTool::markErrorUses(const SourceLoc& loc,
797 const std::vector<std::string>& hintVars) {
798 if (!vm_) return;
799 SourceLoc site = loc;
800 if (site.empty()) {
801 SQStackInfos si;
802 if (SQ_SUCCEEDED(sq_stackinfos(vm_, 1, &si))) {
803 if (si.source) site.source = si.source;
804 site.line = static_cast<int>(si.line);
805 if (si.funcname) site.function = si.funcname;
806 }
807 }
808 graph_.onLine(site);
809
810 const SQUnsignedInteger level = 0;
811 for (SQUnsignedInteger n = 0;; ++n) {
812 const SQInteger top = sq_gettop(vm_);
813 const SQChar* name = sq_getlocal(vm_, level, n);
814 if (!name) {
815 sq_settop(vm_, top);
816 break;
817 }
818 const std::string key(name);
819 sq_settop(vm_, top);
820 if (!hintVars.empty()) {
821 bool wanted = false;
822 for (const auto& h : hintVars) {
823 if (h == key) {
824 wanted = true;
825 break;
826 }
827 }
828 if (!wanted) continue;
829 }
830 graph_.onUse(site, key);
831 }
832}
833
834std::string DevTool::notifyError(const std::string& errorMessage,
835 const std::vector<std::string>& hintVars) {
836 SourceLoc site;
837 if (vm_) {
838 // Prefer the stack captured at throw time. reportError runs from a
839 // script catch, so sq_stackinfos(level 1) is the catch site (load.nut)
840 // rather than the original throw in main.nut.
841 if (const auto* ctx = eve::script::peekLastScriptError(vm_)) {
842 if (!ctx->stack.empty() &&
843 (errorMessage.find(ctx->message) != std::string::npos ||
844 ctx->message.find(errorMessage) != std::string::npos)) {
845 site.source = ctx->source;
846 site.line = ctx->line;
847 site.function = ctx->function;
848 }
849 }
850 if (site.empty()) {
851 SQStackInfos si;
852 if (SQ_SUCCEEDED(sq_stackinfos(vm_, 1, &si))) {
853 if (si.source) site.source = si.source;
854 site.line = static_cast<int>(si.line);
855 if (si.funcname) site.function = si.funcname;
856 }
857 }
858 }
859 markErrorUses(site, hintVars);
860 // Ensure the error is marked on the render flow even if Exception ctor
861 // already did (idempotent append of another Error node is fine).
862 if (renderTraceEnabled_) renderFlow_.error(errorMessage.c_str());
863
864 std::string report;
865 if (vm_ || !graph_.events().empty()) report += formatError(errorMessage, hintVars);
866 if (renderTraceEnabled_ && !renderFlow_.events().empty()) {
867 if (!report.empty()) report += "\n";
868 report += renderFlow_.formatErrorReport(errorMessage);
869 }
870 if (report.empty()) report = std::string("Error: ") + errorMessage + "\n";
871 lastReport_ = report;
872 lastError_ = errorMessage;
873 lastSlice_ = analyzeError(errorMessage, hintVars);
874
875 // If a scenario is being recorded, pair the failure report + site with it so
876 // the dumped scenario becomes a reproducible baseline + input sequence.
877 ScenarioRecorder::instance().setErrorInfo(report, site.source + ":" + std::to_string(site.line));
878
879 RenderVision::instance().notifyPending("error", site.source, site.line);
880 if (debugger().breakOnError()) {
881 // Godot "Break on Error": stop at the reported site. Block inside the
882 // hook so the IDE sees a stable frame instead of the next executed line.
884 dap().notifyStopped(PauseReason::Exception, site, errorMessage);
885 debugger().waitWhilePaused([this]() { pumpWhilePaused(); });
886 }
887
888 return lastReport_;
889}
890
892
893std::size_t mcpCallgraphEvents() { return DevTool::instance().graph().events().size(); }
894
896 return DevTool::instance().graph().currentStack().size();
897}
898
899void DevTool::recordMcpSnippetError(std::string report) {
900 lastError_ = report;
901 lastReport_ = std::move(report);
902 lastSlice_ = {};
903}
904
905void mcpRecordSnippetError(std::string report) { DevTool::instance().recordMcpSnippetError(std::move(report)); }
906
907const std::string& mcpLastReport() { return DevTool::instance().lastReport(); }
908
909std::string mcpFormatError(const std::string& message) {
911}
912
913void DevTool::profileCall(const std::string& func) {
914 profStack_.emplace_back(func, std::chrono::steady_clock::now());
915}
916
917void DevTool::profileLine(const std::string& func) {
918 const auto now = std::chrono::steady_clock::now();
919 if (!profStack_.empty()) {
920 auto& top = profStack_.back();
921 profile_[top.first].ns +=
922 std::chrono::duration_cast<std::chrono::nanoseconds>(now - top.second).count();
923 top.second = now;
924 }
925 if (!func.empty()) ++profile_[func].lines;
926}
927
928void DevTool::profileReturn() {
929 const auto now = std::chrono::steady_clock::now();
930 if (profStack_.empty()) return;
931 auto& top = profStack_.back();
932 profile_[top.first].ns +=
933 std::chrono::duration_cast<std::chrono::nanoseconds>(now - top.second).count();
934 ++profile_[top.first].calls;
935 profStack_.pop_back();
936}
937
938std::string DevTool::formatProfileReport() const {
939 std::ostringstream oss;
940 oss << "function, calls, lines, time_ms\n";
941 std::vector<std::pair<std::string, ProfileEntry>> rows(profile_.begin(), profile_.end());
942 std::sort(rows.begin(), rows.end(), [](const auto& a, const auto& b) {
943 return a.second.ns > b.second.ns;
944 });
945 for (const auto& [name, e] : rows) {
946 oss << name << ", " << e.calls << ", " << e.lines << ", "
947 << (static_cast<double>(e.ns) / 1e6) << "\n";
948 }
949 return oss.str();
950}
951
952} // namespace eve::dev
const std::string & s
struct SQVM * HSQUIRRELVM
Stable, structured diagnostics shared by engine modules.
eve::Value condition
HSQUIRRELVM vm
Definition ECS.cpp:38
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
int rows
Runtime game-world Discover snapshot for MCP / Play Host.
Versioned JSON facade shared by scripting, MCP and scenario tooling.
std::string message
const GltfImportRequest & request
wgpu::PopErrorScopeStatus status
glm::vec3 n
Definition Grass.cpp:63
float v
std::int32_t c
int h
Poco::JSON::Object::Ptr result
Project-script → MCP export registry.
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
int level
double dt
std::string error
Definition Package.cpp:174
int idx
std::string script
Definition PlayHost.cpp:117
std::string path
Definition PlayHost.cpp:111
PrimitiveHandle handle
Object::Ptr value
float t
unsigned line
std::string text
ScriptStructure out
std::string_view source
size_t begin
size_t end
std::string kind
Soft-restart a live game without unloading the resource cache.
The single Squirrel projection for common Result, Status and Value.
Structured operation status used by the common Result foundation.
Share string attribute map operations through the Windows Foundation DLL.
std::vector< std::string_view > lines
std::uint32_t depth
Owning, renderer-independent dynamic values.
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
EVENGINE_API_FOUNDATION public API.
Definition Runtime.h:189
void setErrorHandler(ErrorHandler handler)
Replaces the handler invoked for script errors at the Runtime boundary.
Definition Runtime.h:412
Exception raised at the public Runtime boundary.
Definition Runtime.h:61
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
static Status failure(StatusCode code, Diagnostic diagnostic)
Construct a failed status with one diagnostic.
Definition Status.cpp:28
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
In-engine AI / MCP session surface for DevTools.
Definition AiPanel.hpp:27
void addNote(std::string text)
Definition AiPanel.cpp:95
void setVisible(bool on)
Definition AiPanel.cpp:37
std::string statusLine() const
Compact status line for overlays / MCP resources.
Definition AiPanel.cpp:117
std::string formatLog(size_t max=64) const
Definition AiPanel.cpp:106
bool mcpConnected() const
Definition AiPanel.cpp:64
void toggleVisible()
Definition AiPanel.cpp:47
static AiPanel & instance()
Definition AiPanel.cpp:15
int mcpPort() const
Definition AiPanel.cpp:54
void drawImGui()
Optional ImGui draw hook. Default no-op: in-engine AI status is exposed via MCP / eve....
Definition AiPanel.cpp:140
bool isVisible() const
Definition AiPanel.cpp:42
SliceResult sliceBackward(const SliceCriterion &criterion) const
Dynamic backward slice from an error criterion. Follows data dependencies (Use←Def) and control prede...
uint32_t onLine(const SourceLoc &loc)
uint32_t onUse(const SourceLoc &loc, const std::string &var)
std::string formatErrorReport(const std::string &errorMessage, const SliceCriterion &criterion) const
Human-readable report: message + call stack + data-flow + slice locs.
uint32_t onDef(const SourceLoc &loc, const std::string &var)
std::vector< CallFrame > currentStack() const
EventsView events() const
In-engine runtime console / log ring buffer for DevTools.
std::vector< ConsoleLine > recent(size_t max=128) const
void addWarn(std::string text)
void addLog(std::string level, std::string text)
Append a leveled log line (thread-safe).
static ConsolePanel & instance()
std::string eval(const std::string &expression)
Evaluate a Squirrel expression against the root table and return a formatted result (or error message...
void addError(std::string text)
void addInfo(std::string text)
void attach(HSQUIRRELVM vm)
Attach to a Squirrel VM: capture print/script errors into the log.
std::string format(size_t max=128) const
void drawImGui()
Optional ImGui draw hook. Default no-op: console UI is registered by the host (see setImGuiDrawer) so...
void poll()
Accept clients + process one request batch (non-blocking).
int listen(uint16_t port)
Bind TCP listen port (0 = ephemeral). Returns bound port or 0 on failure.
void registerSource(std::string name, std::string content)
Register virtual source content for compiled buffers (compilestring).
void notifyStopped(PauseReason reason, const SourceLoc &loc, const std::string &description={})
Emit stopped event to the connected client (if any).
static DebugAdapter & instance()
Script + frame debugger: pause/step, breakpoints, watches.
Definition Debugger.hpp:86
void waitWhilePaused(const std::function< void()> &pump={})
Block until resume/step/detach (processes external poll callbacks).
Definition Debugger.cpp:780
void setBreakOnError(bool on)
Break on script errors (Godot "Break on Error"). Default off.
Definition Debugger.hpp:226
void stepInto()
Enter calls: stop on the next script line at any depth.
Definition Debugger.cpp:620
void refreshWatches()
Re-evaluate all watches against current VM (paused preferred).
Definition Debugger.cpp:897
void notifyFrameDone()
After a frame when StepFrame was active → return to Paused.
Definition Debugger.cpp:655
void stepOut()
Finish current function: stop when stack depth drops.
Definition Debugger.cpp:624
bool isPaused() const
Definition Debugger.hpp:133
RunMode mode() const
Definition Debugger.hpp:134
std::string onCall(SourceLoc loc)
Squirrel call debug hook ('c'). Records a frame on the active CallGraph.
Definition Debugger.cpp:500
void pauseAt(PauseReason reason, SourceLoc loc)
Pause and record the script site (copied; Observed until the next pause/resume). Thread: VM / game lo...
Definition Debugger.cpp:564
bool removeWatch(const std::string &expression)
Definition Debugger.cpp:878
void setCallGraph(CallGraph *graph)
Use DevTool's CallGraph for stack names (same object the slicer sees). Pass nullptr to record calls o...
Definition Debugger.cpp:462
void stepOver()
Skip calls: stop on the next line at ≤ current stack depth.
Definition Debugger.cpp:622
void addWatch(std::string expression)
Definition Debugger.cpp:869
bool shouldRunUpdate()
Frame loop: true ⇒ call eve_update this frame. Consumes StepFrame.
Definition Debugger.cpp:645
void pause(PauseReason reason=PauseReason::PauseKey)
Frame-level pause without a script site (PauseKey clears pauseLocation). For Exception / Snapshot,...
Definition Debugger.cpp:553
bool clearBreakpoint(std::string source, int line)
Definition Debugger.cpp:827
void setBreakpointsEnabled(bool on)
Master switch for all breakpoints ("skip all breakpoints").
Definition Debugger.hpp:229
int setBreakpoint(std::string source, int line, bool enabled=true, std::string condition={})
Add or update a line breakpoint. A later call with the same source+line replaces enabled and conditio...
Definition Debugger.cpp:805
void onReturn(const SourceLoc &loc)
Squirrel return debug hook ('r'). Pops the active CallGraph frame.
Definition Debugger.cpp:507
void setPump(PumpFn pump)
Definition Debugger.hpp:237
static Debugger & instance()
Definition Debugger.cpp:387
void step()
Convenience: script stepOver when mid-hook; otherwise one game frame. Prefer stepInto/stepOver/stepOu...
Definition Debugger.cpp:633
bool breakOnError() const
Definition Debugger.hpp:227
void attach(HSQUIRRELVM vm)
Definition Debugger.cpp:440
void stepLine()
Alias for stepInto (historical name).
Definition Debugger.hpp:127
VariableInfo evaluate(const std::string &expression, int frameLevel=0) const
Evaluate an expression in the given frame's scope. Understands plain names, a.b paths,...
void clearBreakpoints(const std::string &source={})
Definition Debugger.cpp:838
bool breakpointsEnabled() const
Definition Debugger.hpp:230
Platform-level script + render debugger / dynamic slicer front-end.
Definition DevTool.hpp:50
const std::string & lastReport() const
Definition DevTool.hpp:122
void enableRenderTrace(bool on=true)
Enable render-flow tracing without a Squirrel VM (C++ / unit tests).
Definition DevTool.cpp:176
int startDap(uint16_t port)
Start DAP server; returns bound port (0 on failure).
Definition DevTool.cpp:247
void handleDebugEvent(HSQUIRRELVM vm, int type, const char *source, int line, const char *funcname)
Definition DevTool.cpp:613
Debugger & debugger()
Definition DevTool.hpp:101
McpServer & mcp()
Definition DevTool.cpp:255
void attach(ssq::VM &vm, bool sampleLocals=true)
Attach script tracer to VM and enable render tracing.
Definition DevTool.cpp:143
void exposeScriptApi(ssq::VM &vm)
Expose eve.dev script API (pause/breakpoint/watch/snapshot/AI).
Definition DevTool.cpp:274
const std::string & lastError() const
Definition DevTool.hpp:123
Snapshot & snapshot()
Definition DevTool.hpp:102
CallGraph & graph()
Definition DevTool.hpp:97
void drawFrameStatsPanel()
Draw FPS / frame-time overlay when visible (call from UI/frame loop).
Definition DevTool.cpp:272
bool sampleLocals() const
Definition DevTool.hpp:94
int startMcp(uint16_t port)
Start MCP server for AI tooling; returns bound port (0 on failure).
Definition DevTool.cpp:251
std::string notifyError(const std::string &errorMessage, const std::vector< std::string > &hintVars={})
Record an error; includes script slice and render-pipeline slice when enabled.
Definition DevTool.cpp:834
ConsolePanel & console()
Definition DevTool.cpp:259
AiPanel & ai()
Definition DevTool.cpp:257
void recordMcpSnippetError(std::string report)
Replace the latest diagnostic with an owning MCP snippet report. Main/VM thread only; synchronous,...
Definition DevTool.cpp:899
void drawConsolePanel()
Draw DevTools console ImGui panel when visible (call from UI/frame loop).
Definition DevTool.cpp:270
std::string formatProfileReport() const
Definition DevTool.cpp:938
bool isAttached() const
Definition DevTool.hpp:90
std::string formatError(const std::string &errorMessage, const std::vector< std::string > &hintVars={}) const
Definition DevTool.cpp:772
void drawAiPanel()
Draw DevTools AI ImGui panel when visible (call from UI/frame loop).
Definition DevTool.cpp:268
static DevTool & instance()
Definition DevTool.cpp:138
SliceResult analyzeError(const std::string &errorMessage, const std::vector< std::string > &hintVars={}) const
Definition DevTool.cpp:740
FrameStatsPanel & frameStats()
Definition DevTool.cpp:261
DebugAdapter & dap()
Definition DevTool.hpp:104
Lightweight FPS / frame-time overlay for DevTools (0.6 closeout).
void setEntityCount(int count)
Optional entity / actor count shown in the overlay; negative clears.
int entityCount() const
-1 when unset
static FrameStatsPanel & instance()
void sample(float dtSeconds)
Feed one frame duration in seconds (must be finite and > 0). Updates EMA FPS and last frame milliseco...
std::string format() const
One-line summary for logs / scripts, e.g. 60.1 fps | 16.6 ms | 128 entities.
Embedded Model Context Protocol (MCP) server for AI-assisted game development.
Definition McpServer.hpp:35
void poll()
Accept clients + process one request batch (non-blocking).
int listen(uint16_t port)
Bind TCP listen port (0 = ephemeral). Returns bound port or 0 on failure.
static McpServer & instance()
static ReloadSession & instance()
Instance.
std::string formatErrorReport(const std::string &errorMessage, const RenderSliceCriterion &c={}) const
void error(const char *message) override
Error.
EventsView events() const
void notifyPending(const std::string &reason, const std::string &source, int line)
Record that a breakpoint / critical site wants a vision dump.
static RenderVision & instance()
void setErrorInfo(const std::string &report, const std::string &site)
Called by DevTool when a script error is dumped during recording.
bool stageFrame()
Re-push the next recorded frame's events into the event queue.
int framesRemaining() const
Number of frames remaining to stage.
void markFrame()
Begin a new frame bucket; no-op unless recording.
void cancel()
Abort recording and restore the previous event observer.
const std::string & errorReport() const
Error report.
bool begin(HSQUIRRELVM vm, std::string *err=nullptr)
Start recording: capture the baseline snapshot and observe the event queue.
bool recording() const
True while a scenario is being recorded.
static ScenarioRecorder & instance()
Instance.
static Snapshot & instance()
Definition Snapshot.cpp:468
SQInteger top
Definition Snapshot.cpp:115
void setRenderTracer(IRenderTracer *tracer)
Sets the render tracer.
IRenderTracer * renderTracer()
Renders tracer.
std::size_t resourceCacheCount()
Current ResourceManager cache entry count (for restart telemetry).
std::size_t mcpCallgraphStackDepth()
Definition DevTool.cpp:895
void clearScriptTools(HSQUIRRELVM owner)
Drop registry entries owned by owner.
std::size_t mcpCallgraphEvents()
Definition DevTool.cpp:893
std::uint32_t resetNativeStateProviders()
Reset every registered IStateProvider to its defaults.
std::string mcpFormatError(const std::string &message)
Definition DevTool.cpp:909
const std::string & mcpLastReport()
Definition DevTool.cpp:907
Result< Value > liveGameWorldSnapshot()
Build the Discover snapshot against the live engine.
Result< SoftRestartReport > executeSoftRestart(HSQUIRRELVM vm, SoftRestartRequest request)
Soft-restart the game attached to vm.
bool mcpDevAttached()
Thin hooks so McpServer.cpp need not include DevTool.hpp (avoids a cycle).
Definition DevTool.cpp:891
void clearWorldContext()
Drop the runtime world brief (soft restart with script reload).
void mcpRecordSnippetError(std::string report)
VM-thread-only owning diagnostic publication; clears stale slicing data.
Definition DevTool.cpp:905
void exposeMcpScriptApi(ssq::VM &vm)
Expose eve.mcp.tool/remove/tools/clear/attachEditor/detachEditor on a VM.
const Value * runtimeWorldContext() noexcept
Current runtime brief, or null when none is published. @ownership Borrowed; valid until the next publ...
Result< void > publishWorldContext(Value world)
Replace the runtime world brief published by the live game script.
@ Snapshot
Script state was restored while the debugger was already paused.
bool hasWorldContext() noexcept
Whether a runtime brief is currently published.
std::string formatScriptError(const ScriptErrorContext &ctx)
Formats a context into a human-readable multi-line report.
ssq::Table projectStatusResult(HSQUIRRELVM vm, const Status &status)
Project a checked native status that carries no payload.
const ScriptErrorContext * peekLastScriptError(HSQUIRRELVM vm)
Peeks at the last recorded error for a VM without clearing it.
ssq::Table projectResult(HSQUIRRELVM vm, Result< void > &&result)
Consume and project a void native Result using the common schema.
void setLastScriptError(HSQUIRRELVM vm, ScriptErrorContext ctx)
Records the last error for a VM (thread-local, synchronous consumers).
Result< Value > valueFromSquirrel(HSQUIRRELVM vm, SQInteger index, const SquirrelValueOptions &options)
Convert one Squirrel value into the canonical owning Value tree.
ScriptErrorContext captureScriptError(HSQUIRRELVM vm)
Captures the pending runtime error from inside the Squirrel error handler.
Build metadata (engine git commit, build time, third-party version).
Definition Build.cpp:16
Result< std::string > executeGameplayControlJson(std::string_view requestJson)
Parse, execute and serialize one gameplay-control JSON request.
constexpr std::string_view statusCodeName(StatusCode code) noexcept
Return the stable protocol spelling of a status code.
Definition Status.h:46
Criterion for a Weiser-style dynamic backward slice.
Definition CallGraph.hpp:57
std::vector< std::string > variables
Definition CallGraph.hpp:59
Outcome of a successful soft restart. @ownership Owning value; safe to keep across frames.
bool scriptsReloaded
Whether tracked scripts were re-dofile'd.
std::size_t resourceCountAfter
Cached resource entries after the restart.
Inputs for one soft restart. @thread Game / MCP poll thread only.
bool reloadScripts
When true (default), re-dofile tracked scripts after clearing persist/state roots so initializers run...
Source location in a Squirrel (or synthetic) script.
Definition CallGraph.hpp:16
std::string function
Definition CallGraph.hpp:19
bool empty() const
Definition CallGraph.hpp:21
std::string source
Definition CallGraph.hpp:17
Structured snapshot of a script error: message, throw site and stack.
Definition ScriptError.h:46
int line
1-based throw-site line; -1 when unknown.
Definition ScriptError.h:50
std::string function
Function of the throwing frame.
Definition ScriptError.h:49
bool reported
True when a reporter already handled this error.
Definition ScriptError.h:54
bool empty() const noexcept
True when no error payload was captured.
Definition ScriptError.h:57
std::string message
Raw error value ("kaboom", "42", ...).
Definition ScriptError.h:47
std::vector< ScriptFrame > stack
Call stack, innermost frame first.
Definition ScriptError.h:53
std::string source
Source of the throwing frame.
Definition ScriptError.h:48
glm::uvec4 info