载入中...
搜索中...
未找到
PlayHost.cpp
浏览该文件的文档.
1#include "devtools/PlayHost.h"
2
3#include "common/Capability.h"
10#include "devtools/Debugger.hpp"
13#include "devtools/PlayTrace.h"
14#include "devtools/Snapshot.hpp"
15
16#include <squirrel.h>
17
18#include <algorithm>
19#include <filesystem>
20#include <fstream>
21#include <set>
22#include <sstream>
23#include <utility>
24
25namespace eve::dev {
26namespace {
27
28constexpr std::string_view kPlaySchemaId = "evengine.play-request";
29constexpr std::string_view kPlayResponseId = "evengine.play-response";
30constexpr std::string_view kContractSchemaId = "evengine.game-agent-contract";
31constexpr std::int64_t kSchemaVersion = 1;
32constexpr std::int64_t kMaxFrameSteps = 1024;
33
34Result<const Value::Object*> asObject(const Value& value, std::string path) {
35 const auto* object = value.getIf<Value::Object>();
36 if (!object)
38 Diagnostic::error(DiagnosticCode::ParseError, "play value must be an object", std::move(path)));
40}
41
42Result<void> knownFields(const Value::Object& object, const std::set<std::string>& allowed,
43 std::string_view path) {
44 for (const auto& [name, value] : object) {
45 (void)value;
46 if (!allowed.contains(name))
48 Diagnostic::error(DiagnosticCode::ParseError, "unknown play field", std::string(path) + "." + name));
49 }
50 return Result<void>::success();
51}
52
53Result<const Value*> member(const Value::Object& object, std::string_view name, Value::Type type,
54 std::string_view path) {
55 const auto found = object.find(std::string(name));
56 if (found == object.end() || found->second.type() != type)
58 DiagnosticCode::ParseError, "missing or invalid play field", std::string(path) + "." + std::string(name)));
59 return Result<const Value*>::success(&found->second);
60}
61
62Result<std::string> stringMember(const Value::Object& object, std::string_view name,
63 std::string_view path) {
64 auto found = member(object, name, Value::Type::String, path);
65 if (!found) return Result<std::string>::failure(found.status());
66 return Result<std::string>::success(found.value()->asString());
67}
68
69Result<std::int64_t> intMember(const Value::Object& object, std::string_view name, std::string_view path) {
70 auto found = member(object, name, Value::Type::Int64, path);
71 if (!found) return Result<std::int64_t>::failure(found.status());
72 return Result<std::int64_t>::success(found.value()->asInt());
73}
74
75Result<void> optionalString(const Value::Object& object, std::string_view name, std::string_view path,
76 std::string* out) {
77 const auto found = object.find(std::string(name));
78 if (found == object.end()) return Result<void>::success();
79 if (!found->second.isString())
80 return Result<void>::failure(Diagnostic::error(DiagnosticCode::ParseError, "play field must be a string",
81 std::string(path) + "." + std::string(name)));
82 *out = found->second.asString();
83 return Result<void>::success();
84}
85
86std::vector<std::string> splitPath(std::string_view dotted) {
87 std::vector<std::string> parts;
88 std::string current;
89 for (char ch : dotted) {
90 if (ch == '.') {
91 if (!current.empty()) parts.push_back(std::move(current));
92 current.clear();
93 } else {
94 current.push_back(ch);
95 }
96 }
97 if (!current.empty()) parts.push_back(std::move(current));
98 return parts;
99}
100
101Value playResponse(std::string op, Value::Object extra) {
102 extra.emplace("op", Value(std::move(op)));
103 extra.emplace("schemaId", Value(std::string(kPlayResponseId)));
104 extra.emplace("schemaVersion", Value(kSchemaVersion));
105 return Value(std::move(extra));
106}
107
108struct ObservationSpec {
109 std::string id;
110 std::string kind;
111 std::string path;
112 std::vector<std::string> fields;
113};
114
115struct ActionSpec {
116 std::string id;
117 std::string script;
118 std::string action;
119};
120
121struct ParsedContract {
122 std::string id;
123 std::string defaultStep;
124 std::string actionSource;
125 std::string actionDomain;
126 std::vector<ObservationSpec> observations;
127 std::vector<ActionSpec> actions;
128 std::vector<std::string> captureRequiredFor;
129};
130
131Result<std::vector<std::string>> stringArray(const Value& value, std::string path) {
132 const auto* array = value.getIf<Value::Array>();
133 if (!array)
134 return Result<std::vector<std::string>>::failure(
135 Diagnostic::error(DiagnosticCode::ParseError, "play array must contain strings", path));
136 std::vector<std::string> out;
137 for (std::size_t index = 0; index < array->size(); ++index) {
138 if (!(*array)[index].isString())
139 return Result<std::vector<std::string>>::failure(Diagnostic::error(
140 DiagnosticCode::ParseError, "play array entry must be a string", path + "." + std::to_string(index)));
141 out.push_back((*array)[index].asString());
142 }
143 return Result<std::vector<std::string>>::success(std::move(out));
144}
145
146Result<ParsedContract> parseContract(const Value& contract) {
147 auto root = asObject(contract, "contract");
148 if (!root) return Result<ParsedContract>::failure(root.status());
149 auto known =
150 knownFields(*root.value(),
151 {"actions", "capture", "clock", "entry", "id", "observations", "schemaId", "schemaVersion",
152 "smoke", "tolerances"},
153 "contract");
154 if (!known) return Result<ParsedContract>::failure(known.status());
155 auto schemaId = stringMember(*root.value(), "schemaId", "contract");
156 if (!schemaId) return Result<ParsedContract>::failure(schemaId.status());
157 auto version = intMember(*root.value(), "schemaVersion", "contract");
158 if (!version) return Result<ParsedContract>::failure(version.status());
159 auto id = stringMember(*root.value(), "id", "contract");
160 if (!id) return Result<ParsedContract>::failure(id.status());
161 auto entry = stringMember(*root.value(), "entry", "contract");
162 if (!entry) return Result<ParsedContract>::failure(entry.status());
163 if (schemaId.value() != kContractSchemaId || version.value() != kSchemaVersion)
165 DiagnosticCode::Unsupported, "unsupported game agent contract schema", "contract.schemaVersion"));
166 if (id.value().empty())
168 Diagnostic::error(DiagnosticCode::ParseError, "contract id must not be empty", "contract.id"));
169
170 ParsedContract parsed;
171 parsed.id = id.value();
172 parsed.defaultStep = "frame";
173
174 const auto clock = root.value()->find("clock");
175 if (clock != root.value()->end()) {
176 auto object = asObject(clock->second, "contract.clock");
177 if (!object) return Result<ParsedContract>::failure(object.status());
178 auto clockKnown = knownFields(*object.value(), {"defaultStep"}, "contract.clock");
179 if (!clockKnown) return Result<ParsedContract>::failure(clockKnown.status());
180 auto step = stringMember(*object.value(), "defaultStep", "contract.clock");
181 if (!step) return Result<ParsedContract>::failure(step.status());
182 parsed.defaultStep = step.value();
183 if (parsed.defaultStep != "frame")
185 "P0 play host only supports frame defaultStep",
186 "contract.clock.defaultStep"));
187 }
188
189 const auto observations = root.value()->find("observations");
190 if (observations == root.value()->end() || !observations->second.isArray())
192 Diagnostic::error(DiagnosticCode::ParseError, "contract requires observations", "contract.observations"));
193 const auto* array = observations->second.getIf<Value::Array>();
194 for (std::size_t index = 0; index < array->size(); ++index) {
195 const std::string itemPath = "contract.observations." + std::to_string(index);
196 auto object = asObject((*array)[index], itemPath);
197 if (!object) return Result<ParsedContract>::failure(object.status());
198 auto itemKnown = knownFields(*object.value(), {"fields", "id", "kind", "path"}, itemPath);
199 if (!itemKnown) return Result<ParsedContract>::failure(itemKnown.status());
200 ObservationSpec spec;
201 auto specId = stringMember(*object.value(), "id", itemPath);
202 if (!specId) return Result<ParsedContract>::failure(specId.status());
203 auto kind = stringMember(*object.value(), "kind", itemPath);
204 if (!kind) return Result<ParsedContract>::failure(kind.status());
205 auto path = stringMember(*object.value(), "path", itemPath);
206 if (!path) return Result<ParsedContract>::failure(path.status());
207 spec.id = specId.value();
208 spec.kind = kind.value();
209 spec.path = path.value();
210 const auto fields = object.value()->find("fields");
211 if (fields != object.value()->end()) {
212 auto parsedFields = stringArray(fields->second, itemPath + ".fields");
213 if (!parsedFields) return Result<ParsedContract>::failure(parsedFields.status());
214 spec.fields = std::move(parsedFields).takeValue();
215 }
216 parsed.observations.push_back(std::move(spec));
217 }
218
219 const auto smoke = root.value()->find("smoke");
220 if (smoke != root.value()->end()) {
221 auto object = asObject(smoke->second, "contract.smoke");
222 if (!object) return Result<ParsedContract>::failure(object.status());
223 auto smokeKnown =
224 knownFields(*object.value(), {"maxHostFrames", "mustReach", "scene", "seed"}, "contract.smoke");
225 if (!smokeKnown) return Result<ParsedContract>::failure(smokeKnown.status());
226 auto scene = stringMember(*object.value(), "scene", "contract.smoke");
227 if (!scene) return Result<ParsedContract>::failure(scene.status());
228 const auto mustReach = object.value()->find("mustReach");
229 if (mustReach != object.value()->end()) {
230 auto reached = stringArray(mustReach->second, "contract.smoke.mustReach");
231 if (!reached) return Result<ParsedContract>::failure(reached.status());
232 }
233 }
234
235 const auto capture = root.value()->find("capture");
236 if (capture != root.value()->end()) {
237 auto object = asObject(capture->second, "contract.capture");
238 if (!object) return Result<ParsedContract>::failure(object.status());
239 auto captureKnown = knownFields(*object.value(), {"backend", "requiredFor"}, "contract.capture");
240 if (!captureKnown) return Result<ParsedContract>::failure(captureKnown.status());
241 auto backend = stringMember(*object.value(), "backend", "contract.capture");
242 if (!backend) return Result<ParsedContract>::failure(backend.status());
243 if (backend.value() != "engine-readback")
245 DiagnosticCode::Unsupported, "capture backend must be engine-readback", "contract.capture.backend"));
246 const auto requiredFor = object.value()->find("requiredFor");
247 if (requiredFor != object.value()->end()) {
248 auto names = stringArray(requiredFor->second, "contract.capture.requiredFor");
249 if (!names) return Result<ParsedContract>::failure(names.status());
250 parsed.captureRequiredFor = std::move(names).takeValue();
251 }
252 }
253
254 const auto actions = root.value()->find("actions");
255 if (actions != root.value()->end()) {
256 auto object = asObject(actions->second, "contract.actions");
257 if (!object) return Result<ParsedContract>::failure(object.status());
258 auto actionsKnown = knownFields(*object.value(), {"domain", "map", "source"}, "contract.actions");
259 if (!actionsKnown) return Result<ParsedContract>::failure(actionsKnown.status());
260 auto source = stringMember(*object.value(), "source", "contract.actions");
261 if (!source) return Result<ParsedContract>::failure(source.status());
262 parsed.actionSource = source.value();
263 if (parsed.actionSource != "script-map" && parsed.actionSource != "gameplay-domain")
265 DiagnosticCode::Unsupported, "unsupported actions.source", "contract.actions.source"));
266 auto domainField = optionalString(*object.value(), "domain", "contract.actions", &parsed.actionDomain);
267 if (!domainField) return Result<ParsedContract>::failure(domainField.status());
268 const auto map = object.value()->find("map");
269 if (map != object.value()->end()) {
270 const auto* array = map->second.getIf<Value::Array>();
271 if (!array)
273 DiagnosticCode::ParseError, "actions.map must be an array", "contract.actions.map"));
274 for (std::size_t index = 0; index < array->size(); ++index) {
275 const std::string itemPath = "contract.actions.map." + std::to_string(index);
276 auto item = asObject((*array)[index], itemPath);
277 if (!item) return Result<ParsedContract>::failure(item.status());
278 auto itemKnown = knownFields(*item.value(), {"action", "id", "script"}, itemPath);
279 if (!itemKnown) return Result<ParsedContract>::failure(itemKnown.status());
280 ActionSpec spec;
281 auto actionId = stringMember(*item.value(), "id", itemPath);
282 if (!actionId) return Result<ParsedContract>::failure(actionId.status());
283 spec.id = actionId.value();
284 auto scriptField = optionalString(*item.value(), "script", itemPath, &spec.script);
285 if (!scriptField) return Result<ParsedContract>::failure(scriptField.status());
286 auto mappedAction = optionalString(*item.value(), "action", itemPath, &spec.action);
287 if (!mappedAction) return Result<ParsedContract>::failure(mappedAction.status());
288 if (parsed.actionSource == "script-map" && spec.script.empty())
290 DiagnosticCode::ParseError, "script-map action requires script", itemPath + ".script"));
291 if (parsed.actionSource == "gameplay-domain" && spec.action.empty())
293 DiagnosticCode::ParseError, "gameplay-domain action requires action", itemPath + ".action"));
294 parsed.actions.push_back(std::move(spec));
295 }
296 }
297 }
298
299 const auto tolerances = root.value()->find("tolerances");
300 if (tolerances != root.value()->end()) {
301 auto object = asObject(tolerances->second, "contract.tolerances");
302 if (!object) return Result<ParsedContract>::failure(object.status());
303 auto tolKnown = knownFields(*object.value(), {"numericAbs", "screenshot"}, "contract.tolerances");
304 if (!tolKnown) return Result<ParsedContract>::failure(tolKnown.status());
305 }
306
307 return Result<ParsedContract>::success(std::move(parsed));
308}
309
310Result<const ObservationSpec*> findObservation(const ParsedContract& contract, std::string_view id) {
311 for (const auto& spec : contract.observations) {
312 if (spec.id == id) return Result<const ObservationSpec*>::success(&spec);
313 }
315 Diagnostic::error(DiagnosticCode::NotFound, "observation id was not declared", "request.observation"));
316}
317
318Result<const ActionSpec*> findAction(const ParsedContract& contract, std::string_view id) {
319 for (const auto& spec : contract.actions) {
320 if (spec.id == id) return Result<const ActionSpec*>::success(&spec);
321 }
323 Diagnostic::error(DiagnosticCode::NotFound, "action id was not declared", "request.action"));
324}
325
326Result<Value> requireContract(IPlayHostRuntime& runtime) {
327 auto loaded = runtime.loadContract();
328 if (!loaded) {
329 if (loaded.code() == StatusCode::NotFound)
331 Diagnostic::error(DiagnosticCode::Unsupported, "play observe requires game.agent.json", "contract"));
332 return Result<Value>::failure(loaded.status());
333 }
334 return loaded;
335}
336
337Value encodeDomains(const std::vector<std::string>& domains) {
339 for (const auto& domain : domains) output.emplace_back(domain);
340 return Value(std::move(output));
341}
342
343Result<Value> opStatus(IPlayHostRuntime& runtime) {
344 Value::Object extra{{"paused", Value(runtime.paused())},
345 {"hostFrame", Value(static_cast<std::int64_t>(runtime.hostFrame()))},
346 {"domains", encodeDomains(runtime.gameplayDomains())}};
347 GameWorldSnapshotInput worldInput;
348 worldInput.domains = runtime.gameplayDomains();
349 worldInput.gameRoot = McpServer::instance().gameRoot();
351 worldInput.configTitle = readConfigTitle(vm);
352 worldInput.configuredModules = readConfiguredModules(vm);
353 worldInput.liveModules = readLiveModules(vm);
354
355 auto loaded = runtime.loadContract();
356 if (loaded) {
357 auto parsed = parseContract(loaded.value());
358 if (!parsed) return Result<Value>::failure(parsed.status());
359 extra.emplace("contractId", Value(parsed.value().id));
360 extra.emplace("contractLoaded", Value(true));
361 worldInput.contractId = parsed.value().id;
362 worldInput.contractLoaded = true;
363 auto snapshot = buildGameWorldSnapshot(worldInput);
364 if (!snapshot) return Result<Value>::failure(snapshot.status());
365 extra.emplace("gameWorld", std::move(snapshot).takeValue());
366 } else if (loaded.code() == StatusCode::NotFound) {
367 extra.emplace("contractLoaded", Value(false));
368 auto snapshot = buildGameWorldSnapshot(worldInput);
369 if (!snapshot) return Result<Value>::failure(snapshot.status());
370 extra.emplace("gameWorld", std::move(snapshot).takeValue());
371 } else {
372 return Result<Value>::failure(loaded.status());
373 }
374 return Result<Value>::success(playResponse("status", std::move(extra)));
375}
376
377Result<Value> opClock(const Value::Object& root, IPlayHostRuntime& runtime) {
378 auto mode = stringMember(root, "mode", "request");
379 if (!mode) return Result<Value>::failure(mode.status());
380 if (mode.value() == "pause") runtime.pause();
381 else if (mode.value() == "play") runtime.play();
382 else
384 Diagnostic::error(DiagnosticCode::ParseError, "clock mode must be pause or play", "request.mode"));
386 playResponse("clock", {{"mode", Value(mode.value())}, {"paused", Value(runtime.paused())}}));
387}
388
389Result<Value> opStep(const Value::Object& root, IPlayHostRuntime& runtime) {
390 std::string clock = "frame";
391 auto clockField = optionalString(root, "clock", "request", &clock);
392 if (!clockField) return Result<Value>::failure(clockField.status());
393 if (clock != "frame")
395 DiagnosticCode::Unsupported, "P0 play host only steps the host frame clock", "request.clock"));
396 auto count = intMember(root, "count", "request");
397 if (!count) return Result<Value>::failure(count.status());
398 if (count.value() < 1 || count.value() > kMaxFrameSteps)
400 Diagnostic::error(DiagnosticCode::ParseError, "step count must be between 1 and 1024", "request.count"));
401 auto stepped = runtime.stepFrames(count.value());
402 if (!stepped) return Result<Value>::failure(stepped.status());
403 return Result<Value>::success(playResponse(
404 "step", {{"clock", Value(std::move(clock))},
405 {"count", Value(count.value())},
406 {"hostFrame", Value(static_cast<std::int64_t>(runtime.hostFrame()))},
407 {"paused", Value(runtime.paused())}}));
408}
409
410Result<Value> opObserve(const Value::Object& root, IPlayHostRuntime& runtime) {
411 auto observation = stringMember(root, "observation", "request");
412 if (!observation) return Result<Value>::failure(observation.status());
413 auto contractValue = requireContract(runtime);
414 if (!contractValue) return Result<Value>::failure(contractValue.status());
415 auto parsed = parseContract(contractValue.value());
416 if (!parsed) return Result<Value>::failure(parsed.status());
417 auto spec = findObservation(parsed.value(), observation.value());
418 if (!spec) return Result<Value>::failure(spec.status());
419 if (spec.value()->kind != "script-root")
421 DiagnosticCode::Unsupported, "P0 play host only observes script-root", "request.observation"));
422 // Prefer gameState (ai-game contract). Legacy `mode` string roots still work once, with a
423 // deprecated flag so agents migrate (EM4). Owner: play-host; remove after 2026-12-31.
424 std::string observedPath = spec.value()->path;
425 bool deprecated = false;
426 auto state = runtime.observeScriptRoot(observedPath, spec.value()->fields);
427 if (!state && observedPath == "mode") {
428 auto fallback = runtime.observeScriptRoot("gameState", spec.value()->fields);
429 if (fallback) {
430 state = std::move(fallback);
431 observedPath = "gameState";
432 deprecated = true;
433 }
434 } else if (state && observedPath == "mode") {
435 deprecated = true;
436 }
437 if (!state) return Result<Value>::failure(state.status());
438 Value::Object payload{{"observation", Value(observation.value())},
439 {"path", Value(observedPath)},
440 {"state", std::move(state).takeValue()}};
441 if (deprecated) payload.emplace("deprecated", Value("observation.path=mode; use paths.gameState / gameState"));
442 return Result<Value>::success(playResponse("observe", std::move(payload)));
443}
444
445Result<Value> opCapture(const Value::Object& root, IPlayHostRuntime& runtime) {
446 std::string path = "mcp_screenshot.png";
447 auto pathField = optionalString(root, "path", "request", &path);
448 if (!pathField) return Result<Value>::failure(pathField.status());
449 if (path.empty()) path = "mcp_screenshot.png";
450 auto captured = runtime.capturePng(std::move(path));
451 if (!captured) return Result<Value>::failure(captured.status());
452 auto object = asObject(captured.value(), "capture");
453 if (!object) return Result<Value>::failure(object.status());
454 Value::Object extra = *object.value();
455 extra.emplace("backend", Value("engine-readback"));
456 return Result<Value>::success(playResponse("capture", std::move(extra)));
457}
458
459Result<Value> opCheckpoint(const Value::Object& root, IPlayHostRuntime& runtime) {
460 auto mode = stringMember(root, "mode", "request");
461 if (!mode) return Result<Value>::failure(mode.status());
462 if (mode.value() == "capture") {
463 auto json = runtime.captureCheckpoint();
464 if (!json) return Result<Value>::failure(json.status());
466 playResponse("checkpoint", {{"mode", Value("capture")}, {"json", Value(std::move(json).takeValue())}}));
467 }
468 if (mode.value() == "restore") {
469 auto json = stringMember(root, "json", "request");
470 if (!json) return Result<Value>::failure(json.status());
471 auto restored = runtime.restoreCheckpoint(json.value());
472 if (!restored) return Result<Value>::failure(restored.status());
473 return Result<Value>::success(playResponse("checkpoint", {{"mode", Value("restore")}}));
474 }
476 Diagnostic::error(DiagnosticCode::ParseError, "checkpoint mode must be capture or restore", "request.mode"));
477}
478
479Result<Value> opAct(const Value::Object& root, IPlayHostRuntime& runtime) {
480 auto action = stringMember(root, "action", "request");
481 if (!action) return Result<Value>::failure(action.status());
482 auto contractValue = requireContract(runtime);
483 if (!contractValue) return Result<Value>::failure(contractValue.status());
484 auto parsed = parseContract(contractValue.value());
485 if (!parsed) return Result<Value>::failure(parsed.status());
486 auto spec = findAction(parsed.value(), action.value());
487 if (!spec) return Result<Value>::failure(spec.status());
488 if (parsed.value().actionSource == "script-map") {
489 auto invoked = runtime.invokeScriptAction(spec.value()->id, spec.value()->script);
490 if (!invoked) return Result<Value>::failure(invoked.status());
491 return Result<Value>::success(playResponse("act", {{"action", Value(action.value())},
492 {"source", Value("script-map")},
493 {"receipt", std::move(invoked).takeValue()}}));
494 }
495 if (parsed.value().actionSource != "gameplay-domain")
497 Diagnostic::error(DiagnosticCode::Unsupported, "unsupported actions.source", "contract.actions.source"));
498 const auto commandField = root.find("command");
499 if (commandField == root.end())
501 Diagnostic::error(DiagnosticCode::ParseError, "gameplay-domain act requires command", "request.command"));
502 auto commandObject = asObject(commandField->second, "request.command");
503 if (!commandObject) return Result<Value>::failure(commandObject.status());
504 Value::Object command = *commandObject.value();
505 if (command.find("action") == command.end()) command.emplace("action", Value(spec.value()->action));
506 std::string domain = parsed.value().actionDomain;
507 auto domainField = optionalString(root, "domain", "request", &domain);
508 if (!domainField) return Result<Value>::failure(domainField.status());
509 if (domain.empty())
511 Diagnostic::error(DiagnosticCode::ParseError, "gameplay-domain act requires domain", "request.domain"));
512 const auto sessionField = root.find("session");
513 const auto instanceField = root.find("instance");
514 if (sessionField == root.end() || instanceField == root.end())
516 DiagnosticCode::ParseError, "gameplay-domain act requires session and instance", "request.session"));
517 Value::Object gameplay{{"schemaId", Value("evengine.gameplay-control-request")},
518 {"schemaVersion", Value(std::int64_t{1})},
519 {"op", Value("submit")},
520 {"domain", Value(std::move(domain))},
521 {"instance", instanceField->second},
522 {"session", sessionField->second},
523 {"command", Value(std::move(command))}};
524 auto submitted = executeGameplayControlRequest(Value(std::move(gameplay)));
525 if (!submitted) return Result<Value>::failure(submitted.status());
526 return Result<Value>::success(playResponse("act", {{"action", Value(action.value())},
527 {"source", Value("gameplay-domain")},
528 {"gameplay", std::move(submitted).takeValue()}}));
529}
530
531Result<Value> opTrace() {
533 playResponse("trace", {{"recording", PlayTraceBuffer::instance().exportTrace()}}));
534}
535
536Result<Value> opReplay(const Value::Object& root, IPlayHostRuntime& runtime) {
537 const auto recording = root.find("recording");
538 if (recording == root.end())
540 Diagnostic::error(DiagnosticCode::ParseError, "replay requires recording", "request.recording"));
541 return replayPlayTrace(recording->second, runtime);
542}
543
544bool sessionWantsTrace() {
546 if (!session.active()) return false;
547 const auto phase = session.phase();
550}
551
552void tryRecordEvidence(std::string criterionId, std::string kind, std::string summary, std::string artifact) {
554 if (!session.active() || PlayTraceBuffer::instance().isReplaying() || criterionId.empty()) return;
555 AgentDevelopmentEvidence evidence;
556 evidence.criterionId = std::move(criterionId);
557 evidence.kind = std::move(kind);
558 evidence.status = "pass";
559 evidence.summary = std::move(summary);
560 evidence.artifact = std::move(artifact);
561 (void)session.record(session.sessionId(), std::move(evidence));
562}
563
564bool hasCriterion(const AgentDevelopmentSession& session, std::string_view id) {
565 for (const auto& criterion : session.criteria()) {
566 if (criterion.id == id) return true;
567 }
568 return false;
569}
570
571void maybeAutoEvidence(const Value::Object& request, const Value& response, IPlayHostRuntime& runtime) {
573 if (!session.active() || PlayTraceBuffer::instance().isReplaying()) return;
574 const auto opField = request.find("op");
575 if (opField == request.end() || !opField->second.isString()) return;
576 const std::string& op = opField->second.asString();
577 std::string criterionId;
578 optionalString(request, "criterionId", "request", &criterionId).ignore("optional play criterionId");
579 const auto* responseObject = response.getIf<Value::Object>();
580 if (op == "observe") {
581 std::string observation;
582 optionalString(request, "observation", "request", &observation).ignore("optional play observation");
583 if (criterionId.empty() && hasCriterion(session, observation)) criterionId = observation;
584 tryRecordEvidence(std::move(criterionId), "runtime-observation", "play observe " + observation, {});
585 return;
586 }
587 if (op == "capture") {
588 std::string path;
589 if (responseObject) {
590 const auto found = responseObject->find("path");
591 if (found != responseObject->end() && found->second.isString()) path = found->second.asString();
592 }
593 if (criterionId.empty() && hasCriterion(session, "visual")) criterionId = "visual";
594 if (criterionId.empty()) {
595 auto loaded = runtime.loadContract();
596 if (loaded) {
597 auto parsed = parseContract(loaded.value());
598 if (parsed) {
599 for (const auto& name : parsed.value().captureRequiredFor) {
600 if (hasCriterion(session, name)) {
601 criterionId = name;
602 break;
603 }
604 }
605 }
606 }
607 }
608 tryRecordEvidence(std::move(criterionId), "screenshot", "play capture", std::move(path));
609 return;
610 }
611 if (op == "checkpoint") {
612 if (criterionId.empty() && hasCriterion(session, "checkpoint")) criterionId = "checkpoint";
613 if (criterionId.empty() && hasCriterion(session, "recovery")) criterionId = "recovery";
614 tryRecordEvidence(std::move(criterionId), "checkpoint", "play checkpoint", {});
615 return;
616 }
617 if (op == "batch") {
618 if (criterionId.empty() && hasCriterion(session, "smoke")) criterionId = "smoke";
619 tryRecordEvidence(std::move(criterionId), "play-trace", "play batch", {});
620 }
621}
622
623void afterPlaySuccess(const Value& request, const Value& response, IPlayHostRuntime& runtime) {
624 auto root = request.getIf<Value::Object>();
625 if (!root) return;
627 std::string trace;
628 optionalString(*root, "trace", "request", &trace).ignore("trace already validated by dispatch");
629 const auto opField = root->find("op");
630 const std::string op = (opField != root->end() && opField->second.isString()) ? opField->second.asString() : "";
631 const bool skipTrace = op == "status" || op == "clock" || op == "trace" || op == "replay" || op == "batch";
632 bool append = trace == "append" || (trace.empty() && sessionWantsTrace());
633 if (trace == "off") append = false;
634 if (append && !skipTrace) {
636 std::string contractId;
637 std::string contractHash;
638 auto loaded = runtime.loadContract();
639 if (loaded) {
640 auto parsed = parseContract(loaded.value());
641 if (parsed) contractId = parsed.value().id;
642 auto digest = playObservationDigest(loaded.value());
643 if (digest) contractHash = std::move(digest).takeValue();
644 }
645 PlayTraceBuffer::instance().begin(std::move(contractId), std::move(contractHash), 0, {});
646 }
647 PlayTraceBuffer::instance().append(request, response, runtime.hostFrame());
648 }
649 maybeAutoEvidence(*root, response, runtime);
650}
651
652Result<Value> dispatchOne(const Value& request, IPlayHostRuntime& runtime, bool inBatch);
653
654Result<Value> opBatch(const Value::Object& root, IPlayHostRuntime& runtime) {
655 auto requests = member(root, "requests", Value::Type::Array, "request");
656 if (!requests) return Result<Value>::failure(requests.status());
657 const auto* array = requests.value()->getIf<Value::Array>();
658 Value::Array results;
659 for (std::size_t index = 0; index < array->size(); ++index) {
660 auto one = dispatchOne((*array)[index], runtime, true);
661 if (!one) return Result<Value>::failure(one.status());
662 results.push_back(std::move(one).takeValue());
663 }
664 const auto count = static_cast<std::int64_t>(results.size());
666 playResponse("batch", {{"count", Value(count)}, {"results", Value(std::move(results))}}));
667}
668
669Result<Value> dispatchOne(const Value& request, IPlayHostRuntime& runtime, bool inBatch) {
670 auto root = asObject(request, "request");
671 if (!root) return Result<Value>::failure(root.status());
672 static const std::set<std::string> allowed{
673 "action", "clock", "command", "count", "criterionId", "domain",
674 "instance", "json", "mode", "observation", "op", "path",
675 "recording", "requests", "schemaId", "schemaVersion","session", "trace"};
676 auto known = knownFields(*root.value(), allowed, "request");
677 if (!known) return Result<Value>::failure(known.status());
678 auto schemaId = stringMember(*root.value(), "schemaId", "request");
679 if (!schemaId) return Result<Value>::failure(schemaId.status());
680 auto version = intMember(*root.value(), "schemaVersion", "request");
681 if (!version) return Result<Value>::failure(version.status());
682 if (schemaId.value() != kPlaySchemaId || version.value() != kSchemaVersion)
684 Diagnostic::error(DiagnosticCode::Unsupported, "unsupported play request schema", "request.schemaVersion"));
685 std::string trace;
686 auto traceField = optionalString(*root.value(), "trace", "request", &trace);
687 if (!traceField) return Result<Value>::failure(traceField.status());
688 if (!trace.empty() && trace != "off" && trace != "append")
690 Diagnostic::error(DiagnosticCode::ParseError, "trace must be off or append", "request.trace"));
691 auto op = stringMember(*root.value(), "op", "request");
692 if (!op) return Result<Value>::failure(op.status());
693 auto executed = [&]() -> Result<Value> {
694 if (op.value() == "batch") {
695 if (inBatch)
697 Diagnostic::error(DiagnosticCode::Unsupported, "nested play batch is not allowed", "request.op"));
698 return opBatch(*root.value(), runtime);
699 }
700 if (op.value() == "status") return opStatus(runtime);
701 if (op.value() == "clock") return opClock(*root.value(), runtime);
702 if (op.value() == "step") return opStep(*root.value(), runtime);
703 if (op.value() == "observe") return opObserve(*root.value(), runtime);
704 if (op.value() == "capture") return opCapture(*root.value(), runtime);
705 if (op.value() == "checkpoint") return opCheckpoint(*root.value(), runtime);
706 if (op.value() == "act") return opAct(*root.value(), runtime);
707 if (op.value() == "trace") return opTrace();
708 if (op.value() == "replay") return opReplay(*root.value(), runtime);
710 Diagnostic::error(DiagnosticCode::Unsupported, "unsupported play operation", "request.op"));
711 }();
712 if (!executed) return executed;
713 afterPlaySuccess(request, executed.value(), runtime);
714 return executed;
715}
716
717Result<Value> snapshotRoot(HSQUIRRELVM vm, std::string_view rootName, const std::vector<std::string>& fields) {
718 if (!vm)
720 "play observe requires an attached script VM", "observation"));
721 const auto roots = Snapshot::instance().rootsFor(vm);
722 if (std::find(roots.begin(), roots.end(), rootName) == roots.end())
724 DiagnosticCode::NotFound, "script root is excluded by snapshot policy", "observation.path"));
725 struct StackGuard {
727 SQInteger top;
728 ~StackGuard() { sq_settop(vm, top); }
729 } guard{vm, sq_gettop(vm)};
730 sq_pushroottable(vm);
731 const std::string name(rootName);
732 sq_pushstring(vm, name.c_str(), -1);
733 if (SQ_FAILED(sq_rawget(vm, -2)))
735 Diagnostic::error(DiagnosticCode::NotFound, "script root was not found", "observation.path"));
736 const SQInteger rootIndex = sq_gettop(vm);
737 script::SquirrelValueOptions options;
738 options.source = "observation." + name;
739 if (fields.empty()) return script::valueFromSquirrel(vm, rootIndex, options);
740 Value::Object projected;
741 for (const auto& field : fields) {
742 sq_settop(vm, rootIndex);
743 sq_push(vm, rootIndex);
744 const auto parts = splitPath(field);
745 if (parts.empty() || field.front() == '.' || field.back() == '.' || field.find("..") != std::string::npos)
747 Diagnostic::error(DiagnosticCode::ParseError, "invalid observation field path", "observation.fields"));
748 for (const auto& part : parts) {
749 // Raw table access never invokes a script delegate or getter.
750 if (sq_gettype(vm, -1) != OT_TABLE)
752 DiagnosticCode::NotFound, "observation path is not a table", "observation.fields." + field));
753 sq_pushstring(vm, part.c_str(), -1);
754 if (SQ_FAILED(sq_rawget(vm, -2)))
756 DiagnosticCode::NotFound, "observation field was not found", "observation.fields." + field));
757 sq_remove(vm, -2);
758 }
760 if (!value) return Result<Value>::failure(value.status());
761 projected.emplace(field, std::move(value).takeValue());
762 }
763 return Result<Value>::success(Value(std::move(projected)));
764}
765
766class EnginePlayHostRuntime final : public IPlayHostRuntime {
767public:
768 bool paused() const override { return Debugger::instance().isPaused(); }
769 std::uint64_t hostFrame() const override { return hostFrame_; }
770 void pause() override { Debugger::instance().pause(PauseReason::PauseKey); }
771 void play() override { Debugger::instance().resume(); }
772
773 Result<void> stepFrames(std::int64_t count) override {
774 Debugger::instance().stepFrames(static_cast<int>(count));
775 hostFrame_ += static_cast<std::uint64_t>(count);
776 return Result<void>::success();
777 }
778
779 Result<Value> loadContract() const override {
780 std::filesystem::path root = McpServer::instance().gameRoot();
781 if (root.empty()) {
782 std::error_code ec;
783 root = std::filesystem::current_path(ec);
784 if (ec)
786 Diagnostic::error(DiagnosticCode::Failed, "cannot resolve game root", "contract"));
787 }
788 const auto path = root / "game.agent.json";
789 std::error_code ec;
790 if (!std::filesystem::is_regular_file(path, ec))
792 Diagnostic::error(DiagnosticCode::NotFound, "game.agent.json was not found", "contract"));
793 std::ifstream in(path, std::ios::binary);
794 if (!in)
796 Diagnostic::error(DiagnosticCode::Failed, "cannot read game.agent.json", "contract"));
797 std::ostringstream contents;
798 contents << in.rdbuf();
799 return Value::fromJson(contents.str());
800 }
801
802 Result<Value> observeScriptRoot(std::string_view root,
803 const std::vector<std::string>& fields) const override {
804 return snapshotRoot(Debugger::instance().vm(), root, fields);
805 }
806
807 Result<Value> capturePng(std::string path) override {
808 auto* capture = eve::cap::query<IRenderCapture>();
809 if (!capture)
811 Diagnostic::error(DiagnosticCode::Unsupported, "IRenderCapture is not available", "capture"));
812 auto captured = capture->savePng(path);
813 if (!captured) return Result<Value>::failure(captured.status());
814 const CaptureImageInfo info = std::move(captured).value();
815 return Result<Value>::success(Value(Value::Object{{"height", Value(static_cast<std::int64_t>(info.height))},
816 {"path", Value(std::move(path))},
817 {"width", Value(static_cast<std::int64_t>(info.width))}}));
818 }
819
820 Result<std::string> captureCheckpoint() override {
822 if (!vm)
824 DiagnosticCode::Unsupported, "play checkpoint requires an attached script VM", "checkpoint"));
825 std::string error;
826 std::string json = Snapshot::instance().capture(vm, &error);
827 if (json.empty())
829 DiagnosticCode::Failed, error.empty() ? "checkpoint capture failed" : error, "checkpoint"));
830 return Result<std::string>::success(std::move(json));
831 }
832
833 Result<void> restoreCheckpoint(std::string_view json) override {
835 if (!vm)
837 DiagnosticCode::Unsupported, "play checkpoint requires an attached script VM", "checkpoint"));
838 std::string error;
839 if (!Snapshot::instance().restore(vm, std::string(json), &error))
841 DiagnosticCode::Failed, error.empty() ? "checkpoint restore failed" : error, "checkpoint"));
842 return Result<void>::success();
843 }
844
845 Result<Value> invokeScriptAction(std::string_view id, std::string_view source) override {
847 if (!vm)
849 DiagnosticCode::Unsupported, "play act requires an attached script VM", "request.action"));
850 const SQInteger top = sq_gettop(vm);
851 const std::string snippet(source);
852 if (SQ_FAILED(sq_compilebuffer(vm, snippet.c_str(), static_cast<SQInteger>(snippet.size()),
853 "<play-action>", SQTrue))) {
854 sq_settop(vm, top);
857 "request.action"));
858 }
859 sq_pushroottable(vm);
860 if (SQ_FAILED(sq_call(vm, 1, SQFalse, SQTrue))) {
861 sq_settop(vm, top);
864 "request.action"));
865 }
866 sq_settop(vm, top);
867 return Result<Value>::success(Value(Value::Object{{"action", Value(std::string(id))}}));
868 }
869
870 std::vector<std::string> gameplayDomains() const override {
871 std::vector<std::string> domains;
872 eve::cap::forEach<IGameplayControlProvider>([&](auto* candidate) {
873 if (candidate) domains.emplace_back(candidate->gameplayDomain());
874 });
875 std::sort(domains.begin(), domains.end());
876 return domains;
877 }
878
879private:
880 std::uint64_t hostFrame_ = 0;
881};
882
883EnginePlayHostRuntime& liveRuntime() {
884 static EnginePlayHostRuntime runtime;
885 return runtime;
886}
887
888} // namespace
889
891 return dispatchOne(request, runtime, false);
892}
893
895 return executePlayRequest(request, liveRuntime());
896}
897
898Result<std::string> executePlayJson(std::string_view requestJson) {
899 auto request = Value::fromJson(requestJson);
900 if (!request) return Result<std::string>::failure(request.status());
901 auto response = executePlayRequest(request.value());
902 if (!response) return Result<std::string>::failure(response.status());
903 return response.value().toJson();
904}
905
906} // namespace eve::dev
Value::Object payload
Trace trace
Definition Agent.cpp:50
int root
Definition AnimSmr.cpp:119
std::vector< eve::artifact::PartView > parts
std::string output
struct SQVM * HSQUIRRELVM
HSQUIRRELVM vm
Definition ECS.cpp:38
std::string name
Definition ECS.cpp:154
std::vector< std::string > fields
Definition ECS.cpp:42
EnvironmentMetricContract contract
Runtime game-world Discover snapshot for MCP / Play Host.
Versioned JSON facade shared by scripting, MCP and scenario tooling.
Host-neutral player-equivalent command and observation protocol.
const GltfImportRequest & request
wgpu::PopErrorScopeStatus status
std::string evidence
std::string id
std::string response
Snapshot snapshot
OceanRenderBackend backend
std::string error
Definition Package.cpp:174
RigidRecording recording
std::string action
Definition PlayHost.cpp:118
std::string script
Definition PlayHost.cpp:117
std::string path
Definition PlayHost.cpp:111
std::string defaultStep
Definition PlayHost.cpp:123
std::vector< ObservationSpec > observations
Definition PlayHost.cpp:126
std::vector< std::string > captureRequiredFor
Definition PlayHost.cpp:128
std::vector< ActionSpec > actions
Definition PlayHost.cpp:127
std::string actionSource
Definition PlayHost.cpp:124
std::string actionDomain
Definition PlayHost.cpp:125
Versioned Play Host protocol for Agent pause / step / observe / capture.
Versioned Play Trace recording, digest and replay.
std::unordered_set< std::string > loaded
Definition Plugins.cpp:24
std::weak_ptr< PrimitiveScene > scene
Object::Ptr value
std::string domain
bool found
ScriptStructure out
std::string_view source
size_t end
std::string kind
double current
std::string digest
const SquirrelValueOptions & options
int count
The single Squirrel projection for common Result, Status and Value.
float phase
std::optional< InteractionSession > session
Definition Tactics.cpp:39
Json object
float step
Definition TreeMesh.cpp:451
float(ui::Theme::* member)[4]
uint32_t index
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
static Result< Value > fromJson(std::string_view json)
Parse one strict JSON value into an owning Value.
Definition Value.cpp:177
std::map< std::string, Value > Object
Definition Value.h:34
Type
Runtime kind of the owned value.
Definition Value.h:38
std::vector< Value > Array
Definition Value.h:33
static AgentDevelopmentSession & instance()
Return the process-lifetime session authority.
HSQUIRRELVM vm() const
Definition Debugger.hpp:96
void stepFrames(int count)
Run count game frames then pause. Each frame is consumed by shouldRunUpdate / notifyFrameDone on the ...
Definition Debugger.cpp:587
bool isPaused() const
Definition Debugger.hpp:133
void pause(PauseReason reason=PauseReason::PauseKey)
Frame-level pause without a script site (PauseKey clears pauseLocation). For Exception / Snapshot,...
Definition Debugger.cpp:553
static Debugger & instance()
Definition Debugger.cpp:387
Injected runtime used by Play Host. Tests supply a fake; MCP uses the engine adapter....
Definition PlayHost.h:25
const std::string & gameRoot() const
Definition McpServer.hpp:67
static McpServer & instance()
void begin(std::string contractId, std::string contractHash, std::int64_t seed, std::string startCheckpoint)
Begins .
static PlayTraceBuffer & instance()
Instance.
bool isRecording() const
True when recording.
Definition PlayTrace.h:74
void append(const Value &request, const Value &response, std::uint64_t hostFrame)
Append.
bool isReplaying() const
True while replayPlayTrace is executing.
Definition PlayTrace.h:66
Value exportTrace() const
Export trace.
static Snapshot & instance()
Definition Snapshot.cpp:468
SQInteger top
Definition Snapshot.cpp:115
const Value * field(const Value &value, const char *key)
Borrow an optional object field.
Value stringArray(const std::vector< std::string > &values)
const ClimbingActionDefinition * findAction(const ClimbingProfile &profile, std::string_view id)
Optional action. @borrowed From profile; lifetime ends when the caller-owned profile changes or is de...
std::variant< std::monostate, std::int64_t, double, std::string, bool > Value
Definition Database.h:27
std::vector< std::string > readConfiguredModules(HSQUIRRELVM vm)
Read config.modules / optionalModules from the attached VM root.
Result< std::string > executePlayJson(std::string_view requestJson)
Parse, execute and serialize one Play JSON request against the live engine.
Definition PlayHost.cpp:898
Result< Value > buildGameWorldSnapshot(const GameWorldSnapshotInput &input)
Assemble runtime world brief plus live system lists.
std::string readConfigTitle(HSQUIRRELVM vm)
Read config.title from the attached VM root.
Result< Value > replayPlayTrace(const Value &recording, IPlayHostRuntime &runtime)
Replay a parsed recording against a host runtime.
std::vector< std::string > readLiveModules(HSQUIRRELVM vm)
List instantiated module slots declared in eve.moduleList.
Result< std::string > playObservationDigest(const Value &state)
Canonical digest of a Play observation state object.
Definition PlayTrace.cpp:57
Result< Value > executePlayRequest(const Value &request, IPlayHostRuntime &runtime)
Execute one versioned Play request against an injected runtime.
Definition PlayHost.cpp:890
std::string formatScriptError(const ScriptErrorContext &ctx)
Formats a context into a human-readable multi-line report.
ScriptErrorContext takeLastScriptError(HSQUIRRELVM vm)
Consumes and clears the last recorded error for a VM.
ScriptErrorContext captureCompileError(HSQUIRRELVM vm)
Captures the last compilation error recorded by the VM.
Result< Value > valueFromSquirrel(HSQUIRRELVM vm, SQInteger index, const SquirrelValueOptions &options)
Convert one Squirrel value into the canonical owning Value tree.
Result< Value > executeGameplayControlRequest(const Value &request)
Routes one versioned owning request to the uniquely matching gameplay provider.
glm::uvec4 info