@chrrxs/robloxstudio-mcp-inspector 3.2.1 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -396,8 +396,14 @@ local function release(data)
396
396
  chunkBytes = CHUNK_BYTES,
397
397
  }
398
398
  end
399
+ -- ttlSeconds bounds how long the transfer may hold its slot. The broker passes
400
+ -- the request's remaining budget: once the server stopped waiting, nobody will
401
+ -- read the pixels, so the slot must not stay reserved for the full TTL.
399
402
  local validSize
400
- local function begin(data, capture)
403
+ local function begin(data, capture, ttlSeconds)
404
+ if ttlSeconds == nil then
405
+ ttlSeconds = TRANSFER_TTL_SECONDS
406
+ end
401
407
  prune()
402
408
  local id = data.transferId
403
409
  -- An older server cannot consume chunk descriptors. Let it use legacy
@@ -422,15 +428,20 @@ local function begin(data, capture)
422
428
  end
423
429
  -- ▲ ReadonlyMap.size ▲
424
430
  if _size >= MAX_TRANSFERS then
425
- return fail("two captures are already in flight; release or await them first")
431
+ local soonest = math.huge
432
+ for _, held in transfers do
433
+ soonest = math.min(soonest, held.expiresAt - os.clock())
434
+ end
435
+ return fail(`two earlier captures still hold this client's transfer slots; the first frees itself in {string.format("%.1f", math.max(0, soonest))} s, when its request deadline has passed. Retry after that.`)
426
436
  end
437
+ local ttl = math.clamp(ttlSeconds, 1, TRANSFER_TTL_SECONDS)
427
438
  local transfer = {
428
439
  offset = 0,
429
- expiresAt = os.clock() + TRANSFER_TTL_SECONDS,
440
+ expiresAt = os.clock() + ttl,
430
441
  }
431
442
  transfers[id] = transfer
432
443
  -- Capture only the ID, not the large payload, in the expiry closure.
433
- transfer.expiryThread = task.delay(TRANSFER_TTL_SECONDS, function()
444
+ transfer.expiryThread = task.delay(ttl, function()
434
445
  local current = transfers[id]
435
446
  if current ~= nil and os.clock() >= current.expiresAt then
436
447
  current.expiryThread = nil
@@ -670,8 +681,23 @@ local CLIENT_IDENTITY_KIND = "identity"
670
681
  -- A normal capture needs at most 15s sampling + 5s waiting for profiler data.
671
682
  -- Leave room for processing, then return a diagnostic before the outer 30s wait.
672
683
  local CLIENT_PROFILER_MAX_WAIT_SECONDS = 25
673
- local CLIENT_PROFILER_RESPONSE_RESERVE_SECONDS = 5
674
- local CLIENT_PROFILER_POLL_SECONDS = 0.05
684
+ -- Every forwarded request ends its local wait this long before the MCP
685
+ -- deadline, so the caller receives the broker's diagnosis instead of a bare
686
+ -- "executing; unknown" timeout from the server.
687
+ local CLIENT_RESPONSE_RESERVE_SECONDS = 5
688
+ local CLIENT_WAIT_POLL_SECONDS = 0.05
689
+ -- Client Peers send a heartbeat over this RemoteEvent every second, and the
690
+ -- server pings them back. Both use the same server-client connection as
691
+ -- InvokeClient, so they show whether the bridge channel is delivering,
692
+ -- separately from whether the game itself is running.
693
+ local HEARTBEAT_NAME = "__MCPClientBrokerHeartbeat"
694
+ local HEARTBEAT_INTERVAL_SECONDS = 1
695
+ -- Ten missed heartbeats, or a channel delay of ten seconds, marks the bridge as
696
+ -- stalled. While it is stalled and an earlier request went unanswered, new
697
+ -- requests are refused before sending (see unresponsiveBridge).
698
+ local BRIDGE_STALE_SECONDS = 10
699
+ local MAX_REPORTED_CLIENT_REQUESTS = 8
700
+ local CLIENT_REQUEST_REPORT_SECONDS = 60
675
701
  -- Endpoints the server-peer broker is allowed to forward to the client peer.
676
702
  -- Each requires the client peer's plugin VM (because the buffer / require
677
703
  -- cache / etc. lives there) so the server peer alone can't satisfy them.
@@ -835,121 +861,267 @@ local function sendClientIdentity(rf, attempt)
835
861
  end
836
862
  task.delay(proxyRetryDelay(attempt + 1), sendClientIdentity, rf, attempt + 1)
837
863
  end
838
- local function setupClientBroker(attempt)
864
+ local function routeClientRequest(payload)
865
+ if payload.endpoint == "/api/get-runtime-logs" then
866
+ return handleGetRuntimeLogs(payload.data)
867
+ end
868
+ if payload.endpoint == "/api/get-memory-breakdown" then
869
+ return MemoryHandlers.getMemoryBreakdown(payload.data or {})
870
+ end
871
+ if payload.endpoint == "/api/get-scene-analysis" then
872
+ return SceneAnalysisHandlers.getSceneAnalysis(payload.data or {})
873
+ end
874
+ if payload.endpoint == "/api/breakpoints" then
875
+ return BreakpointHandlers.breakpoints(payload.data or {})
876
+ end
877
+ if payload.endpoint == "/api/capture-script-profiler" then
878
+ return ScriptProfilerHandlers.captureScriptProfiler(payload.data or {})
879
+ end
880
+ if payload.endpoint == "/api/capture-micro-profiler" then
881
+ return MicroProfilerHandlers.captureMicroProfiler(payload.data or {})
882
+ end
883
+ if payload.endpoint == "/api/multiplayer-test-state" then
884
+ return handleMultiplayerTestState()
885
+ end
886
+ if payload.endpoint == "/api/multiplayer-test-leave-client" then
887
+ return handleMultiplayerTestLeaveClient()
888
+ end
889
+ if payload.endpoint == "/api/capture-begin" then
890
+ return CaptureHandlers.captureBegin()
891
+ end
892
+ if payload.endpoint == "/api/capture-studio" then
893
+ -- Every chunk read shares this request's deadline, so after it nobody
894
+ -- reads the pixels and the transfer slot can be freed.
895
+ local _expiresAtServerTime = payload.expiresAtServerTime
896
+ local ttl = if type(_expiresAtServerTime) == "number" then payload.expiresAtServerTime - Workspace:GetServerTimeNow() + 1 else nil
897
+ return CaptureTransfer.begin(payload.data or {}, function()
898
+ return CaptureHandlers.captureStudio(payload.data or {})
899
+ end, ttl)
900
+ end
901
+ if payload.endpoint == "/api/capture-markers" then
902
+ return CaptureHandlers.captureMarkers(payload.data or {})
903
+ end
904
+ if payload.endpoint == CaptureTransfer.READ_ENDPOINT then
905
+ return CaptureTransfer.read(payload.data or {})
906
+ end
907
+ if payload.endpoint == CaptureTransfer.RELEASE_ENDPOINT then
908
+ return CaptureTransfer.release(payload.data or {})
909
+ end
910
+ if payload.endpoint == "/api/simulate-mouse-input" then
911
+ return InputHandlers.simulateMouseInput(payload.data or {})
912
+ end
913
+ if payload.endpoint == "/api/simulate-keyboard-input" then
914
+ return InputHandlers.simulateKeyboardInput(payload.data or {})
915
+ end
916
+ if payload.endpoint == "/api/focus-viewport" then
917
+ return MetadataHandlers.focusViewport(payload.data or {})
918
+ end
919
+ if payload.endpoint == "/api/execute-luau" then
920
+ return handleExecuteLuau(payload.data)
921
+ end
922
+ if payload.endpoint == "/api/eval-runtime" then
923
+ return EvalRuntimeHandlers.evalRuntime(payload.data or {})
924
+ end
925
+ return {
926
+ error = `Unsupported client broker endpoint: {payload.endpoint}`,
927
+ }
928
+ end
929
+ -- Requests this client received recently, reported in heartbeats so the server
930
+ -- can tell "never arrived" from "still running" when a request times out.
931
+ local clientRequests = {}
932
+ local lastServerPing
933
+ local clientHeartbeatStarted = false
934
+ local function pruneClientRequests(now)
935
+ for requestId, observation in clientRequests do
936
+ if observation.finishedAt ~= nil and now - observation.finishedAt > CLIENT_REQUEST_REPORT_SECONDS then
937
+ clientRequests[requestId] = nil
938
+ end
939
+ end
940
+ end
941
+ local function reportedClientRequests(now)
942
+ pruneClientRequests(now)
943
+ local reported = {}
944
+ for _, observation in clientRequests do
945
+ table.insert(reported, observation)
946
+ end
947
+ -- Running requests first, then the most recently started.
948
+ table.sort(reported, function(a, b)
949
+ if (a.finishedAt == nil) ~= (b.finishedAt == nil) then
950
+ return a.finishedAt == nil
951
+ end
952
+ return a.startedAt > b.startedAt
953
+ end)
954
+ local limited = {}
955
+ do
956
+ local i = 0
957
+ local _shouldIncrement = false
958
+ while true do
959
+ if _shouldIncrement then
960
+ i += 1
961
+ else
962
+ _shouldIncrement = true
963
+ end
964
+ if not (i < math.min(#reported, MAX_REPORTED_CLIENT_REQUESTS)) then
965
+ break
966
+ end
967
+ local _arg0 = reported[i + 1]
968
+ table.insert(limited, _arg0)
969
+ end
970
+ end
971
+ return limited
972
+ end
973
+ local function handleClientInvoke(payload)
974
+ local _condition = not payload
975
+ if not _condition then
976
+ local _endpoint = payload.endpoint
977
+ _condition = not (type(_endpoint) == "string")
978
+ end
979
+ if _condition then
980
+ return {
981
+ error = "Client broker request is missing its endpoint.",
982
+ }
983
+ end
984
+ -- os.clock is VM-local. Only the engine-synchronized server clock can
985
+ -- reject an envelope that expired while travelling to this client. The
986
+ -- server already reported a timeout for it, so running it now would apply
987
+ -- a change the caller was told had an unknown outcome, long after the fact.
988
+ local now = Workspace:GetServerTimeNow()
989
+ local _remainingMs = payload.remainingMs
990
+ local _condition_1 = type(_remainingMs) == "number"
991
+ if _condition_1 then
992
+ _condition_1 = payload.remainingMs <= 0
993
+ end
994
+ local _condition_2 = _condition_1
995
+ if not _condition_2 then
996
+ local _expiresAtServerTime = payload.expiresAtServerTime
997
+ local _condition_3 = type(_expiresAtServerTime) == "number"
998
+ if _condition_3 then
999
+ _condition_3 = now >= payload.expiresAtServerTime
1000
+ end
1001
+ _condition_2 = _condition_3
1002
+ end
1003
+ if _condition_2 then
1004
+ local _expiresAtServerTime = payload.expiresAtServerTime
1005
+ local lateMs = if type(_expiresAtServerTime) == "number" then math.floor(math.max(0, now - payload.expiresAtServerTime) * 1000) else 0
1006
+ return {
1007
+ success = false,
1008
+ error = "client_broker_expired",
1009
+ stage = "client_broker_pre_start",
1010
+ requestId = payload.requestId,
1011
+ executionOutcome = "not_executed",
1012
+ lateMs = lateMs,
1013
+ message = `Request {tostring(payload.requestId)} ({payload.endpoint}) reached the client {lateMs} ms after its deadline, so it was not started.`,
1014
+ }
1015
+ end
1016
+ local _requestId = payload.requestId
1017
+ local requestId = if type(_requestId) == "string" then payload.requestId else nil
1018
+ local observation
1019
+ if requestId ~= nil then
1020
+ observation = {
1021
+ requestId = requestId,
1022
+ endpoint = payload.endpoint,
1023
+ startedAt = now,
1024
+ }
1025
+ local _observation = observation
1026
+ clientRequests[requestId] = _observation
1027
+ end
1028
+ local ok, result = pcall(function()
1029
+ return routeClientRequest(payload)
1030
+ end)
1031
+ if observation ~= nil then
1032
+ observation.finishedAt = Workspace:GetServerTimeNow()
1033
+ end
1034
+ -- Keep the engine's error propagation: InvokeClient raises on the server.
1035
+ if not ok then
1036
+ error(result, 0)
1037
+ end
1038
+ return result
1039
+ end
1040
+ local function startClientHeartbeat(attempt)
839
1041
  if attempt == nil then
840
1042
  attempt = 0
841
1043
  end
842
- if PeerRole.detect() ~= "client" then
1044
+ if clientHeartbeatStarted or PeerRole.detect() ~= "client" or not RunService:IsRunning() then
843
1045
  return nil
844
1046
  end
845
- local rf = ReplicatedStorage:WaitForChild(BROKER_NAME, 10)
846
- if not rf or not rf:IsA("RemoteFunction") then
847
- if attempt == 0 then
848
- warn(`[robloxstudio-mcp] client: {BROKER_NAME} not found; retrying`)
849
- end
850
- if RunService:IsRunning() then
851
- task.delay(proxyRetryDelay(attempt + 1), setupClientBroker, attempt + 1)
1047
+ local event = ReplicatedStorage:WaitForChild(HEARTBEAT_NAME, 10)
1048
+ if not event or not event:IsA("RemoteEvent") then
1049
+ -- An older server broker has no heartbeat channel; requests still work.
1050
+ if RunService:IsRunning() and attempt < 5 then
1051
+ task.delay(proxyRetryDelay(attempt + 1), startClientHeartbeat, attempt + 1)
852
1052
  end
853
1053
  return nil
854
1054
  end
855
- rf.OnClientInvoke = function(payload)
856
- local _condition = not payload
1055
+ clientHeartbeatStarted = true
1056
+ event.OnClientEvent:Connect(function(payload)
1057
+ local _payload = payload
1058
+ if not (type(_payload) == "table") then
1059
+ return nil
1060
+ end
1061
+ local ping = payload
1062
+ local _condition = ping.kind ~= "ping"
857
1063
  if not _condition then
858
- local _endpoint = payload.endpoint
859
- _condition = not (type(_endpoint) == "string")
1064
+ local _sentAt = ping.sentAt
1065
+ _condition = not (type(_sentAt) == "number")
860
1066
  end
861
1067
  if _condition then
862
- return {
863
- error = "Client broker request is missing its endpoint.",
864
- }
865
- end
866
- if payload and payload.endpoint == "/api/get-runtime-logs" then
867
- return handleGetRuntimeLogs(payload.data)
868
- end
869
- if payload and payload.endpoint == "/api/get-memory-breakdown" then
870
- return MemoryHandlers.getMemoryBreakdown(payload.data or {})
871
- end
872
- if payload and payload.endpoint == "/api/get-scene-analysis" then
873
- return SceneAnalysisHandlers.getSceneAnalysis(payload.data or {})
874
- end
875
- if payload and payload.endpoint == "/api/breakpoints" then
876
- return BreakpointHandlers.breakpoints(payload.data or {})
1068
+ return nil
877
1069
  end
878
- if payload and payload.endpoint == "/api/capture-script-profiler" then
879
- -- os.clock is VM-local. Only the engine-synchronized server clock can
880
- -- reject an envelope that expired while travelling to this client.
881
- local _remainingMs = payload.remainingMs
882
- local _condition_1 = type(_remainingMs) == "number"
883
- if _condition_1 then
884
- _condition_1 = payload.remainingMs <= 0
885
- end
886
- local _condition_2 = _condition_1
887
- if not _condition_2 then
888
- local _expiresAtServerTime = payload.expiresAtServerTime
889
- local _condition_3 = type(_expiresAtServerTime) == "number"
890
- if _condition_3 then
891
- _condition_3 = Workspace:GetServerTimeNow() >= payload.expiresAtServerTime
892
- end
893
- _condition_2 = _condition_3
894
- end
895
- if _condition_2 then
896
- return {
897
- success = false,
898
- error = "client_broker_expired",
899
- stage = "client_broker_pre_start",
900
- requestId = payload.requestId,
901
- executionOutcome = "not_executed",
902
- message = "Client profiler request expired before capture started.",
1070
+ lastServerPing = {
1071
+ sentAt = ping.sentAt,
1072
+ receivedAt = Workspace:GetServerTimeNow(),
1073
+ }
1074
+ end)
1075
+ task.spawn(function()
1076
+ while event.Parent ~= nil and RunService:IsRunning() do
1077
+ -- One failed beat must not end the loop: silence means "stalled".
1078
+ pcall(function()
1079
+ local now = Workspace:GetServerTimeNow()
1080
+ local _object = {
1081
+ kind = "heartbeat",
1082
+ sentAt = now,
903
1083
  }
904
- end
905
- return ScriptProfilerHandlers.captureScriptProfiler(payload.data or {})
906
- end
907
- if payload and payload.endpoint == "/api/capture-micro-profiler" then
908
- return MicroProfilerHandlers.captureMicroProfiler(payload.data or {})
909
- end
910
- if payload and payload.endpoint == "/api/multiplayer-test-state" then
911
- return handleMultiplayerTestState()
912
- end
913
- if payload and payload.endpoint == "/api/multiplayer-test-leave-client" then
914
- return handleMultiplayerTestLeaveClient()
915
- end
916
- if payload and payload.endpoint == "/api/capture-begin" then
917
- return CaptureHandlers.captureBegin()
918
- end
919
- if payload and payload.endpoint == "/api/capture-studio" then
920
- return CaptureTransfer.begin(payload.data or {}, function()
921
- return CaptureHandlers.captureStudio(payload.data or {})
1084
+ local _left = "pingSentAt"
1085
+ local _result = lastServerPing
1086
+ if _result ~= nil then
1087
+ _result = _result.sentAt
1088
+ end
1089
+ _object[_left] = _result
1090
+ local _left_1 = "pingReceivedAt"
1091
+ local _result_1 = lastServerPing
1092
+ if _result_1 ~= nil then
1093
+ _result_1 = _result_1.receivedAt
1094
+ end
1095
+ _object[_left_1] = _result_1
1096
+ _object.requests = reportedClientRequests(now)
1097
+ local heartbeat = _object
1098
+ event:FireServer(heartbeat)
922
1099
  end)
1100
+ task.wait(HEARTBEAT_INTERVAL_SECONDS)
923
1101
  end
924
- if payload and payload.endpoint == "/api/capture-markers" then
925
- return CaptureHandlers.captureMarkers(payload.data or {})
926
- end
927
- if payload and payload.endpoint == CaptureTransfer.READ_ENDPOINT then
928
- return CaptureTransfer.read(payload.data or {})
929
- end
930
- if payload and payload.endpoint == CaptureTransfer.RELEASE_ENDPOINT then
931
- return CaptureTransfer.release(payload.data or {})
932
- end
933
- if payload and payload.endpoint == "/api/simulate-mouse-input" then
934
- return InputHandlers.simulateMouseInput(payload.data or {})
935
- end
936
- if payload and payload.endpoint == "/api/simulate-keyboard-input" then
937
- return InputHandlers.simulateKeyboardInput(payload.data or {})
938
- end
939
- if payload and payload.endpoint == "/api/focus-viewport" then
940
- return MetadataHandlers.focusViewport(payload.data or {})
941
- end
942
- if payload and payload.endpoint == "/api/execute-luau" then
943
- return handleExecuteLuau(payload.data)
1102
+ clientHeartbeatStarted = false
1103
+ end)
1104
+ end
1105
+ local function setupClientBroker(attempt)
1106
+ if attempt == nil then
1107
+ attempt = 0
1108
+ end
1109
+ if PeerRole.detect() ~= "client" then
1110
+ return nil
1111
+ end
1112
+ local rf = ReplicatedStorage:WaitForChild(BROKER_NAME, 10)
1113
+ if not rf or not rf:IsA("RemoteFunction") then
1114
+ if attempt == 0 then
1115
+ warn(`[robloxstudio-mcp] client: {BROKER_NAME} not found; retrying`)
944
1116
  end
945
- if payload and payload.endpoint == "/api/eval-runtime" then
946
- return EvalRuntimeHandlers.evalRuntime(payload.data or {})
1117
+ if RunService:IsRunning() then
1118
+ task.delay(proxyRetryDelay(attempt + 1), setupClientBroker, attempt + 1)
947
1119
  end
948
- return {
949
- error = `Unsupported client broker endpoint: {payload.endpoint}`,
950
- }
1120
+ return nil
951
1121
  end
1122
+ rf.OnClientInvoke = handleClientInvoke
952
1123
  task.spawn(sendClientIdentity, rf, 0)
1124
+ task.spawn(startClientHeartbeat, 0)
953
1125
  end
954
1126
  local INITIAL_PROXY_RETRY_DELAY_SECONDS = 0.5
955
1127
  local MAX_PROXY_RETRY_DELAY_SECONDS = 5
@@ -1202,32 +1374,211 @@ local function refreshAllProxyRegistrations()
1202
1374
  task.spawn(registerProxyEntry, entry)
1203
1375
  end
1204
1376
  end
1205
- local function invokeClientProfiler(entry, target, data, context)
1377
+ local function msBetween(later, earlier)
1378
+ return math.floor(math.max(0, later - earlier) * 1000)
1379
+ end
1380
+ local function seconds(ms)
1381
+ return string.format("%.1f s", ms / 1000)
1382
+ end
1383
+ -- Everything here is measured with Workspace:GetServerTimeNow, which the engine
1384
+ -- keeps synchronized between the server and its clients.
1385
+ local function bridgeHealth(entry, requestId, dispatchedAt)
1386
+ local heartbeat = entry.heartbeat
1387
+ if heartbeat == nil then
1388
+ return {}
1389
+ end
1390
+ local now = Workspace:GetServerTimeNow()
1391
+ local health = {
1392
+ heartbeatAgeMs = msBetween(now, heartbeat.receivedAt),
1393
+ clientToServerDelayMs = msBetween(heartbeat.receivedAt, heartbeat.sentAt),
1394
+ }
1395
+ -- Pings leave every second, so the newest ping the client had seen is at most
1396
+ -- about a second old on a healthy channel. Its age measures server->client delay.
1397
+ if heartbeat.pingSentAt ~= nil then
1398
+ health.serverToClientDelayMs = msBetween(heartbeat.sentAt, heartbeat.pingSentAt)
1399
+ elseif entry.firstPingSentAt ~= nil and heartbeat.sentAt > entry.firstPingSentAt then
1400
+ health.serverToClientDelayMs = msBetween(heartbeat.sentAt, entry.firstPingSentAt)
1401
+ end
1402
+ if requestId ~= nil then
1403
+ local _exp = heartbeat.requests
1404
+ -- ▼ ReadonlyArray.find ▼
1405
+ local _callback = function(request)
1406
+ return request.requestId == requestId
1407
+ end
1408
+ local _result
1409
+ for _i, _v in _exp do
1410
+ if _callback(_v, _i - 1, _exp) == true then
1411
+ _result = _v
1412
+ break
1413
+ end
1414
+ end
1415
+ -- ▲ ReadonlyArray.find ▲
1416
+ local observed = _result
1417
+ if observed ~= nil then
1418
+ if observed.finishedAt == nil then
1419
+ health.requestState = "running"
1420
+ health.requestRunningMs = msBetween(now, observed.startedAt)
1421
+ else
1422
+ health.requestState = "completed"
1423
+ health.requestRunningMs = msBetween(observed.finishedAt, observed.startedAt)
1424
+ end
1425
+ elseif dispatchedAt ~= nil and heartbeat.pingSentAt ~= nil and heartbeat.pingSentAt > dispatchedAt and #heartbeat.requests < MAX_REPORTED_CLIENT_REQUESTS then
1426
+ health.requestState = "not_started"
1427
+ elseif dispatchedAt ~= nil and heartbeat.sentAt > dispatchedAt then
1428
+ health.requestState = "not_received"
1429
+ end
1430
+ end
1431
+ return health
1432
+ end
1433
+ local BACKLOG_EXPLANATION = "Requests to a client share the server-client connection with the game's replication and remote traffic, " .. "so a backlog there delays them while the game itself keeps running."
1434
+ local function describeBridgeHealth(health)
1435
+ if health.heartbeatAgeMs == nil then
1436
+ return "No heartbeat has arrived from this client's MCP bridge, so its liveness is unknown."
1437
+ end
1438
+ local _exp = seconds(health.heartbeatAgeMs)
1439
+ local _condition = health.clientToServerDelayMs
1440
+ if _condition == nil then
1441
+ _condition = 0
1442
+ end
1443
+ local channel = `Bridge heartbeat {_exp} ago; client->server delay {seconds(_condition)}` .. (if health.serverToClientDelayMs ~= nil then `; server->client delay {seconds(health.serverToClientDelayMs)}.` else ".")
1444
+ if health.heartbeatAgeMs > BRIDGE_STALE_SECONDS * 1000 then
1445
+ return `{channel} The client's MCP bridge has stopped sending heartbeats: either the client's Luau scheduler is blocked by a long-running script, or client->server messages are stalled. The game window can keep rendering in both cases.`
1446
+ end
1447
+ if health.requestState == "running" then
1448
+ local _condition_1 = health.requestRunningMs
1449
+ if _condition_1 == nil then
1450
+ _condition_1 = 0
1451
+ end
1452
+ return `{channel} The client received this request and its handler has been running for {seconds(_condition_1)}: the code is yielding or blocked inside the client.`
1453
+ end
1454
+ if health.requestState == "completed" then
1455
+ return `{channel} The client finished this request but its response has not arrived: client->server traffic is backlogged. {BACKLOG_EXPLANATION}`
1456
+ end
1457
+ if health.requestState == "not_started" then
1458
+ return `{channel} The client has received server messages sent after this request but has not started it: the client broker never ran it, or it is still queued inside the client.`
1459
+ end
1460
+ local _condition_1 = health.serverToClientDelayMs
1461
+ if _condition_1 == nil then
1462
+ _condition_1 = 0
1463
+ end
1464
+ local _condition_2 = _condition_1 > BRIDGE_STALE_SECONDS * 1000
1465
+ if not _condition_2 then
1466
+ _condition_2 = health.requestState == "not_received"
1467
+ end
1468
+ if _condition_2 then
1469
+ return `{channel} The request has not reached the client: server->client traffic is backlogged. {BACKLOG_EXPLANATION}`
1470
+ end
1471
+ local _condition_3 = health.clientToServerDelayMs
1472
+ if _condition_3 == nil then
1473
+ _condition_3 = 0
1474
+ end
1475
+ if _condition_3 > BRIDGE_STALE_SECONDS * 1000 then
1476
+ return `{channel} Client->server traffic is backlogged. {BACKLOG_EXPLANATION}`
1477
+ end
1478
+ return channel
1479
+ end
1480
+ -- A request sent into a stalled channel only waits out its deadline, and may
1481
+ -- then run on the client long after the caller gave up on it. Heartbeats alone
1482
+ -- are not enough to refuse: a request to this client must also have timed out
1483
+ -- with no answer since, so a broken heartbeat can never block a working channel.
1484
+ local function unresponsiveBridge(entry)
1485
+ if entry.lastTimeoutAt == nil then
1486
+ return nil
1487
+ end
1488
+ if entry.lastAnswerAt ~= nil and entry.lastAnswerAt > entry.lastTimeoutAt then
1489
+ return nil
1490
+ end
1491
+ local health = bridgeHealth(entry)
1492
+ if health.heartbeatAgeMs == nil then
1493
+ return nil
1494
+ end
1495
+ local staleMs = BRIDGE_STALE_SECONDS * 1000
1496
+ local _condition = health.heartbeatAgeMs > staleMs
1497
+ if not _condition then
1498
+ local _condition_1 = health.clientToServerDelayMs
1499
+ if _condition_1 == nil then
1500
+ _condition_1 = 0
1501
+ end
1502
+ _condition = _condition_1 > staleMs
1503
+ if not _condition then
1504
+ local _condition_2 = health.serverToClientDelayMs
1505
+ if _condition_2 == nil then
1506
+ _condition_2 = 0
1507
+ end
1508
+ _condition = _condition_2 > staleMs
1509
+ end
1510
+ end
1511
+ if _condition then
1512
+ return health
1513
+ end
1514
+ return nil
1515
+ end
1516
+ local function callFailure(call, code, stage, outcome, detail, health)
1517
+ call.context.executionOutcome = outcome
1518
+ local healthText = if health ~= nil then ` {describeBridgeHealth(health)}` else ""
1519
+ return {
1520
+ success = false,
1521
+ error = code,
1522
+ stage = stage,
1523
+ requestId = call.context.requestId,
1524
+ peerId = call.entry.peerId,
1525
+ target = call.target,
1526
+ endpoint = call.endpoint,
1527
+ elapsedMs = math.floor(math.max(0, os.clock() - call.startedAt) * 1000),
1528
+ executionOutcome = outcome,
1529
+ bridge = health,
1530
+ message = if outcome == "unknown" then `{detail}{healthText} Only the broker's local wait ended: a request that already started on the client is not cancelled or rolled back, and one still in transit is refused by the client once its deadline has passed. No retry was started.` else `{detail}{healthText} The request was not sent to the client.`,
1531
+ }
1532
+ end
1533
+ local function beginClientCall(entry, target, endpoint, context, maxWaitSeconds, reserveSeconds)
1206
1534
  local startedAt = os.clock()
1207
- local deadlineAt = math.min(context.deadlineAt - CLIENT_PROFILER_RESPONSE_RESERVE_SECONDS, startedAt + CLIENT_PROFILER_MAX_WAIT_SECONDS)
1208
- local failure = function(code, stage, outcome, detail)
1209
- context.executionOutcome = outcome
1210
- return {
1211
- success = false,
1212
- error = code,
1213
- stage = stage,
1214
- requestId = context.requestId,
1215
- peerId = entry.peerId,
1216
- target = target,
1217
- elapsedMs = math.floor(math.max(0, os.clock() - startedAt) * 1000),
1218
- executionOutcome = outcome,
1219
- message = if outcome == "unknown" then `{detail} Only the broker's local wait ended; remote execution may still be running. No retry was started.` else `{detail} Client profiler execution was not started.`,
1220
- }
1535
+ local remaining = context.deadlineAt - startedAt
1536
+ -- Short budgets (runtime log fan-out uses 5 s) keep most of their time.
1537
+ local _condition = reserveSeconds
1538
+ if _condition == nil then
1539
+ _condition = math.clamp(remaining * 0.2, 0.25, CLIENT_RESPONSE_RESERVE_SECONDS)
1221
1540
  end
1222
- if context.isCancelled() then
1223
- return failure("client_broker_cancelled", "client_broker_admission", "not_executed", "Request cancelled before client invocation.")
1541
+ local reserve = _condition
1542
+ local deadlineAt = context.deadlineAt - reserve
1543
+ if maxWaitSeconds ~= nil then
1544
+ deadlineAt = math.min(deadlineAt, startedAt + maxWaitSeconds)
1224
1545
  end
1225
- if startedAt >= deadlineAt then
1226
- return failure("client_broker_timeout", "client_broker_admission", "not_executed", "Insufficient request budget for client invocation and response delivery.")
1546
+ return {
1547
+ entry = entry,
1548
+ target = target,
1549
+ endpoint = endpoint,
1550
+ context = context,
1551
+ startedAt = startedAt,
1552
+ deadlineAt = deadlineAt,
1553
+ }
1554
+ end
1555
+ local function admitClientCall(call)
1556
+ if call.context.isCancelled() then
1557
+ return callFailure(call, "client_broker_cancelled", "client_broker_admission", "not_executed", "Request cancelled before client invocation.")
1558
+ end
1559
+ if call.startedAt >= call.deadlineAt then
1560
+ return callFailure(call, "client_broker_timeout", "client_broker_admission", "not_executed", "Insufficient request budget for client invocation and response delivery.")
1227
1561
  end
1562
+ local unresponsive = unresponsiveBridge(call.entry)
1563
+ if unresponsive ~= nil then
1564
+ return callFailure(call, "client_bridge_unresponsive", "client_broker_admission", "not_executed", `The MCP bridge to {call.target} is unresponsive, so {call.endpoint} was refused instead of waiting for its deadline. This is the plugin's server-to-client channel, not necessarily the game.`, unresponsive)
1565
+ end
1566
+ return nil
1567
+ end
1568
+ -- InvokeClient yields until the client answers, forever if it never does. Run it
1569
+ -- on its own thread and stop waiting at the call's deadline. requestId names
1570
+ -- this one invocation in the client's heartbeat reports.
1571
+ local function invokeClient(call, endpoint, data, requestId)
1572
+ if requestId == nil then
1573
+ requestId = call.context.requestId
1574
+ end
1575
+ local _binding = call
1576
+ local entry = _binding.entry
1577
+ local context = _binding.context
1578
+ local dispatchedAt = Workspace:GetServerTimeNow()
1228
1579
  local interrupted = function()
1229
1580
  if context.isCancelled() then
1230
- return failure("client_broker_cancelled", "client_broker_wait", "unknown", "Request cancelled while awaiting the client profiler response.")
1581
+ return callFailure(call, "client_broker_cancelled", "client_broker_wait", "unknown", `Request cancelled while awaiting {call.target}'s response.`)
1231
1582
  end
1232
1583
  local _peerId = entry.peerId
1233
1584
  local _condition = proxyByPeerId[_peerId] ~= entry
@@ -1239,28 +1590,34 @@ local function invokeClientProfiler(entry, target, data, context)
1239
1590
  end
1240
1591
  end
1241
1592
  if _condition then
1242
- return failure("client_broker_disconnected", "client_broker_wait", "unknown", "Client proxy disconnected while awaiting the profiler response.")
1593
+ return callFailure(call, "client_broker_disconnected", "client_broker_wait", "unknown", `Client proxy {call.target} disconnected while awaiting its response.`)
1243
1594
  end
1244
- if os.clock() >= deadlineAt then
1245
- return failure("client_broker_timeout", "client_broker_wait", "unknown", "Client profiler round-trip exceeded its response deadline.")
1595
+ if os.clock() >= call.deadlineAt then
1596
+ entry.lastTimeoutAt = os.clock()
1597
+ return callFailure(call, "client_broker_timeout", "client_broker_wait", "unknown", `{call.target} did not answer {endpoint} within {seconds(msBetween(os.clock(), call.startedAt))}.`, bridgeHealth(entry, requestId, dispatchedAt))
1246
1598
  end
1247
1599
  return nil
1248
1600
  end
1249
- local remainingMs = math.max(0, math.floor((deadlineAt - os.clock()) * 1000))
1601
+ local remainingMs = math.max(0, math.floor((call.deadlineAt - os.clock()) * 1000))
1602
+ local expiresAtServerTime = Workspace:GetServerTimeNow() + remainingMs / 1000
1250
1603
  local envelope = {
1251
- endpoint = "/api/capture-script-profiler",
1604
+ endpoint = endpoint,
1252
1605
  data = data,
1253
- requestId = context.requestId,
1606
+ requestId = requestId,
1254
1607
  remainingMs = remainingMs,
1255
- expiresAtServerTime = Workspace:GetServerTimeNow() + remainingMs / 1000,
1608
+ expiresAtServerTime = expiresAtServerTime,
1256
1609
  }
1257
1610
  local settled = false
1258
- local response
1611
+ local outcome
1259
1612
  context.executionOutcome = "unknown"
1260
1613
  local invocation = task.spawn(function()
1261
1614
  local ok, result = pcall(function()
1262
1615
  return entry.remote:InvokeClient(entry.player, envelope)
1263
1616
  end)
1617
+ -- Even a late answer shows the channel delivers again.
1618
+ if ok then
1619
+ entry.lastAnswerAt = os.clock()
1620
+ end
1264
1621
  -- Cancelling a suspended engine wait is best effort. A late return must
1265
1622
  -- never replace the chosen outcome, even if task.cancel was unavailable.
1266
1623
  if settled then
@@ -1268,16 +1625,28 @@ local function invokeClientProfiler(entry, target, data, context)
1268
1625
  end
1269
1626
  local interruption = interrupted()
1270
1627
  if interruption ~= nil then
1271
- response = interruption
1628
+ outcome = {
1629
+ ok = false,
1630
+ failure = interruption,
1631
+ }
1272
1632
  elseif not ok then
1273
- response = failure("client_broker_invoke_failed", "client_broker_wait", "unknown", `InvokeClient failed: {tostring(result)}`)
1633
+ outcome = {
1634
+ ok = false,
1635
+ failure = callFailure(call, "client_broker_invoke_failed", "client_broker_wait", "unknown", `InvokeClient failed: {tostring(result)}`),
1636
+ }
1274
1637
  elseif result == nil then
1275
- response = failure("client_broker_nil_response", "client_broker_wait", "unknown", "Client profiler returned no response.")
1638
+ outcome = {
1639
+ ok = false,
1640
+ failure = callFailure(call, "client_broker_nil_response", "client_broker_wait", "unknown", `{call.target} returned no response.`),
1641
+ }
1276
1642
  else
1277
- response = result
1278
- -- Only this endpoint's broker pre-start refusal establishes that no
1279
- -- remote capture ran. Other responses retain normal handler outcome
1280
- -- classification; arbitrary payload fields cannot override transport.
1643
+ outcome = {
1644
+ ok = true,
1645
+ result = result,
1646
+ }
1647
+ -- Only the client's own pre-start refusal establishes that nothing ran.
1648
+ -- Other responses keep normal handler outcome classification;
1649
+ -- arbitrary payload fields cannot override the transport observation.
1281
1650
  context.executionOutcome = nil
1282
1651
  if type(result) == "table" then
1283
1652
  local reply = result
@@ -1291,18 +1660,60 @@ local function invokeClientProfiler(entry, target, data, context)
1291
1660
  while not settled do
1292
1661
  local interruption = interrupted()
1293
1662
  if interruption ~= nil then
1294
- response = interruption
1663
+ outcome = {
1664
+ ok = false,
1665
+ failure = interruption,
1666
+ }
1295
1667
  settled = true
1296
1668
  -- This only releases the local coroutine; it cannot stop the remote
1297
- -- OnClientInvoke callback or roll back an already-started capture.
1669
+ -- OnClientInvoke callback or roll back work that already started.
1298
1670
  pcall(function()
1299
1671
  return task.cancel(invocation)
1300
1672
  end)
1301
1673
  break
1302
1674
  end
1303
- task.wait(math.min(CLIENT_PROFILER_POLL_SECONDS, deadlineAt - os.clock()))
1675
+ task.wait(math.min(CLIENT_WAIT_POLL_SECONDS, call.deadlineAt - os.clock()))
1676
+ end
1677
+ return outcome
1678
+ end
1679
+ local function invokeClientOnce(entry, target, endpoint, data, context, maxWaitSeconds, reserveSeconds)
1680
+ local call = beginClientCall(entry, target, endpoint, context, maxWaitSeconds, reserveSeconds)
1681
+ local refused = admitClientCall(call)
1682
+ if refused ~= nil then
1683
+ return refused
1684
+ end
1685
+ local outcome = invokeClient(call, endpoint, data)
1686
+ return if outcome.ok then outcome.result else outcome.failure
1687
+ end
1688
+ -- Screenshot transfer is several invocations; they share one deadline, and the
1689
+ -- first broker failure ends the transfer with that failure's diagnosis.
1690
+ local function invokeClientCapture(entry, target, data, context)
1691
+ local call = beginClientCall(entry, target, "/api/capture-studio", context)
1692
+ local refused = admitClientCall(call)
1693
+ if refused ~= nil then
1694
+ return refused
1695
+ end
1696
+ local brokerFailure
1697
+ local outcome
1698
+ local invocations = 0
1699
+ local result = CaptureTransfer.receive(function(captureEndpoint, captureData)
1700
+ if brokerFailure ~= nil then
1701
+ error("client broker failed", 0)
1702
+ end
1703
+ invocations += 1
1704
+ local invoked = invokeClient(call, captureEndpoint, captureData, `{context.requestId}:{invocations}`)
1705
+ if not invoked.ok then
1706
+ brokerFailure = invoked.failure
1707
+ outcome = context.executionOutcome
1708
+ error("client broker failed", 0)
1709
+ end
1710
+ return invoked.result
1711
+ end, data or {})
1712
+ if brokerFailure ~= nil then
1713
+ context.executionOutcome = outcome
1714
+ return brokerFailure
1304
1715
  end
1305
- return response
1716
+ return result
1306
1717
  end
1307
1718
  local function dispatchClientRequest(peerId, target, endpoint, data, context)
1308
1719
  if endpoint == "/api/capture-script-profiler" then
@@ -1348,33 +1759,123 @@ local function dispatchClientRequest(peerId, target, endpoint, data, context)
1348
1759
  }
1349
1760
  end
1350
1761
  if endpoint == "/api/capture-script-profiler" then
1351
- return invokeClientProfiler(entry, target, data, context)
1762
+ return invokeClientOnce(entry, target, endpoint, data, context, CLIENT_PROFILER_MAX_WAIT_SECONDS, CLIENT_RESPONSE_RESERVE_SECONDS)
1352
1763
  end
1353
1764
  if endpoint == "/api/capture-studio" then
1354
- return CaptureTransfer.receive(function(captureEndpoint, captureData)
1355
- return entry.remote:InvokeClient(entry.player, {
1356
- endpoint = captureEndpoint,
1357
- data = captureData,
1358
- })
1359
- end, data or {})
1765
+ return invokeClientCapture(entry, target, data, context)
1360
1766
  end
1361
- local envelope = {
1362
- endpoint = endpoint,
1363
- data = data,
1767
+ return invokeClientOnce(entry, target, endpoint, data, context)
1768
+ end
1769
+ local function optionalNumber(value)
1770
+ local _value = value
1771
+ local _condition = type(_value) == "number"
1772
+ if _condition then
1773
+ _condition = value == value
1774
+ end
1775
+ return if _condition then value else nil
1776
+ end
1777
+ local function parseHeartbeat(payload)
1778
+ local _payload = payload
1779
+ if not (type(_payload) == "table") then
1780
+ return nil
1781
+ end
1782
+ local fields = payload
1783
+ local sentAt = optionalNumber(fields.sentAt)
1784
+ if fields.kind ~= "heartbeat" or sentAt == nil then
1785
+ return nil
1786
+ end
1787
+ local requests = {}
1788
+ local _requests = fields.requests
1789
+ if type(_requests) == "table" then
1790
+ for _, value in fields.requests do
1791
+ if #requests >= MAX_REPORTED_CLIENT_REQUESTS then
1792
+ break
1793
+ end
1794
+ if not (type(value) == "table") then
1795
+ continue
1796
+ end
1797
+ local request = value
1798
+ local startedAt = optionalNumber(request.startedAt)
1799
+ local _requestId = request.requestId
1800
+ local _condition = not (type(_requestId) == "string")
1801
+ if not _condition then
1802
+ _condition = #request.requestId > 384
1803
+ if not _condition then
1804
+ local _endpoint = request.endpoint
1805
+ _condition = not (type(_endpoint) == "string")
1806
+ if not _condition then
1807
+ _condition = #request.endpoint > 128 or startedAt == nil
1808
+ end
1809
+ end
1810
+ end
1811
+ if _condition then
1812
+ continue
1813
+ end
1814
+ local _arg0 = {
1815
+ requestId = request.requestId,
1816
+ endpoint = request.endpoint,
1817
+ startedAt = startedAt,
1818
+ finishedAt = optionalNumber(request.finishedAt),
1819
+ }
1820
+ table.insert(requests, _arg0)
1821
+ end
1822
+ end
1823
+ return {
1824
+ kind = "heartbeat",
1825
+ sentAt = sentAt,
1826
+ pingSentAt = optionalNumber(fields.pingSentAt),
1827
+ pingReceivedAt = optionalNumber(fields.pingReceivedAt),
1828
+ requests = requests,
1364
1829
  }
1365
- local invokeOk, invokeResult = pcall(function()
1366
- return entry.remote:InvokeClient(entry.player, envelope)
1830
+ end
1831
+ local function setupHeartbeatChannel()
1832
+ local existing = ReplicatedStorage:FindFirstChild(HEARTBEAT_NAME)
1833
+ if existing ~= nil and not existing:IsA("RemoteEvent") then
1834
+ warn(`[robloxstudio-mcp] server: {HEARTBEAT_NAME} exists but is not a RemoteEvent; client bridge liveness is unavailable`)
1835
+ return nil
1836
+ end
1837
+ local event = existing or Instance.new("RemoteEvent")
1838
+ event.Name = HEARTBEAT_NAME
1839
+ event.OnServerEvent:Connect(function(player, payload)
1840
+ local _player = player
1841
+ local entry = proxyByPlayer[_player]
1842
+ if entry == nil then
1843
+ return nil
1844
+ end
1845
+ local heartbeat = parseHeartbeat(payload)
1846
+ if heartbeat == nil then
1847
+ return nil
1848
+ end
1849
+ local _object = table.clone(heartbeat)
1850
+ setmetatable(_object, nil)
1851
+ _object.receivedAt = Workspace:GetServerTimeNow()
1852
+ entry.heartbeat = _object
1367
1853
  end)
1368
- if not invokeOk then
1369
- return {
1370
- success = false,
1371
- error = `InvokeClient failed: {tostring(invokeResult)}`,
1372
- }
1854
+ if event.Parent == nil then
1855
+ event.Parent = ReplicatedStorage
1373
1856
  end
1374
- return if invokeResult ~= nil then invokeResult else {
1375
- success = false,
1376
- error = "nil response",
1377
- }
1857
+ task.spawn(function()
1858
+ while event.Parent ~= nil and RunService:IsRunning() do
1859
+ local sentAt = Workspace:GetServerTimeNow()
1860
+ -- Only clients that have shown they listen get pings, so an older
1861
+ -- client never accumulates unhandled events.
1862
+ for player, entry in proxyByPlayer do
1863
+ if entry.heartbeat == nil then
1864
+ continue
1865
+ end
1866
+ if entry.firstPingSentAt == nil then
1867
+ entry.firstPingSentAt = sentAt
1868
+ end
1869
+ pcall(function()
1870
+ return event:FireClient(player, {
1871
+ kind = "ping",
1872
+ sentAt = sentAt,
1873
+ })
1874
+ end)
1875
+ end
1876
+ task.wait(HEARTBEAT_INTERVAL_SECONDS)
1877
+ end
1878
+ end)
1378
1879
  end
1379
1880
  local function setupServerBroker()
1380
1881
  if serverBrokerStarted then
@@ -1414,6 +1915,9 @@ local function setupServerBroker()
1414
1915
  success = true,
1415
1916
  }
1416
1917
  end
1918
+ -- Publish the heartbeat channel first, so a client that finds the broker
1919
+ -- also finds its liveness channel.
1920
+ setupHeartbeatChannel()
1417
1921
  if rf.Parent == nil then
1418
1922
  rf.Parent = ReplicatedStorage
1419
1923
  end
@@ -1471,6 +1975,7 @@ local ClientBroker = TS.import(script, script.Parent, "ClientBroker")
1471
1975
  local ServerUrlSettings = TS.import(script, script.Parent, "ServerUrlSettings")
1472
1976
  local PluginSession = TS.import(script, script.Parent, "PluginSession")
1473
1977
  local StudioWebSocket = TS.import(script, script.Parent, "StudioWebSocket")
1978
+ local PathGuard = TS.import(script, script.Parent, "PathGuard")
1474
1979
  local assignedRole
1475
1980
  local lastReadyPlaceKey
1476
1981
  local initialRole = PluginSession.getRole()
@@ -1523,12 +2028,17 @@ local routeMap = {
1523
2028
  ["/api/get-memory-breakdown"] = MemoryHandlers.getMemoryBreakdown,
1524
2029
  ["/api/get-scene-analysis"] = SceneAnalysisHandlers.getSceneAnalysis,
1525
2030
  }
2031
+ local pathGuard = PathGuard.createPathGuard(function(path)
2032
+ return Utils.resolveInstancePath(path).ambiguity
2033
+ end)
1526
2034
  local function processRequest(request, context)
1527
2035
  local endpoint = request.endpoint
1528
- local data = request.data or {}
2036
+ local data = (request.data or {})
1529
2037
  local handler = routeMap[endpoint]
1530
2038
  if handler then
1531
- return handler(data, context)
2039
+ return pathGuard.run(endpoint, data, function()
2040
+ return handler(data, context)
2041
+ end)
1532
2042
  else
1533
2043
  return {
1534
2044
  error = `Unknown endpoint: {endpoint}`,
@@ -1975,9 +2485,9 @@ local function computeBridgeStamp()
1975
2485
  for i = 1, #combined do
1976
2486
  h = (h * 33 + (string.byte(combined, i))) % 2147483647
1977
2487
  end
1978
- -- "3.2.1" is replaced with the package version at package time
2488
+ -- "3.4.0" is replaced with the package version at package time
1979
2489
  -- (scripts/build-plugin.mjs injectVersion), so a release bump also restamps.
1980
- return `{tostring(h)}-3.2.1`
2490
+ return `{tostring(h)}-3.4.0`
1981
2491
  end
1982
2492
  local BRIDGE_STAMP = computeBridgeStamp()
1983
2493
  local function setSource(scriptInst, source)
@@ -4213,15 +4723,20 @@ local TS = require(script.Parent.Parent.Parent.include.RuntimeLib)
4213
4723
  -- capability and drives the REAL input pipeline: SendKey feeds
4214
4724
  -- UserInputService.InputBegan/Ended and the control modules (so WASD walks the
4215
4725
  -- character at full WalkSpeed with controls intact, no Humanoid hijack),
4216
- -- SendMouseButton feeds UIS and activates GUI buttons (and hit-tests against
4217
- -- CoreGui), and SendTextInput types into the focused TextBox.
4726
+ -- SendMouseButton feeds UIS and activates GUI buttons, SendMousePosition moves
4727
+ -- the cursor (hover, MouseEnter, InputChanged), SendPointerAction scrolls
4728
+ -- under a position, and SendTextInput types into the focused TextBox. Every method throws when the
4729
+ -- input would hit interactive CoreGui.
4730
+ --
4731
+ -- Verified live on a play client: move and scroll reach game scripts with
4732
+ -- the device simulator stopped. Under touch device emulation the client has
4733
+ -- no mouse: clicks arrive as Touch, scroll still works, but moves never reach
4734
+ -- the game, so we reject move there instead of returning a false success.
4218
4735
  --
4219
- -- Method set on the VirtualInput object (verified live):
4220
- -- SendKey(isDown: boolean, keyCode: Enum.KeyCode)
4221
- -- SendMouseButton(position: Vector2, inputType: Enum.UserInputType, isDown: boolean)
4222
- -- SendTextInput(text: string)
4223
- -- There is NO SendMouseMove / SendMouseWheel / SendKeyEvent — so "move" and
4224
- -- "scroll" mouse actions are not supported.
4736
+ -- SendMouseDelta is deliberately NOT exposed. It only works while the cursor
4737
+ -- is locked (MouseBehavior.LockCenter), and on desktop Studio holds that lock
4738
+ -- by pinning and hiding the user's real OS cursor — an unacceptable takeover
4739
+ -- of the host's input.
4225
4740
  --
4226
4741
  -- Coordinate space: SendMouseButton coordinates are viewport pixels matching
4227
4742
  -- what capture_screenshot returns (window space, origin at the top-left of the
@@ -4254,6 +4769,7 @@ local MOUSE_TYPE_MAP = {
4254
4769
  Right = Enum.UserInputType.MouseButton2,
4255
4770
  Middle = Enum.UserInputType.MouseButton3,
4256
4771
  }
4772
+ local NO_MOUSE_ERROR = "This client has no mouse (touch device emulation is active), so cursor movement never reaches the game. " .. "Stop it with set_device_simulator stopSimulation=true, then retry."
4257
4773
  local function simulateMouseInput(requestData)
4258
4774
  local action = requestData.action
4259
4775
  local x = requestData.x
@@ -4263,6 +4779,7 @@ local function simulateMouseInput(requestData)
4263
4779
  _condition = "Left"
4264
4780
  end
4265
4781
  local button = _condition
4782
+ local wheel = requestData.wheel
4266
4783
  if not (action ~= "" and action) then
4267
4784
  return {
4268
4785
  error = "action is required",
@@ -4273,6 +4790,11 @@ local function simulateMouseInput(requestData)
4273
4790
  error = "x and y are required",
4274
4791
  }
4275
4792
  end
4793
+ if action == "scroll" and (not (type(wheel) == "number") or wheel == 0) then
4794
+ return {
4795
+ error = "wheel must be a non-zero number for scroll",
4796
+ }
4797
+ end
4276
4798
  -- Input is silently dropped by the engine when the window isn't rendering
4277
4799
  -- (e.g. minimized). Surface that instead of returning a false success.
4278
4800
  local notRendering = RenderMonitor.notRenderingReason()
@@ -4281,6 +4803,11 @@ local function simulateMouseInput(requestData)
4281
4803
  error = notRendering,
4282
4804
  }
4283
4805
  end
4806
+ if action == "move" and not UserInputService.MouseEnabled then
4807
+ return {
4808
+ error = NO_MOUSE_ERROR,
4809
+ }
4810
+ end
4284
4811
  local vi = getVI()
4285
4812
  if not vi then
4286
4813
  return {
@@ -4298,18 +4825,29 @@ local function simulateMouseInput(requestData)
4298
4825
  vi:SendMouseButton(pos, inputType, true)
4299
4826
  elseif action == "mouseUp" then
4300
4827
  vi:SendMouseButton(pos, inputType, false)
4828
+ elseif action == "move" then
4829
+ vi:SendMousePosition(pos)
4830
+ elseif action == "scroll" then
4831
+ vi:SendPointerAction(pos, {
4832
+ Wheel = wheel,
4833
+ })
4301
4834
  else
4302
- error(`Unsupported action "{action}". CreateVirtualInput supports click, mouseDown, mouseUp ` .. `(no move/scroll — those methods don't exist on VirtualInput).`)
4835
+ error(`Unsupported action "{action}". Use click, mouseDown, mouseUp, move, or scroll.`)
4303
4836
  end
4304
4837
  end)
4305
4838
  if success then
4306
- return {
4839
+ local result = {
4307
4840
  success = true,
4308
4841
  action = action,
4309
4842
  x = x,
4310
4843
  y = y,
4311
- button = button,
4312
4844
  }
4845
+ if action == "scroll" then
4846
+ result.wheel = wheel
4847
+ elseif action ~= "move" then
4848
+ result.button = button
4849
+ end
4850
+ return result
4313
4851
  end
4314
4852
  return {
4315
4853
  error = `Failed to simulate mouse input: {err}`,
@@ -4500,6 +5038,7 @@ local Selection = game:GetService("Selection")
4500
5038
  local _binding = Utils
4501
5039
  local getInstancePath = _binding.getInstancePath
4502
5040
  local getInstanceByPath = _binding.getInstanceByPath
5041
+ local createPathAmbiguityChecker = _binding.createPathAmbiguityChecker
4503
5042
  local function serializeValue(value)
4504
5043
  local _value = value
4505
5044
  local vType = typeof(_value)
@@ -4601,15 +5140,20 @@ local function getSelection(_requestData)
4601
5140
  message = "No objects selected",
4602
5141
  }
4603
5142
  end
5143
+ local isAmbiguous = createPathAmbiguityChecker()
4604
5144
  -- ▼ ReadonlyArray.map ▼
4605
5145
  local _newValue = table.create(#selection)
4606
5146
  local _callback = function(instance)
4607
- return {
5147
+ local entry = {
4608
5148
  name = instance.Name,
4609
5149
  className = instance.ClassName,
4610
5150
  path = getInstancePath(instance),
4611
5151
  parent = if instance.Parent then getInstancePath(instance.Parent) else nil,
4612
5152
  }
5153
+ if isAmbiguous(instance) then
5154
+ entry.ambiguous = true
5155
+ end
5156
+ return entry
4613
5157
  end
4614
5158
  for _k, _v in selection do
4615
5159
  _newValue[_k] = _callback(_v, _k - 1, selection)
@@ -4852,6 +5396,8 @@ return {
4852
5396
  <string name="Source"><![CDATA[-- Compiled with roblox-ts v3.0.0
4853
5397
  local TS = require(script.Parent.Parent.Parent.include.RuntimeLib)
4854
5398
  local RunService = TS.import(script, script.Parent.Parent.Parent, "node_modules", "@rbxts", "services").RunService
5399
+ -- Length of one MicroProfiler tick for this snapshot. CPU threads and frame
5400
+ -- boundaries use TickToMsCpu; the GPU thread uses TickToMsGpu.
4855
5401
  local DEFAULT_DURATION_MS = 1000
4856
5402
  local MIN_DURATION_MS = 100
4857
5403
  local MAX_DURATION_MS = 5000
@@ -4864,6 +5410,25 @@ local MAX_EVENTS = 1000000
4864
5410
  local COOPERATIVE_CLOCK_CHECK_INTERVAL = 128
4865
5411
  local MAX_COOPERATIVE_SLICE_SECONDS = 0.008
4866
5412
  local DEFAULT_FRAME_WINDOW = 240
5413
+ -- The engine holds at most 256 frames, and fresh Studio peers already use 256.
5414
+ -- SetFrameLimit only narrows the view of retained frames (lowering it hides
5415
+ -- frames, raising it shows them again); the profiler's memory budget often holds
5416
+ -- fewer. Changing the limit clears counter history; setting the same value does not.
5417
+ local HISTORY_FRAME_LIMIT = 256
5418
+ -- A recording peer shows a new frame after one task.wait() almost always;
5419
+ -- Studio hitches of up to 12 frames (~0.2 s) were observed.
5420
+ local RECORDING_PROBE_SECONDS = 0.3
5421
+ -- Each probe copies the whole snapshot, so re-read at this interval after the
5422
+ -- first one-frame check instead of every frame.
5423
+ local RECORDING_PROBE_INTERVAL_SECONDS = 0.1
5424
+ -- A capture's first frame with scope events can arrive several frames after
5425
+ -- EnableCapture (on a fresh Studio peer the first frame took ~70 ms and frames
5426
+ -- 1-5 had no events). Check every frame for the first FIRST_FRAME_FAST_POLLS
5427
+ -- checks, then at the poll interval, for at most the timeout. Each check copies
5428
+ -- the snapshot, so the count stays bounded.
5429
+ local FIRST_FRAME_TIMEOUT_SECONDS = 0.5
5430
+ local FIRST_FRAME_FAST_POLLS = 12
5431
+ local FIRST_FRAME_POLL_SECONDS = 0.05
4867
5432
  local BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
4868
5433
  local PAD_BYTE = (string.byte("="))
4869
5434
  local B64 = {}
@@ -5030,8 +5595,10 @@ end
5030
5595
  local function stringContains(haystack, needle)
5031
5596
  return (string.find(string.lower(haystack), string.lower(needle), 1, true)) ~= nil
5032
5597
  end
5033
- local function rawToUs(raw)
5034
- return math.floor(raw / 1000 + 0.5)
5598
+ -- Spans above this are corrupt (the old raw-tick bound, 1e12 ns, was 1000 s).
5599
+ local MAX_SPAN_US = 1e9
5600
+ local function roundUs(us)
5601
+ return math.floor(us + 0.5)
5035
5602
  end
5036
5603
  local function round2(value)
5037
5604
  return math.floor(value * 100 + 0.5) / 100
@@ -5072,7 +5639,7 @@ local function pickFields(row, fields)
5072
5639
  end
5073
5640
  return out
5074
5641
  end
5075
- local function addFrameRaw(map, frameId, raw)
5642
+ local function addFrameUs(map, frameId, us)
5076
5643
  if frameId <= 0 then
5077
5644
  return nil
5078
5645
  end
@@ -5084,15 +5651,15 @@ local function addFrameRaw(map, frameId, raw)
5084
5651
  if _condition == nil then
5085
5652
  _condition = 0
5086
5653
  end
5087
- local _arg1 = _condition + raw
5654
+ local _arg1 = _condition + us
5088
5655
  _map[_exp] = _arg1
5089
5656
  end
5090
- local function summarizeFrameImpact(frameRawById, analyzedFrames, checkpoint)
5091
- local _condition = frameRawById == nil
5657
+ local function summarizeFrameImpact(frameUsById, analyzedFrames, checkpoint)
5658
+ local _condition = frameUsById == nil
5092
5659
  if not _condition then
5093
5660
  -- ▼ ReadonlyMap.size ▼
5094
5661
  local _size = 0
5095
- for _ in frameRawById do
5662
+ for _ in frameUsById do
5096
5663
  _size += 1
5097
5664
  end
5098
5665
  -- ▲ ReadonlyMap.size ▲
@@ -5111,9 +5678,9 @@ local function summarizeFrameImpact(frameRawById, analyzedFrames, checkpoint)
5111
5678
  local totalUs = 0
5112
5679
  local maxUs = 0
5113
5680
  local maxFrameId = 0
5114
- for frameId, raw in frameRawById do
5681
+ for frameId, exactUs in frameUsById do
5115
5682
  checkpoint()
5116
- local us = rawToUs(raw)
5683
+ local us = roundUs(exactUs)
5117
5684
  table.insert(values, us)
5118
5685
  totalUs += us
5119
5686
  if us > maxUs then
@@ -5213,6 +5780,100 @@ local function safeCall(fn)
5213
5780
  end
5214
5781
  return false, tostring(value)
5215
5782
  end
5783
+ local function readNewestFrame(LibMP, checkEvents)
5784
+ if checkEvents == nil then
5785
+ checkEvents = false
5786
+ end
5787
+ local readOk, data = safeCall(function()
5788
+ return LibMP.Control:CaptureToBufferSync()
5789
+ end)
5790
+ if not readOk then
5791
+ return nil
5792
+ end
5793
+ local openOk, opened = safeCall(function()
5794
+ return LibMP.Session.OpenFromBuffer(data)
5795
+ end)
5796
+ if not openOk or not (opened ~= "" and opened) then
5797
+ return nil
5798
+ end
5799
+ local session = opened
5800
+ local infoOk, info = safeCall(function()
5801
+ local newest = session:GetFrameIdMax()
5802
+ -- A GetFrameDesc view is invalidated by the next Get/Fetch call on the
5803
+ -- session, so read it immediately.
5804
+ local desc = if newest > 0 then session:GetFrameDesc(newest) else nil
5805
+ local absolute = if desc ~= nil then desc:FrameAbsoluteId() else 0
5806
+ local hasEvents = false
5807
+ if checkEvents and newest > 0 then
5808
+ local iterator = session:CreateLogIterator()
5809
+ local configured = safeCall(function()
5810
+ iterator:Configure({
5811
+ StartFrameId = newest,
5812
+ EndFrameId = newest,
5813
+ SkipGpuThreads = true,
5814
+ SkipEvents = true,
5815
+ SkipPausedFrames = true,
5816
+ SkipFrameBoundaries = true,
5817
+ })
5818
+ return true
5819
+ end)
5820
+ if configured then
5821
+ local stepped, steppedResult = safeCall(function()
5822
+ return iterator:Step()
5823
+ end)
5824
+ hasEvents = stepped and steppedResult == true
5825
+ end
5826
+ iterator:Dispose()
5827
+ end
5828
+ return {
5829
+ id = math.max(newest, 0),
5830
+ absolute = absolute,
5831
+ hasEvents = hasEvents,
5832
+ }
5833
+ end)
5834
+ session:Dispose()
5835
+ return if infoOk then info else nil
5836
+ end
5837
+ -- LibMP cannot report whether capture is on. A paused peer serves the same
5838
+ -- cached frames on every read, so only a recording peer's newest absolute frame
5839
+ -- ID advances. Studio peers start with capture paused. This must run before the
5840
+ -- tool calls EnableProfiler: on a fresh peer EnableProfiler alone starts frames
5841
+ -- recording, which would read as a peer that was already recording.
5842
+ local function detectRecording(LibMP)
5843
+ local first = readNewestFrame(LibMP)
5844
+ if first == nil then
5845
+ return {
5846
+ recording = false,
5847
+ known = false,
5848
+ boundaryAbsolute = 0,
5849
+ boundaryFrameId = 0,
5850
+ }
5851
+ end
5852
+ local deadline = os.clock() + RECORDING_PROBE_SECONDS
5853
+ local waitSeconds
5854
+ while os.clock() < deadline do
5855
+ task.wait(waitSeconds)
5856
+ waitSeconds = RECORDING_PROBE_INTERVAL_SECONDS
5857
+ local latest = readNewestFrame(LibMP)
5858
+ if latest == nil then
5859
+ break
5860
+ end
5861
+ if latest.absolute ~= first.absolute then
5862
+ return {
5863
+ recording = true,
5864
+ known = true,
5865
+ boundaryAbsolute = latest.absolute,
5866
+ boundaryFrameId = latest.id,
5867
+ }
5868
+ end
5869
+ end
5870
+ return {
5871
+ recording = false,
5872
+ known = true,
5873
+ boundaryAbsolute = first.absolute,
5874
+ boundaryFrameId = first.id,
5875
+ }
5876
+ end
5216
5877
  local function isIdleTimer(info)
5217
5878
  local name = string.lower(info.name)
5218
5879
  if name == "sleep" or name == "idle" then
@@ -5274,7 +5935,7 @@ local function recommendedToolsForGroups(groups, targetRole)
5274
5935
  end
5275
5936
  return tools
5276
5937
  end
5277
- local function collectFrameSummary(session, startFrame, frameMax, checkpoint)
5938
+ local function collectFrameSummary(session, startFrame, frameMax, usPerTickCpu, checkpoint)
5278
5939
  local frameRows = {}
5279
5940
  local durations = {}
5280
5941
  local incompleteFrames = 0
@@ -5303,20 +5964,25 @@ local function collectFrameSummary(session, startFrame, frameMax, checkpoint)
5303
5964
  local desc = descOrErr
5304
5965
  local tickStart = desc:TickStartCpu()
5305
5966
  local tickEnd = desc:TickEndCpu()
5306
- local durationRaw = tickEnd - tickStart
5967
+ local durationExactUs = (tickEnd - tickStart) * usPerTickCpu
5307
5968
  local isIncomplete = desc:IsIncomplete()
5308
5969
  local isPaused = desc:IsPaused()
5309
5970
  if isIncomplete then
5310
5971
  incompleteFrames += 1
5311
5972
  end
5973
+ -- Pausing capture leaves one frame spanning the whole pause (seconds long,
5974
+ -- IsPaused). It holds no captured work, so it is counted but not timed,
5975
+ -- matching the event iterator's SkipPausedFrames.
5312
5976
  if isPaused then
5313
5977
  pausedFrames += 1
5978
+ _frameId = frameId
5979
+ continue
5314
5980
  end
5315
- if durationRaw <= 0 or durationRaw > 1000000000000 then
5981
+ if durationExactUs <= 0 or durationExactUs > MAX_SPAN_US then
5316
5982
  _frameId = frameId
5317
5983
  continue
5318
5984
  end
5319
- local durationUs = rawToUs(durationRaw)
5985
+ local durationUs = roundUs(durationExactUs)
5320
5986
  table.insert(durations, durationUs)
5321
5987
  local row = {
5322
5988
  frame_id = frameId,
@@ -5325,9 +5991,6 @@ local function collectFrameSummary(session, startFrame, frameMax, checkpoint)
5325
5991
  if isIncomplete then
5326
5992
  row.incomplete = true
5327
5993
  end
5328
- if isPaused then
5329
- row.paused = true
5330
- end
5331
5994
  table.insert(frameRows, row)
5332
5995
  _frameId = frameId
5333
5996
  end
@@ -5419,8 +6082,14 @@ local function captureMicroProfiler(requestData)
5419
6082
  backend = backend,
5420
6083
  }
5421
6084
  end
6085
+ -- Studio peers start with capture paused. Leave the peer as found: if
6086
+ -- something else is already recording, keep it recording; otherwise pause
6087
+ -- again after the export.
6088
+ local prior = detectRecording(LibMP)
6089
+ -- Keep the engine default instead of narrowing history to frame_window:
6090
+ -- frame_window selects frames during analysis.
5422
6091
  local frameLimitOk, frameLimitResult = safeCall(function()
5423
- return LibMP.Control:SetFrameLimit(math.min(frameWindow, 256))
6092
+ return LibMP.Control:SetFrameLimit(HISTORY_FRAME_LIMIT)
5424
6093
  end)
5425
6094
  if not frameLimitOk then
5426
6095
  return {
@@ -5429,6 +6098,9 @@ local function captureMicroProfiler(requestData)
5429
6098
  backend = backend,
5430
6099
  }
5431
6100
  end
6101
+ -- Profiling is on by default in Studio and the tool never turns it off. It
6102
+ -- must follow the recording check: on a fresh peer EnableProfiler alone
6103
+ -- starts frames recording.
5432
6104
  local profilerOk, profilerResult = safeCall(function()
5433
6105
  return LibMP.Control:EnableProfiler(true)
5434
6106
  end)
@@ -5439,31 +6111,72 @@ local function captureMicroProfiler(requestData)
5439
6111
  backend = backend,
5440
6112
  }
5441
6113
  end
5442
- local captureStartOk, captureStartResult = safeCall(function()
5443
- return LibMP.Control:EnableCapture(true)
5444
- end)
5445
- if not captureStartOk then
5446
- return {
5447
- error = "micro_profiler_capture_start_failed",
5448
- message = tostring(captureStartResult),
5449
- backend = backend,
5450
- }
6114
+ -- Absolute ID of the capture's first analyzed frame. Frames before it predate
6115
+ -- the capture or are instrumentation warm-up without scope events.
6116
+ local windowStartAbsolute = prior.boundaryAbsolute + 1
6117
+ -- Frame ID of that frame. Frame IDs run on without gaps, so dropped frames
6118
+ -- from the window are counted exactly against it.
6119
+ local windowStartFrameId = prior.boundaryFrameId + 1
6120
+ local firstFrameWaitMs = 0
6121
+ -- When the first-frame wait times out, the window starts right after the
6122
+ -- pre-capture frame and so includes the frames recorded during the wait.
6123
+ local windowStartsAtWait
6124
+ if not prior.recording then
6125
+ local captureStartOk, captureStartResult = safeCall(function()
6126
+ return LibMP.Control:EnableCapture(true)
6127
+ end)
6128
+ if not captureStartOk then
6129
+ return {
6130
+ error = "micro_profiler_capture_start_failed",
6131
+ message = tostring(captureStartResult),
6132
+ backend = backend,
6133
+ }
6134
+ end
6135
+ -- The first frames after capture starts can carry no scope events yet
6136
+ -- (frames 1-5 of a fresh peer's first capture), so start timing
6137
+ -- duration_ms at the first frame with events; the analysis starts there too.
6138
+ local waitStartedAt = os.clock()
6139
+ windowStartsAtWait = waitStartedAt
6140
+ local polls = 0
6141
+ while os.clock() - waitStartedAt < FIRST_FRAME_TIMEOUT_SECONDS do
6142
+ task.wait(if polls < FIRST_FRAME_FAST_POLLS then nil else FIRST_FRAME_POLL_SECONDS)
6143
+ polls += 1
6144
+ local latest = readNewestFrame(LibMP, true)
6145
+ if latest ~= nil and latest.absolute > prior.boundaryAbsolute and latest.hasEvents then
6146
+ windowStartAbsolute = latest.absolute
6147
+ windowStartFrameId = latest.id
6148
+ windowStartsAtWait = nil
6149
+ break
6150
+ end
6151
+ end
6152
+ firstFrameWaitMs = (os.clock() - waitStartedAt) * 1000
5451
6153
  end
6154
+ local timerStartedAt = os.clock()
5452
6155
  task.wait(durationMs / 1000)
6156
+ -- Wall time covered by the analysis window: from the first analyzed frame, or
6157
+ -- from the start of the wait when it timed out.
6158
+ local _exp = os.clock()
6159
+ local _condition_1 = windowStartsAtWait
6160
+ if _condition_1 == nil then
6161
+ _condition_1 = timerStartedAt
6162
+ end
6163
+ local captureWallMs = (_exp - _condition_1) * 1000
5453
6164
  -- Active reads synchronize the engine's data; paused reads can return an
5454
- -- empty or stale cache. Export first, then pause, including on export failure.
6165
+ -- empty or stale cache. Export first, then restore, including on export failure.
5455
6166
  local bufferOk, snapshotOrErr = safeCall(function()
5456
6167
  return LibMP.Control:CaptureToBufferSync()
5457
6168
  end)
5458
- local captureStopOk, captureStopResult = safeCall(function()
5459
- return LibMP.Control:EnableCapture(false)
5460
- end)
5461
- if not captureStopOk then
5462
- return {
5463
- error = "micro_profiler_capture_stop_failed",
5464
- message = tostring(captureStopResult),
5465
- backend = backend,
5466
- }
6169
+ if not prior.recording then
6170
+ local captureStopOk, captureStopResult = safeCall(function()
6171
+ return LibMP.Control:EnableCapture(false)
6172
+ end)
6173
+ if not captureStopOk then
6174
+ return {
6175
+ error = "micro_profiler_capture_stop_failed",
6176
+ message = tostring(captureStopResult),
6177
+ backend = backend,
6178
+ }
6179
+ end
5467
6180
  end
5468
6181
  if not bufferOk then
5469
6182
  return {
@@ -5493,13 +6206,94 @@ local function captureMicroProfiler(requestData)
5493
6206
  backend = backend,
5494
6207
  }
5495
6208
  end
6209
+ -- MicroProfiler ticks are not nanoseconds: their length comes from the
6210
+ -- snapshot's clock (for example 2.1e-7 ms on a 4.7 GHz CPU timer). GPU-thread
6211
+ -- timestamps use their own clock.
6212
+ local clockOk, clockOrErr = safeCall(function()
6213
+ return session:FetchGlobalDesc()
6214
+ end)
6215
+ local clock = if clockOk then clockOrErr else nil
6216
+ local _tickToMsCpu = clock
6217
+ if _tickToMsCpu ~= nil then
6218
+ _tickToMsCpu = _tickToMsCpu.TickToMsCpu
6219
+ end
6220
+ local tickToMsCpu = _tickToMsCpu
6221
+ local _tickToMsGpu = clock
6222
+ if _tickToMsGpu ~= nil then
6223
+ _tickToMsGpu = _tickToMsGpu.TickToMsGpu
6224
+ end
6225
+ local tickToMsGpu = _tickToMsGpu
6226
+ local validTickLength = function(value)
6227
+ local _value = value
6228
+ local _condition_2 = type(_value) == "number"
6229
+ if _condition_2 then
6230
+ _condition_2 = value > 0 and value < math.huge
6231
+ end
6232
+ return _condition_2
6233
+ end
6234
+ if not validTickLength(tickToMsCpu) or (includeGpu and not validTickLength(tickToMsGpu)) then
6235
+ session:Dispose()
6236
+ return {
6237
+ error = "micro_profiler_clock_unavailable",
6238
+ message = "The MicroProfiler snapshot did not report a valid tick length, so its times cannot be converted.",
6239
+ tick_to_ms_cpu = tickToMsCpu,
6240
+ tick_to_ms_gpu = tickToMsGpu,
6241
+ buffer_bytes = buffer.len(snapshot),
6242
+ backend = backend,
6243
+ }
6244
+ end
6245
+ local usPerTickCpu = tickToMsCpu * 1000
6246
+ local usPerTickGpu = if validTickLength(tickToMsGpu) then tickToMsGpu * 1000 else usPerTickCpu
5496
6247
  local timerIds = session:FetchTimerIds() or {}
5497
6248
  local threadIds = session:FetchThreadIds() or {}
5498
6249
  local frameMin = session:GetFrameIdMin()
5499
6250
  local frameMax = session:GetFrameIdMax()
5500
- -- Frame IDs start at 1. Studio cuts a frame only when it renders, so a capture
5501
- -- without frames means nothing was drawn, not that the workload was idle.
5502
- if frameMax <= 0 then
6251
+ -- Frame IDs start at 1. Studio cuts a frame only when it renders. Retained
6252
+ -- history can predate this capture (a recording peer, or frames kept from an
6253
+ -- earlier capture), so analyze only frames from the capture's first analyzed
6254
+ -- frame on. That also drops warm-up frames without scope events and the one
6255
+ -- IsPaused frame a resume adds.
6256
+ local firstCaptureFrame = frameMax + 1
6257
+ local capturedFrames = 0
6258
+ -- Paused frames inside the window (none normally) can never carry events.
6259
+ local pausedFrameIds = {}
6260
+ do
6261
+ local _frameId = frameMax
6262
+ local _shouldIncrement = false
6263
+ while true do
6264
+ local frameId = _frameId
6265
+ if _shouldIncrement then
6266
+ frameId -= 1
6267
+ else
6268
+ _shouldIncrement = true
6269
+ end
6270
+ if not (frameMax > 0 and frameId >= frameMin) then
6271
+ break
6272
+ end
6273
+ local descOk, descOrErr = safeCall(function()
6274
+ return session:GetFrameDesc(frameId)
6275
+ end)
6276
+ if not descOk or not (descOrErr ~= "" and descOrErr) then
6277
+ break
6278
+ end
6279
+ local desc = descOrErr
6280
+ if desc:FrameAbsoluteId() < windowStartAbsolute then
6281
+ break
6282
+ end
6283
+ if desc:IsPaused() then
6284
+ local _frameId_1 = frameId
6285
+ table.insert(pausedFrameIds, _frameId_1)
6286
+ _frameId = frameId
6287
+ continue
6288
+ end
6289
+ capturedFrames += 1
6290
+ firstCaptureFrame = frameId
6291
+ _frameId = frameId
6292
+ end
6293
+ end
6294
+ -- No frame recorded during the capture means nothing was drawn, not that the
6295
+ -- workload was idle.
6296
+ if capturedFrames == 0 then
5503
6297
  session:Dispose()
5504
6298
  return {
5505
6299
  error = "micro_profiler_no_frames",
@@ -5509,8 +6303,18 @@ local function captureMicroProfiler(requestData)
5509
6303
  backend = backend,
5510
6304
  }
5511
6305
  end
5512
- local startFrame = math.max(frameMin, frameMax - frameWindow + 1)
5513
- local framesConsidered = if frameMax >= startFrame then frameMax - startFrame + 1 else 0
6306
+ local startFrame = math.max(firstCaptureFrame, frameMax - frameWindow + 1)
6307
+ local framesConsidered = frameMax - startFrame + 1
6308
+ -- The engine drops its oldest frames once its memory budget fills, often well
6309
+ -- below the frame limit (about 70 frames on a loaded server peer). Frames from
6310
+ -- the window's first frame to the oldest retained one were recorded during
6311
+ -- this capture and are gone (warm-up frames and the IsPaused frame a resume
6312
+ -- adds come before the window and do not count, except after a first-frame
6313
+ -- wait timeout, when the window starts right after the pre-capture frame).
6314
+ -- That matters only if the analysis wanted them: frame_window may ask for
6315
+ -- fewer frames than were retained.
6316
+ local framesEvicted = if prior.known then math.max(0, frameMin - windowStartFrameId) else 0
6317
+ local historyTruncated = framesEvicted > 0 and frameMax - firstCaptureFrame + 1 < frameWindow
5514
6318
  local groupCache = {}
5515
6319
  local timerCache = {}
5516
6320
  local threadCache = {}
@@ -5527,15 +6331,15 @@ local function captureMicroProfiler(requestData)
5527
6331
  return session:FetchGroupDesc(groupId)
5528
6332
  end)
5529
6333
  local desc = if ok then descOrErr else nil
5530
- local _condition_1 = desc
5531
- if _condition_1 then
6334
+ local _condition_2 = desc
6335
+ if _condition_2 then
5532
6336
  local _groupName = desc.GroupName
5533
- _condition_1 = type(_groupName) == "string"
5534
- if _condition_1 then
5535
- _condition_1 = desc.GroupName ~= ""
6337
+ _condition_2 = type(_groupName) == "string"
6338
+ if _condition_2 then
6339
+ _condition_2 = desc.GroupName ~= ""
5536
6340
  end
5537
6341
  end
5538
- local name = if _condition_1 then desc.GroupName else tostring(groupId)
6342
+ local name = if _condition_2 then desc.GroupName else tostring(groupId)
5539
6343
  local _groupId_1 = groupId
5540
6344
  groupCache[_groupId_1] = name
5541
6345
  return name
@@ -5550,25 +6354,25 @@ local function captureMicroProfiler(requestData)
5550
6354
  return session:FetchTimerDesc(timerId)
5551
6355
  end)
5552
6356
  local desc = if ok then descOrErr else nil
5553
- local _condition_1 = desc
5554
- if _condition_1 then
6357
+ local _condition_2 = desc
6358
+ if _condition_2 then
5555
6359
  local _groupId = desc.GroupId
5556
- _condition_1 = type(_groupId) == "number"
6360
+ _condition_2 = type(_groupId) == "number"
5557
6361
  end
5558
- local groupId = if _condition_1 then desc.GroupId else nil
6362
+ local groupId = if _condition_2 then desc.GroupId else nil
5559
6363
  local _object = {
5560
6364
  timer_id = timerId,
5561
6365
  }
5562
6366
  local _left = "name"
5563
- local _condition_2 = desc
5564
- if _condition_2 then
6367
+ local _condition_3 = desc
6368
+ if _condition_3 then
5565
6369
  local _timerName = desc.TimerName
5566
- _condition_2 = type(_timerName) == "string"
5567
- if _condition_2 then
5568
- _condition_2 = desc.TimerName ~= ""
6370
+ _condition_3 = type(_timerName) == "string"
6371
+ if _condition_3 then
6372
+ _condition_3 = desc.TimerName ~= ""
5569
6373
  end
5570
6374
  end
5571
- _object[_left] = if _condition_2 then desc.TimerName else tostring(timerId)
6375
+ _object[_left] = if _condition_3 then desc.TimerName else tostring(timerId)
5572
6376
  _object.group_id = groupId
5573
6377
  _object.group = getGroupName(groupId)
5574
6378
  _object.is_user_timer = if desc and desc.IsUserTimer == true then true else nil
@@ -5591,53 +6395,53 @@ local function captureMicroProfiler(requestData)
5591
6395
  thread_id = threadId,
5592
6396
  }
5593
6397
  local _left = "name"
5594
- local _condition_1 = desc
5595
- if _condition_1 then
6398
+ local _condition_2 = desc
6399
+ if _condition_2 then
5596
6400
  local _threadName = desc.ThreadName
5597
- _condition_1 = type(_threadName) == "string"
5598
- if _condition_1 then
5599
- _condition_1 = desc.ThreadName ~= ""
6401
+ _condition_2 = type(_threadName) == "string"
6402
+ if _condition_2 then
6403
+ _condition_2 = desc.ThreadName ~= ""
5600
6404
  end
5601
6405
  end
5602
- _object[_left] = if _condition_1 then desc.ThreadName else tostring(threadId)
6406
+ _object[_left] = if _condition_2 then desc.ThreadName else tostring(threadId)
5603
6407
  local info = _object
5604
6408
  if desc and desc.IsGpu == true then
5605
6409
  info.is_gpu = true
5606
6410
  end
5607
- local _condition_2 = desc
5608
- if _condition_2 then
6411
+ local _condition_3 = desc
6412
+ if _condition_3 then
5609
6413
  local _bufferSize = desc.BufferSize
5610
- _condition_2 = type(_bufferSize) == "number"
6414
+ _condition_3 = type(_bufferSize) == "number"
5611
6415
  end
5612
- if _condition_2 then
6416
+ if _condition_3 then
5613
6417
  info.buffer_size = desc.BufferSize
5614
6418
  end
5615
6419
  local _threadId_1 = threadId
5616
6420
  threadCache[_threadId_1] = info
5617
6421
  return info
5618
6422
  end
5619
- local function addTimerAggregate(map, timerId, inclusiveRaw, exclusiveRaw)
6423
+ local function addTimerAggregate(map, timerId, inclusiveUs, exclusiveUs)
5620
6424
  local _map = map
5621
6425
  local _timerId = timerId
5622
6426
  local aggregate = _map[_timerId]
5623
6427
  if aggregate == nil then
5624
6428
  aggregate = {
5625
6429
  timer_id = timerId,
5626
- inclusive_raw = 0,
5627
- exclusive_raw = 0,
6430
+ inclusive_us = 0,
6431
+ exclusive_us = 0,
5628
6432
  count = 0,
5629
- max_raw = 0,
6433
+ max_us = 0,
5630
6434
  }
5631
6435
  local _map_1 = map
5632
6436
  local _timerId_1 = timerId
5633
6437
  local _aggregate = aggregate
5634
6438
  _map_1[_timerId_1] = _aggregate
5635
6439
  end
5636
- aggregate.inclusive_raw += inclusiveRaw
5637
- aggregate.exclusive_raw += exclusiveRaw
6440
+ aggregate.inclusive_us += inclusiveUs
6441
+ aggregate.exclusive_us += exclusiveUs
5638
6442
  aggregate.count += 1
5639
- if inclusiveRaw > aggregate.max_raw then
5640
- aggregate.max_raw = inclusiveRaw
6443
+ if inclusiveUs > aggregate.max_us then
6444
+ aggregate.max_us = inclusiveUs
5641
6445
  end
5642
6446
  end
5643
6447
  local focusMasks = FOCUS_GROUP_MASKS[focus] or {}
@@ -5681,6 +6485,8 @@ local function captureMicroProfiler(requestData)
5681
6485
  end
5682
6486
  local checkpoint = createCooperativeCheckpoint()
5683
6487
  local stacks = {}
6488
+ -- Microseconds per tick for each thread: the GPU thread has its own clock.
6489
+ local threadUsPerTick = {}
5684
6490
  local aggregates = {}
5685
6491
  local timerThreadAggregates = {}
5686
6492
  local timerFrameAggregates = {}
@@ -5694,7 +6500,7 @@ local function captureMicroProfiler(requestData)
5694
6500
  local sampledFrameMin
5695
6501
  local sampledFrameMax
5696
6502
  local lastProcessedFrameId
5697
- local lastProcessedTimestampRaw
6503
+ local lastProcessedTimestampUs
5698
6504
  while eventsSampled < maxEvents do
5699
6505
  checkpoint()
5700
6506
  if not iterator:Step() then
@@ -5708,9 +6514,15 @@ local function captureMicroProfiler(requestData)
5708
6514
  local frameId = state:FrameId()
5709
6515
  local threadId = state:ThreadId()
5710
6516
  local timerId = state:TimerId()
5711
- local timestampRaw = state:Timestamp()
6517
+ local timestampTick = state:Timestamp()
6518
+ local usPerTick = threadUsPerTick[threadId]
6519
+ if usPerTick == nil then
6520
+ usPerTick = if state:IsGpuThread() then usPerTickGpu else usPerTickCpu
6521
+ local _usPerTick = usPerTick
6522
+ threadUsPerTick[threadId] = _usPerTick
6523
+ end
5712
6524
  lastProcessedFrameId = frameId
5713
- lastProcessedTimestampRaw = timestampRaw
6525
+ lastProcessedTimestampUs = timestampTick * usPerTick
5714
6526
  if frameId > 0 then
5715
6527
  sampledFrames[frameId] = true
5716
6528
  if sampledFrameMin == nil or frameId < sampledFrameMin then
@@ -5731,8 +6543,8 @@ local function captureMicroProfiler(requestData)
5731
6543
  local _stack = stack
5732
6544
  local _arg0 = {
5733
6545
  timerId = timerId,
5734
- timestampRaw = timestampRaw,
5735
- childRaw = 0,
6546
+ enterTick = timestampTick,
6547
+ childUs = 0,
5736
6548
  frameId = frameId,
5737
6549
  }
5738
6550
  table.insert(_stack, _arg0)
@@ -5756,49 +6568,56 @@ local function captureMicroProfiler(requestData)
5756
6568
  unmatchedExits += 1
5757
6569
  continue
5758
6570
  end
5759
- local inclusiveRaw = timestampRaw - entry.timestampRaw
5760
- if inclusiveRaw < 0 or inclusiveRaw > 1000000000000 then
6571
+ local inclusiveUs = (timestampTick - entry.enterTick) * usPerTick
6572
+ if inclusiveUs < 0 or inclusiveUs > MAX_SPAN_US then
5761
6573
  droppedSpans += 1
5762
6574
  continue
5763
6575
  end
5764
- local exclusiveRaw = math.max(0, inclusiveRaw - entry.childRaw)
6576
+ local exclusiveUs = math.max(0, inclusiveUs - entry.childUs)
5765
6577
  local parent = stack[#stack]
5766
6578
  if parent ~= nil then
5767
- parent.childRaw += inclusiveRaw
6579
+ parent.childUs += inclusiveUs
5768
6580
  local edgeKey = `{parent.timerId}:{timerId}`
5769
6581
  local edge = edgeAggregates[edgeKey]
5770
6582
  if edge == nil then
5771
6583
  edge = {
5772
6584
  parent_timer_id = parent.timerId,
5773
6585
  child_timer_id = timerId,
5774
- inclusive_raw = 0,
6586
+ inclusive_us = 0,
5775
6587
  count = 0,
5776
- max_raw = 0,
6588
+ max_us = 0,
5777
6589
  }
5778
6590
  local _edge = edge
5779
6591
  edgeAggregates[edgeKey] = _edge
5780
6592
  end
5781
- edge.inclusive_raw += inclusiveRaw
6593
+ edge.inclusive_us += inclusiveUs
5782
6594
  edge.count += 1
5783
- if inclusiveRaw > edge.max_raw then
5784
- edge.max_raw = inclusiveRaw
6595
+ if inclusiveUs > edge.max_us then
6596
+ edge.max_us = inclusiveUs
5785
6597
  end
5786
6598
  end
5787
- addTimerAggregate(aggregates, timerId, inclusiveRaw, exclusiveRaw)
6599
+ addTimerAggregate(aggregates, timerId, inclusiveUs, exclusiveUs)
5788
6600
  local frameMap = timerFrameAggregates[timerId]
5789
6601
  if frameMap == nil then
5790
6602
  frameMap = {}
5791
6603
  local _frameMap = frameMap
5792
6604
  timerFrameAggregates[timerId] = _frameMap
5793
6605
  end
5794
- addFrameRaw(frameMap, if entry.frameId > 0 then entry.frameId else frameId, inclusiveRaw)
6606
+ addFrameUs(frameMap, if entry.frameId > 0 then entry.frameId else frameId, inclusiveUs)
5795
6607
  local threadMap = timerThreadAggregates[timerId]
5796
6608
  if threadMap == nil then
5797
6609
  threadMap = {}
5798
6610
  local _threadMap = threadMap
5799
6611
  timerThreadAggregates[timerId] = _threadMap
5800
6612
  end
5801
- addTimerAggregate(threadMap, threadId, inclusiveRaw, exclusiveRaw)
6613
+ addTimerAggregate(threadMap, threadId, inclusiveUs, exclusiveUs)
6614
+ end
6615
+ end
6616
+ -- The iterator skips paused frames (SkipPausedFrames), so they cannot be sampled.
6617
+ local selectedPausedFrames = 0
6618
+ for _, frameId in pausedFrameIds do
6619
+ if frameId >= startFrame then
6620
+ selectedPausedFrames += 1
5802
6621
  end
5803
6622
  end
5804
6623
  -- ▼ ReadonlySet.size ▼
@@ -5807,25 +6626,25 @@ local function captureMicroProfiler(requestData)
5807
6626
  _size += 1
5808
6627
  end
5809
6628
  -- ▲ ReadonlySet.size ▲
5810
- local sampledFrameCoveragePct = percent(_size, framesConsidered)
5811
- local _condition_1 = sampledFrameMin
5812
- if _condition_1 == nil then
5813
- _condition_1 = startFrame
5814
- end
5815
- local analysisFrameMin = _condition_1
5816
- local _condition_2 = sampledFrameMax
6629
+ local sampledFrameCoveragePct = percent(_size, framesConsidered - selectedPausedFrames)
6630
+ local _condition_2 = sampledFrameMin
5817
6631
  if _condition_2 == nil then
5818
- _condition_2 = frameMax
6632
+ _condition_2 = startFrame
6633
+ end
6634
+ local analysisFrameMin = _condition_2
6635
+ local _condition_3 = sampledFrameMax
6636
+ if _condition_3 == nil then
6637
+ _condition_3 = frameMax
5819
6638
  end
5820
- local analysisFrameMax = _condition_2
5821
- local frameSummary = collectFrameSummary(session, analysisFrameMin, analysisFrameMax, checkpoint)
6639
+ local analysisFrameMax = _condition_3
6640
+ local frameSummary = collectFrameSummary(session, analysisFrameMin, analysisFrameMax, usPerTickCpu, checkpoint)
5822
6641
  local _frames = frameSummary.frames
5823
- local _condition_3 = type(_frames) == "number"
5824
- if _condition_3 then
5825
- _condition_3 = (frameSummary.frames) > 0
6642
+ local _condition_4 = type(_frames) == "number"
6643
+ if _condition_4 then
6644
+ _condition_4 = (frameSummary.frames) > 0
5826
6645
  end
5827
6646
  local _result
5828
- if _condition_3 then
6647
+ if _condition_4 then
5829
6648
  _result = frameSummary.frames
5830
6649
  else
5831
6650
  -- ▼ ReadonlySet.size ▼
@@ -5850,11 +6669,11 @@ local function captureMicroProfiler(requestData)
5850
6669
  end
5851
6670
  local analysisFrameCount = _result
5852
6671
  local _total_duration_us = frameSummary.total_duration_us
5853
- local _condition_4 = type(_total_duration_us) == "number"
5854
- if _condition_4 then
5855
- _condition_4 = (frameSummary.total_duration_us) > 0
6672
+ local _condition_5 = type(_total_duration_us) == "number"
6673
+ if _condition_5 then
6674
+ _condition_5 = (frameSummary.total_duration_us) > 0
5856
6675
  end
5857
- local analysisDurationUs = if _condition_4 then frameSummary.total_duration_us else durationMs * 1000
6676
+ local analysisDurationUs = if _condition_5 then frameSummary.total_duration_us else durationMs * 1000
5858
6677
  local analysisDurationMs = analysisDurationUs / 1000
5859
6678
  local rows = {}
5860
6679
  local rowsByTimerId = {}
@@ -5869,7 +6688,7 @@ local function captureMicroProfiler(requestData)
5869
6688
  for timerId, aggregate in aggregates do
5870
6689
  checkpoint()
5871
6690
  local info = getTimerInfo(timerId)
5872
- local totalUs = rawToUs(aggregate.inclusive_raw)
6691
+ local totalUs = roundUs(aggregate.inclusive_us)
5873
6692
  if not includeIdle and isIdleTimer(info) then
5874
6693
  omittedIdle += 1
5875
6694
  continue
@@ -5879,39 +6698,39 @@ local function captureMicroProfiler(requestData)
5879
6698
  continue
5880
6699
  end
5881
6700
  if filter ~= nil then
5882
- local _exp = info.name
5883
- local _condition_5 = info.group
5884
- if _condition_5 == nil then
5885
- _condition_5 = ""
6701
+ local _exp_1 = info.name
6702
+ local _condition_6 = info.group
6703
+ if _condition_6 == nil then
6704
+ _condition_6 = ""
5886
6705
  end
5887
- local searchable = `{_exp} {_condition_5}`
6706
+ local searchable = `{_exp_1} {_condition_6}`
5888
6707
  if not stringContains(searchable, filter) then
5889
6708
  omittedByFilter += 1
5890
6709
  continue
5891
6710
  end
5892
6711
  end
5893
- local _condition_5 = info.group
5894
- if _condition_5 == nil then
5895
- _condition_5 = "<unknown>"
6712
+ local _condition_6 = info.group
6713
+ if _condition_6 == nil then
6714
+ _condition_6 = "<unknown>"
5896
6715
  end
5897
- local group = _condition_5
5898
- local inclusiveUs = rawToUs(aggregate.inclusive_raw)
5899
- local exclusiveUs = rawToUs(aggregate.exclusive_raw)
6716
+ local group = _condition_6
6717
+ local inclusiveUs = roundUs(aggregate.inclusive_us)
6718
+ local exclusiveUs = roundUs(aggregate.exclusive_us)
5900
6719
  local avgUs = if aggregate.count > 0 then round2(totalUs / aggregate.count) else 0
5901
- local maxUs = rawToUs(aggregate.max_raw)
6720
+ local maxUs = roundUs(aggregate.max_us)
5902
6721
  local groupAgg = groupAggregates[group]
5903
6722
  if groupAgg == nil then
5904
6723
  groupAgg = {
5905
6724
  group = group,
5906
- inclusive_raw = 0,
5907
- exclusive_raw = 0,
6725
+ inclusive_us = 0,
6726
+ exclusive_us = 0,
5908
6727
  count = 0,
5909
6728
  }
5910
6729
  local _groupAgg = groupAgg
5911
6730
  groupAggregates[group] = _groupAgg
5912
6731
  end
5913
- groupAgg.inclusive_raw += aggregate.inclusive_raw
5914
- groupAgg.exclusive_raw += aggregate.exclusive_raw
6732
+ groupAgg.inclusive_us += aggregate.inclusive_us
6733
+ groupAgg.exclusive_us += aggregate.exclusive_us
5915
6734
  groupAgg.count += aggregate.count
5916
6735
  local row = {
5917
6736
  timer_id = timerId,
@@ -5956,8 +6775,8 @@ local function captureMicroProfiler(requestData)
5956
6775
  local _groupFrames = groupFrames
5957
6776
  groupFrameAggregates[group] = _groupFrames
5958
6777
  end
5959
- for frameId, raw in timerFrames do
5960
- addFrameRaw(groupFrames, frameId, raw)
6778
+ for frameId, us in timerFrames do
6779
+ addFrameUs(groupFrames, frameId, us)
5961
6780
  checkpoint()
5962
6781
  end
5963
6782
  end
@@ -5970,19 +6789,19 @@ local function captureMicroProfiler(requestData)
5970
6789
  if threadAggregateRow == nil then
5971
6790
  threadAggregateRow = {
5972
6791
  timer_id = threadId,
5973
- inclusive_raw = 0,
5974
- exclusive_raw = 0,
6792
+ inclusive_us = 0,
6793
+ exclusive_us = 0,
5975
6794
  count = 0,
5976
- max_raw = 0,
6795
+ max_us = 0,
5977
6796
  }
5978
6797
  local _threadAggregateRow = threadAggregateRow
5979
6798
  threadAggregates[threadId] = _threadAggregateRow
5980
6799
  end
5981
- threadAggregateRow.inclusive_raw += threadAggregate.inclusive_raw
5982
- threadAggregateRow.exclusive_raw += threadAggregate.exclusive_raw
6800
+ threadAggregateRow.inclusive_us += threadAggregate.inclusive_us
6801
+ threadAggregateRow.exclusive_us += threadAggregate.exclusive_us
5983
6802
  threadAggregateRow.count += threadAggregate.count
5984
- if threadAggregate.max_raw > threadAggregateRow.max_raw then
5985
- threadAggregateRow.max_raw = threadAggregate.max_raw
6803
+ if threadAggregate.max_us > threadAggregateRow.max_us then
6804
+ threadAggregateRow.max_us = threadAggregate.max_us
5986
6805
  end
5987
6806
  local threadRows = threadTimerRows[threadId]
5988
6807
  if threadRows == nil then
@@ -5990,8 +6809,8 @@ local function captureMicroProfiler(requestData)
5990
6809
  local _threadRows = threadRows
5991
6810
  threadTimerRows[threadId] = _threadRows
5992
6811
  end
5993
- local threadTotalUs = rawToUs(threadAggregate.inclusive_raw)
5994
- local threadExclusiveUs = rawToUs(threadAggregate.exclusive_raw)
6812
+ local threadTotalUs = roundUs(threadAggregate.inclusive_us)
6813
+ local threadExclusiveUs = roundUs(threadAggregate.exclusive_us)
5995
6814
  local threadAvgUs = if threadAggregate.count > 0 then round2(threadTotalUs / threadAggregate.count) else 0
5996
6815
  local threadInfo = getThreadInfo(threadId)
5997
6816
  local threadTimerRow = {
@@ -6007,7 +6826,7 @@ local function captureMicroProfiler(requestData)
6007
6826
  count = threadAggregate.count,
6008
6827
  count_per_s = perSecond(threadAggregate.count, analysisDurationMs),
6009
6828
  avg_invocation_us = threadAvgUs,
6010
- max_invocation_us = rawToUs(threadAggregate.max_raw),
6829
+ max_invocation_us = roundUs(threadAggregate.max_us),
6011
6830
  }
6012
6831
  local threadMaxToAvg = ratio(threadTimerRow.max_invocation_us, threadAvgUs)
6013
6832
  if threadMaxToAvg ~= nil then
@@ -6064,8 +6883,8 @@ local function captureMicroProfiler(requestData)
6064
6883
  if parentRow == nil or childRow == nil then
6065
6884
  continue
6066
6885
  end
6067
- local inclusiveUs = rawToUs(edge.inclusive_raw)
6068
- local maxUs = rawToUs(edge.max_raw)
6886
+ local inclusiveUs = roundUs(edge.inclusive_us)
6887
+ local maxUs = roundUs(edge.max_us)
6069
6888
  local avgUs = if edge.count > 0 then round2(inclusiveUs / edge.count) else 0
6070
6889
  local edgeRow = {
6071
6890
  parent = {
@@ -6256,8 +7075,8 @@ local function captureMicroProfiler(requestData)
6256
7075
  for threadId, aggregate in threadAggregates do
6257
7076
  checkpoint()
6258
7077
  local info = getThreadInfo(threadId)
6259
- local inclusiveUs = rawToUs(aggregate.inclusive_raw)
6260
- local exclusiveUs = rawToUs(aggregate.exclusive_raw)
7078
+ local inclusiveUs = roundUs(aggregate.inclusive_us)
7079
+ local exclusiveUs = roundUs(aggregate.exclusive_us)
6261
7080
  local row = {
6262
7081
  thread_id = threadId,
6263
7082
  thread_name = info.name,
@@ -6268,7 +7087,7 @@ local function captureMicroProfiler(requestData)
6268
7087
  exclusive_pct = percent(exclusiveUs, inclusiveUs),
6269
7088
  count = aggregate.count,
6270
7089
  count_per_s = perSecond(aggregate.count, analysisDurationMs),
6271
- max_invocation_us = rawToUs(aggregate.max_raw),
7090
+ max_invocation_us = roundUs(aggregate.max_us),
6272
7091
  pct_of_analyzed_wall = percent(inclusiveUs, analysisDurationUs),
6273
7092
  }
6274
7093
  local timerRows = threadTimerRows[threadId] or {}
@@ -6322,11 +7141,11 @@ local function captureMicroProfiler(requestData)
6322
7141
  for _, aggregate in groupAggregates do
6323
7142
  checkpoint()
6324
7143
  local _group = aggregate.group
6325
- local _condition_5 = groupTimerRows[_group]
6326
- if _condition_5 == nil then
6327
- _condition_5 = {}
7144
+ local _condition_6 = groupTimerRows[_group]
7145
+ if _condition_6 == nil then
7146
+ _condition_6 = {}
6328
7147
  end
6329
- local timerRows = _condition_5
7148
+ local timerRows = _condition_6
6330
7149
  cooperativeSort(timerRows, function(a, b)
6331
7150
  return (a.inclusive_us) > (b.inclusive_us)
6332
7151
  end, checkpoint)
@@ -6357,8 +7176,8 @@ local function captureMicroProfiler(requestData)
6357
7176
  table.insert(topGroupTimers, _arg0)
6358
7177
  end
6359
7178
  end
6360
- local inclusiveUs = rawToUs(aggregate.inclusive_raw)
6361
- local exclusiveUs = rawToUs(aggregate.exclusive_raw)
7179
+ local inclusiveUs = roundUs(aggregate.inclusive_us)
7180
+ local exclusiveUs = roundUs(aggregate.exclusive_us)
6362
7181
  local groupRow = {
6363
7182
  group = aggregate.group,
6364
7183
  inclusive_us = inclusiveUs,
@@ -6454,6 +7273,41 @@ local function captureMicroProfiler(requestData)
6454
7273
  if sampledFrameCoveragePct < 100 then
6455
7274
  table.insert(partialReasons, "selected_frame_event_coverage_below_100")
6456
7275
  end
7276
+ if historyTruncated then
7277
+ table.insert(partialReasons, "capture_history_truncated")
7278
+ end
7279
+ -- Safety net for any other shortfall. Whole frames make up to about two frames
7280
+ -- of slack normal, a frame_window smaller than the capture is intentional, and
7281
+ -- hitting max_events already has its own reason.
7282
+ local eventLimitHit = eventsSampled >= maxEvents
7283
+ local _avg_us = frameSummary.avg_us
7284
+ local avgFrameUs = if type(_avg_us) == "number" then frameSummary.avg_us else 0
7285
+ -- A frame_window the caller chose is intentional; the default (240 frames) is
7286
+ -- not, so a long capture it cuts short is flagged.
7287
+ local frameWindowLimited = startFrame > firstCaptureFrame
7288
+ local _frame_window = requestData.frame_window
7289
+ local frameWindowRequested = type(_frame_window) == "number"
7290
+ local coverageShort = not historyTruncated and not (frameWindowLimited and frameWindowRequested) and not eventLimitHit and captureWallMs - analysisDurationMs > math.max(captureWallMs * 0.1, (2 * avgFrameUs) / 1000)
7291
+ if coverageShort then
7292
+ table.insert(partialReasons, "capture_coverage_below_requested")
7293
+ end
7294
+ local qualityNotes = {}
7295
+ if focus ~= "all" then
7296
+ table.insert(qualityNotes, "focus filters events before stack aggregation; exclusive_us is exclusive within emitted focused events, not the full snapshot.")
7297
+ end
7298
+ if historyTruncated then
7299
+ local _arg0 = `MicroProfiler kept only the newest {frameMax - firstCaptureFrame + 1} frames of this capture (its memory budget filled; {framesEvicted} earlier frames were dropped), so the analysis covers {roundUs(analysisDurationMs)} ms of the {roundUs(captureWallMs)} ms capture. Times and rates are correct for that span; use a shorter duration_ms to analyze the whole capture.`
7300
+ table.insert(qualityNotes, _arg0)
7301
+ end
7302
+ if eventLimitHit then
7303
+ local _arg0 = `Analysis stopped at max_events ({maxEvents} events), so it covers {roundUs(analysisDurationMs)} ms of the {roundUs(captureWallMs)} ms capture. Raise max_events or shorten duration_ms to analyze all of it.`
7304
+ table.insert(qualityNotes, _arg0)
7305
+ end
7306
+ if coverageShort then
7307
+ local cause = if frameWindowLimited then ` The default frame_window ({frameWindow} frames) kept only the newest {framesConsidered} frames; pass a larger frame_window (the engine holds at most {HISTORY_FRAME_LIMIT}) or a shorter duration_ms.` else ""
7308
+ local _arg0 = `The analyzed frames cover {roundUs(analysisDurationMs)} ms of the {roundUs(captureWallMs)} ms capture. Times and rates are correct for that span.{cause}`
7309
+ table.insert(qualityNotes, _arg0)
7310
+ end
6457
7311
  local comparisonIndex
6458
7312
  if includeComparisonIndex then
6459
7313
  local timerFields = { "timer_id", "name", "group", "inclusive_us", "inclusive_us_per_s", "exclusive_us", "count", "count_per_s", "active_frame_count", "inclusive_us_per_frame", "max_frame_inclusive_us", "max_frame_id" }
@@ -6492,13 +7346,20 @@ local function captureMicroProfiler(requestData)
6492
7346
  }
6493
7347
  end
6494
7348
  local _object = {
6495
- schema_version = 1,
7349
+ schema_version = 2,
6496
7350
  ok = true,
6497
7351
  duration_ms = durationMs,
6498
7352
  target = targetRole,
6499
7353
  scope = "micro_profiler",
6500
7354
  time_unit = "microseconds",
6501
- time_basis = "LibMP MicroProfiler timestamps converted from nanosecond ticks. inclusive_us is cumulative nested timer time and can overlap across nested timers/threads; do not sum rows as total frame time.",
7355
+ time_basis = "MicroProfiler ticks converted with the snapshot's clock (GlobalDesc TickToMsCpu; TickToMsGpu for the GPU thread). inclusive_us is cumulative nested timer time and can overlap across nested timers/threads; do not sum rows as total frame time.",
7356
+ clock = {
7357
+ tick_to_ms_cpu = tickToMsCpu,
7358
+ tick_to_ms_gpu = tickToMsGpu,
7359
+ },
7360
+ capture_state = {
7361
+ was_recording = prior.recording,
7362
+ },
6502
7363
  }
6503
7364
  local _left = "analysis_window"
6504
7365
  local _object_1 = {
@@ -6506,6 +7367,7 @@ local function captureMicroProfiler(requestData)
6506
7367
  analysis_duration_us = analysisDurationUs,
6507
7368
  snapshot_frame_min = frameMin,
6508
7369
  snapshot_frame_max = frameMax,
7370
+ capture_start_frame = firstCaptureFrame,
6509
7371
  selected_frame_min = startFrame,
6510
7372
  selected_frame_max = frameMax,
6511
7373
  selected_frame_count = framesConsidered,
@@ -6525,17 +7387,21 @@ local function captureMicroProfiler(requestData)
6525
7387
  _object_1[_left_1] = _size_1
6526
7388
  _object_1.selected_frame_event_coverage_pct = sampledFrameCoveragePct
6527
7389
  _object_1.frame_window = frameWindow
7390
+ _object_1.capture_wall_ms = round2(captureWallMs)
7391
+ _object_1.first_frame_wait_ms = round2(firstFrameWaitMs)
7392
+ _object_1.coverage_pct = percent(analysisDurationMs, captureWallMs)
7393
+ _object_1.frames_evicted = framesEvicted
6528
7394
  _object[_left] = _object_1
6529
7395
  local _left_2 = "applied"
6530
7396
  local _object_2 = {
6531
7397
  focus = focus,
6532
7398
  }
6533
7399
  local _left_3 = "filter"
6534
- local _condition_5 = filter
6535
- if _condition_5 == nil then
6536
- _condition_5 = nil
7400
+ local _condition_6 = filter
7401
+ if _condition_6 == nil then
7402
+ _condition_6 = nil
6537
7403
  end
6538
- _object_2[_left_3] = _condition_5
7404
+ _object_2[_left_3] = _condition_6
6539
7405
  _object_2.include_idle = includeIdle
6540
7406
  _object_2.include_gpu = includeGpu
6541
7407
  _object_2.min_total_us = minTotalUs
@@ -6574,7 +7440,7 @@ local function captureMicroProfiler(requestData)
6574
7440
  _object_3.open_stack_entries_at_end = openStackEntriesAtEnd
6575
7441
  _object_3.iterator_finished = iteratorFinished
6576
7442
  _object_3.last_processed_frame_id = lastProcessedFrameId
6577
- _object_3.last_processed_timestamp_us = if lastProcessedTimestampRaw ~= nil then rawToUs(lastProcessedTimestampRaw) else nil
7443
+ _object_3.last_processed_timestamp_us = if lastProcessedTimestampUs ~= nil then roundUs(lastProcessedTimestampUs) else nil
6578
7444
  _object_3.event_limit_hit = eventsSampled >= maxEvents
6579
7445
  _object[_left_4] = _object_3
6580
7446
  _object.frame_summary = frameSummary
@@ -6591,9 +7457,10 @@ local function captureMicroProfiler(requestData)
6591
7457
  dropped_spans = droppedSpans,
6592
7458
  open_stack_entries_at_end = openStackEntriesAtEnd,
6593
7459
  selected_frame_event_coverage_pct = sampledFrameCoveragePct,
7460
+ history_truncated = historyTruncated,
6594
7461
  partial = #partialReasons > 0,
6595
7462
  partial_reasons = partialReasons,
6596
- notes = if focus ~= "all" then { "focus filters events before stack aggregation; exclusive_us is exclusive within emitted focused events, not the full snapshot." } else nil,
7463
+ notes = if #qualityNotes > 0 then qualityNotes else nil,
6597
7464
  }
6598
7465
  _object.recommended_tools = recommendedToolsForGroups(topGroups, targetRole)
6599
7466
  local result = _object
@@ -6748,9 +7615,11 @@ local TS = require(script.Parent.Parent.Parent.include.RuntimeLib)
6748
7615
  local Utils = TS.import(script, script.Parent.Parent, "Utils")
6749
7616
  local CooperativeJobRunner = TS.import(script, script.Parent.Parent, "CooperativeJobRunner")
6750
7617
  local ScriptSearch = TS.import(script, script.Parent.Parent, "ScriptSearch")
7618
+ local InstanceSearch = TS.import(script, script.Parent.Parent, "InstanceSearch")
6751
7619
  local _binding = Utils
6752
7620
  local getInstancePath = _binding.getInstancePath
6753
7621
  local getInstanceByPath = _binding.getInstanceByPath
7622
+ local createPathAmbiguityChecker = _binding.createPathAmbiguityChecker
6754
7623
  local readScriptSource = _binding.readScriptSource
6755
7624
  local function getFileTree(requestData)
6756
7625
  local _condition = (requestData.path)
@@ -6876,62 +7745,42 @@ local function getPlaceInfo(_requestData)
6876
7745
  },
6877
7746
  }
6878
7747
  end
6879
- local function searchObjects(requestData)
6880
- local query = requestData.query
6881
- local _condition = (requestData.searchType)
6882
- if _condition == nil then
6883
- _condition = "name"
6884
- end
6885
- local searchType = _condition
6886
- local propertyName = requestData.propertyName
6887
- if not (query ~= "" and query) then
6888
- return {
6889
- error = "Query is required",
6890
- }
6891
- end
6892
- local results = {}
6893
- local function searchRecursive(instance)
6894
- local match = false
6895
- if searchType == "name" then
6896
- local _exp = string.lower(instance.Name)
6897
- local _arg0 = string.lower(query)
6898
- match = (string.find(_exp, _arg0)) ~= nil
6899
- elseif searchType == "class" then
6900
- local _exp = string.lower(instance.ClassName)
6901
- local _arg0 = string.lower(query)
6902
- match = (string.find(_exp, _arg0)) ~= nil
6903
- else
6904
- local _value = searchType == "property" and propertyName
6905
- if _value ~= "" and _value then
6906
- local success, value = pcall(function()
6907
- return tostring(instance[propertyName])
6908
- end)
6909
- if success then
6910
- local _exp = string.lower(value)
6911
- local _arg0 = string.lower(query)
6912
- match = (string.find(_exp, _arg0)) ~= nil
6913
- end
6914
- end
6915
- end
6916
- if match then
6917
- local _arg0 = {
6918
- name = instance.Name,
6919
- className = instance.ClassName,
6920
- path = getInstancePath(instance),
6921
- }
6922
- table.insert(results, _arg0)
6923
- end
6924
- for _, child in instance:GetChildren() do
6925
- searchRecursive(child)
6926
- end
7748
+ local instanceSearch = InstanceSearch.createInstanceSearch({
7749
+ resolveRoot = getInstanceByPath,
7750
+ getChildren = function(instance)
7751
+ return instance:GetChildren()
7752
+ end,
7753
+ getName = function(instance)
7754
+ return instance.Name
7755
+ end,
7756
+ getClassName = function(instance)
7757
+ return instance.ClassName
7758
+ end,
7759
+ isA = function(instance, className)
7760
+ return instance:IsA(className)
7761
+ end,
7762
+ readPropertyText = function(instance, propertyName)
7763
+ local success, value = pcall(function()
7764
+ return tostring(instance[propertyName])
7765
+ end)
7766
+ return if success then value else nil
7767
+ end,
7768
+ getPath = getInstancePath,
7769
+ createAmbiguityChecker = createPathAmbiguityChecker,
7770
+ })
7771
+ local function searchObjects(requestData, execution)
7772
+ -- Keyed per request: concurrent searches are independent reads, so the
7773
+ -- runner is used only for yielding, deadlines and cancellation.
7774
+ local result = CooperativeJobRunner.runExclusive(`instance-search:{execution.requestId}`, execution, function(control)
7775
+ return instanceSearch.search(requestData, control)
7776
+ end)
7777
+ if result.error == "deadline_exceeded" then
7778
+ local _object = table.clone(result)
7779
+ setmetatable(_object, nil)
7780
+ _object.message = "search_objects exceeded its bridge deadline before the scan completed. Narrow it with path or className."
7781
+ return _object
6927
7782
  end
6928
- searchRecursive(game)
6929
- return {
6930
- results = results,
6931
- query = query,
6932
- searchType = searchType,
6933
- count = #results,
6934
- }
7783
+ return result
6935
7784
  end
6936
7785
  local function getInstanceProperties(requestData)
6937
7786
  local instancePath = requestData.instancePath
@@ -7199,9 +8048,10 @@ local function getProjectStructure(requestData)
7199
8048
  error = `Path not found: {startPath}`,
7200
8049
  }
7201
8050
  end
8051
+ local isAmbiguous = createPathAmbiguityChecker()
7202
8052
  local function getStructure(instance, depth)
7203
8053
  if depth > maxDepth then
7204
- return {
8054
+ local truncatedNode = {
7205
8055
  name = instance.Name,
7206
8056
  className = instance.ClassName,
7207
8057
  path = getInstancePath(instance),
@@ -7209,12 +8059,19 @@ local function getProjectStructure(requestData)
7209
8059
  hasMore = true,
7210
8060
  note = "Max depth reached - use this path to explore further",
7211
8061
  }
8062
+ if isAmbiguous(instance) then
8063
+ truncatedNode.ambiguous = true
8064
+ end
8065
+ return truncatedNode
7212
8066
  end
7213
8067
  local node = {
7214
8068
  name = instance.Name,
7215
8069
  className = instance.ClassName,
7216
8070
  path = getInstancePath(instance),
7217
8071
  }
8072
+ if isAmbiguous(instance) then
8073
+ node.ambiguous = true
8074
+ end
7218
8075
  if instance:IsA("LuaSourceContainer") then
7219
8076
  node.hasSource = true
7220
8077
  node.scriptType = instance.ClassName
@@ -7344,6 +8201,9 @@ local scriptSearch = ScriptSearch.createScriptSearch({
7344
8201
  resolveRoot = function(self, path)
7345
8202
  return getInstanceByPath(path)
7346
8203
  end,
8204
+ createAmbiguityChecker = function(self)
8205
+ return createPathAmbiguityChecker()
8206
+ end,
7347
8207
  getChildren = function(self, instance)
7348
8208
  return instance:GetChildren()
7349
8209
  end,
@@ -7651,9 +8511,14 @@ return {
7651
8511
  local TS = require(script.Parent.Parent.Parent.include.RuntimeLib)
7652
8512
  local Utils = TS.import(script, script.Parent.Parent, "Utils")
7653
8513
  local Recording = TS.import(script, script.Parent.Parent, "Recording")
8514
+ local ScriptReplace = TS.import(script, script.Parent.Parent, "ScriptReplace")
8515
+ local _ScriptEdits = TS.import(script, script.Parent.Parent, "ScriptEdits")
8516
+ local planScriptEdits = _ScriptEdits.planScriptEdits
8517
+ local sourceRevision = _ScriptEdits.sourceRevision
7654
8518
  local _binding = Utils
7655
8519
  local getInstancePath = _binding.getInstancePath
7656
8520
  local getInstanceByPath = _binding.getInstanceByPath
8521
+ local createPathAmbiguityChecker = _binding.createPathAmbiguityChecker
7657
8522
  local readScriptSource = _binding.readScriptSource
7658
8523
  local applyScriptSource = _binding.applyScriptSource
7659
8524
  local splitLines = _binding.splitLines
@@ -7766,6 +8631,7 @@ local function getScriptSource(requestData)
7766
8631
  numberedSource = numberLines(selectedLines, returnedStartLine),
7767
8632
  sourceLength = #fullSource,
7768
8633
  lineCount = totalLineCount,
8634
+ revision = sourceRevision(fullSource),
7769
8635
  startLine = returnedStartLine,
7770
8636
  endLine = returnedEndLine,
7771
8637
  isPartial = explicitRange,
@@ -7788,14 +8654,45 @@ local function getScriptSource(requestData)
7788
8654
  }
7789
8655
  end
7790
8656
  end
8657
+ -- The revision_mismatch response shared by every revision-checked script
8658
+ -- write, or undefined when no revision was expected or it still matches.
8659
+ local function revisionMismatch(instancePath, source, expectedRevision)
8660
+ if expectedRevision == nil then
8661
+ return nil
8662
+ end
8663
+ local revision = sourceRevision(source)
8664
+ if revision == expectedRevision then
8665
+ return nil
8666
+ end
8667
+ return {
8668
+ error = "Script changed since expected_revision; read it again with get_script_source and retry.",
8669
+ code = "revision_mismatch",
8670
+ instancePath = instancePath,
8671
+ expectedRevision = expectedRevision,
8672
+ revision = revision,
8673
+ }
8674
+ end
8675
+ local function readExpectedRevision(requestData)
8676
+ local expectedRevision = requestData.expectedRevision
8677
+ if expectedRevision == nil then
8678
+ return nil
8679
+ end
8680
+ return if type(expectedRevision) == "string" and expectedRevision ~= "" then expectedRevision else false
8681
+ end
7791
8682
  local function setScriptSource(requestData)
7792
8683
  local instancePath = requestData.instancePath
7793
8684
  local newSource = requestData.source
8685
+ local expectedRevision = readExpectedRevision(requestData)
7794
8686
  if not (instancePath ~= "" and instancePath) or not (type(newSource) == "string") then
7795
8687
  return {
7796
8688
  error = "Instance path and source are required",
7797
8689
  }
7798
8690
  end
8691
+ if expectedRevision == false then
8692
+ return {
8693
+ error = "expectedRevision must be a nonempty string",
8694
+ }
8695
+ end
7799
8696
  local instance = getInstanceByPath(instancePath)
7800
8697
  if not instance then
7801
8698
  return {
@@ -7809,25 +8706,31 @@ local function setScriptSource(requestData)
7809
8706
  end
7810
8707
  -- Communication has already JSON-decoded the transport payload; source text is exact at this boundary.
7811
8708
  local sourceToSet = newSource
7812
- local recordingId = beginRecording(`Set script source: {instance.Name}`)
7813
8709
  local readSuccess, readResult = pcall(function()
7814
- return #readScriptSource(instance)
8710
+ return readScriptSource(instance)
7815
8711
  end)
7816
8712
  if not readSuccess then
7817
- finishRecording(recordingId, false)
7818
8713
  return {
7819
8714
  error = `Failed to read script source before updating: {readResult}`,
7820
8715
  }
7821
8716
  end
7822
- local oldSourceLength = readResult
7823
- local applyResult = applyScriptSource(instance, sourceToSet)
8717
+ local oldSource = readResult
8718
+ local mismatch = revisionMismatch(instancePath, oldSource, expectedRevision)
8719
+ if mismatch then
8720
+ return mismatch
8721
+ end
8722
+ local recordingId = beginRecording(`Set script source: {instance.Name}`)
8723
+ -- A revision-checked replacement is a compare-and-set against the checked text,
8724
+ -- so a draft typed while UpdateSourceAsync yields is not overwritten.
8725
+ local applyResult = if expectedRevision == nil then applyScriptSource(instance, sourceToSet) else applyScriptSource(instance, sourceToSet, oldSource)
7824
8726
  if applyResult.success then
7825
8727
  finishRecording(recordingId, true)
7826
8728
  return {
7827
8729
  success = true,
7828
8730
  instancePath = instancePath,
7829
- oldSourceLength = oldSourceLength,
8731
+ oldSourceLength = #oldSource,
7830
8732
  newSourceLength = #sourceToSet,
8733
+ revision = sourceRevision(sourceToSet),
7831
8734
  method = applyResult.method,
7832
8735
  message = `Script source updated successfully ({if applyResult.method == "UpdateSourceAsync" then "editor-safe" else "direct assignment"})`,
7833
8736
  }
@@ -7837,14 +8740,74 @@ local function setScriptSource(requestData)
7837
8740
  error = `Failed to set script source: {applyResult.error}`,
7838
8741
  }
7839
8742
  end
8743
+ -- Accepts the batched `edits` array or the single top-level old_string form.
8744
+ local function readScriptEdits(requestData)
8745
+ local rawEdits = requestData.edits
8746
+ if rawEdits == nil then
8747
+ local oldString = requestData.old_string
8748
+ local newString = requestData.new_string
8749
+ local startLine = requestData.startLine
8750
+ if not (type(oldString) == "string") or not (type(newString) == "string") then
8751
+ return "Instance path, old_string, and new_string are required"
8752
+ end
8753
+ if startLine ~= nil and not (type(startLine) == "number") then
8754
+ return "startLine must be a number"
8755
+ end
8756
+ return { {
8757
+ oldString = oldString,
8758
+ newString = newString,
8759
+ startLine = startLine,
8760
+ } }
8761
+ end
8762
+ if not (type(rawEdits) == "table") then
8763
+ return "edits must be an array"
8764
+ end
8765
+ local edits = {}
8766
+ for _, rawEdit in rawEdits do
8767
+ local index = #edits
8768
+ if not (type(rawEdit) == "table") then
8769
+ return `edits[{index}] must be an object`
8770
+ end
8771
+ local fields = rawEdit
8772
+ local oldString = fields.old_string
8773
+ local newString = fields.new_string
8774
+ local startLine = fields.startLine
8775
+ if not (type(oldString) == "string") or not (type(newString) == "string") then
8776
+ return `edits[{index}] requires old_string and new_string`
8777
+ end
8778
+ if startLine ~= nil and not (type(startLine) == "number") then
8779
+ return `edits[{index}].startLine must be a number`
8780
+ end
8781
+ local _arg0 = {
8782
+ oldString = oldString,
8783
+ newString = newString,
8784
+ startLine = startLine,
8785
+ }
8786
+ table.insert(edits, _arg0)
8787
+ end
8788
+ if #edits == 0 then
8789
+ return "edits must contain at least one edit"
8790
+ end
8791
+ return edits
8792
+ end
7840
8793
  local function editScriptLines(requestData)
7841
8794
  local instancePath = requestData.instancePath
7842
- local oldString = requestData.old_string
7843
- local newString = requestData.new_string
7844
- local startLine = requestData.startLine
7845
- if not (instancePath ~= "" and instancePath) or oldString == nil or newString == nil then
8795
+ local expectedRevision = requestData.expectedRevision
8796
+ local dryRun = requestData.dryRun == true
8797
+ if not (instancePath ~= "" and instancePath) then
8798
+ return {
8799
+ error = "Instance path is required",
8800
+ }
8801
+ end
8802
+ local edits = readScriptEdits(requestData)
8803
+ if type(edits) == "string" then
7846
8804
  return {
7847
- error = "Instance path, old_string, and new_string are required",
8805
+ error = edits,
8806
+ }
8807
+ end
8808
+ if expectedRevision ~= nil and not (type(expectedRevision) == "string") then
8809
+ return {
8810
+ error = "expectedRevision must be a string",
7848
8811
  }
7849
8812
  end
7850
8813
  local instance = getInstanceByPath(instancePath)
@@ -7858,76 +8821,58 @@ local function editScriptLines(requestData)
7858
8821
  error = `Instance is not a script-like object: {instance.ClassName}`,
7859
8822
  }
7860
8823
  end
7861
- local recordingId = beginRecording(`Edit script: {instance.Name}`)
7862
- local success, result = pcall(function()
7863
- local source = readScriptSource(instance)
7864
- local searchLen = #oldString
7865
- local matchStart
7866
- if startLine ~= nil then
7867
- if startLine < 1 then
7868
- error(`startLine must be >= 1 (got {startLine})`)
7869
- end
7870
- local lineStartByte = 1
7871
- local currentLine = 1
7872
- while currentLine < startLine do
7873
- local nlPos = string.find(source, "\n", lineStartByte, true)
7874
- if nlPos == nil then
7875
- error(`startLine {startLine} is past end of script ({currentLine} lines)`)
7876
- end
7877
- lineStartByte = nlPos + 1
7878
- currentLine += 1
7879
- end
7880
- local candidate = string.sub(source, lineStartByte, lineStartByte + searchLen - 1)
7881
- if candidate ~= oldString then
7882
- error(`old_string does not match at line {startLine}. Use get_script_source to verify the exact text at that line.`)
7883
- end
7884
- matchStart = lineStartByte
7885
- else
7886
- local count = 0
7887
- local searchPos = 1
7888
- local firstMatch
7889
- while true do
7890
- local foundStart = string.find(source, oldString, searchPos, true)
7891
- if foundStart == nil then
7892
- break
7893
- end
7894
- if firstMatch == nil then
7895
- firstMatch = foundStart
7896
- end
7897
- count += 1
7898
- if count > 1 then
7899
- break
7900
- end
7901
- searchPos = foundStart + searchLen
7902
- end
7903
- if count == 0 then
7904
- error("old_string not found in script. If old_string contains repeated patterns (e.g. closing braces), pass startLine to anchor the edit.")
7905
- end
7906
- if count > 1 then
7907
- error("old_string matches multiple locations. Provide more surrounding context, or pass startLine to anchor the edit to a specific line.")
7908
- end
7909
- matchStart = firstMatch
7910
- end
7911
- -- Byte-slice replacement avoids Lua pattern escaping (safe for multi-byte chars like em dashes).
7912
- local newSource = string.sub(source, 1, matchStart - 1) .. newString .. string.sub(source, matchStart + searchLen)
7913
- local applyResult = applyScriptSource(instance, newSource, source)
7914
- if not applyResult.success then
7915
- error(applyResult.error)
7916
- end
8824
+ local readSuccess, readResult = pcall(function()
8825
+ return readScriptSource(instance)
8826
+ end)
8827
+ if not readSuccess then
8828
+ return {
8829
+ error = `Failed to edit script: {readResult}`,
8830
+ }
8831
+ end
8832
+ local source = readResult
8833
+ local revision = sourceRevision(source)
8834
+ local mismatch = revisionMismatch(instancePath, source, expectedRevision)
8835
+ if mismatch then
8836
+ return mismatch
8837
+ end
8838
+ local plan = planScriptEdits(source, edits, dryRun)
8839
+ if not plan.ok then
7917
8840
  return {
8841
+ error = `Failed to edit script: {plan.error}`,
8842
+ }
8843
+ end
8844
+ if dryRun then
8845
+ local preview = {
7918
8846
  success = true,
8847
+ dryRun = true,
7919
8848
  instancePath = instancePath,
7920
- method = applyResult.method,
7921
- message = "Script edited successfully",
8849
+ editCount = #edits,
8850
+ revision = revision,
8851
+ resultRevision = sourceRevision(plan.newSource),
8852
+ diff = plan.diff,
7922
8853
  }
7923
- end)
7924
- if success then
7925
- finishRecording(recordingId, true)
7926
- return result
8854
+ if plan.diffTruncated then
8855
+ preview.diffTruncated = true
8856
+ end
8857
+ return preview
7927
8858
  end
7928
- finishRecording(recordingId, false)
8859
+ local recordingId = beginRecording(if #edits > 1 then `Edit script ({#edits} edits): {instance.Name}` else `Edit script: {instance.Name}`)
8860
+ -- One compare-and-set write: a draft typed since the read rejects the whole batch.
8861
+ local applyResult = applyScriptSource(instance, plan.newSource, source)
8862
+ if not applyResult.success then
8863
+ finishRecording(recordingId, false)
8864
+ return {
8865
+ error = `Failed to edit script: {applyResult.error}`,
8866
+ }
8867
+ end
8868
+ finishRecording(recordingId, true)
7929
8869
  return {
7930
- error = `Failed to edit script: {result}`,
8870
+ success = true,
8871
+ instancePath = instancePath,
8872
+ editCount = #edits,
8873
+ revision = sourceRevision(plan.newSource),
8874
+ method = applyResult.method,
8875
+ message = "Script edited successfully",
7931
8876
  }
7932
8877
  end
7933
8878
  local function insertScriptLines(requestData)
@@ -7938,11 +8883,17 @@ local function insertScriptLines(requestData)
7938
8883
  end
7939
8884
  local afterLine = _condition
7940
8885
  local newContent = requestData.newContent
8886
+ local expectedRevision = readExpectedRevision(requestData)
7941
8887
  if not (instancePath ~= "" and instancePath) or not (newContent ~= "" and newContent) then
7942
8888
  return {
7943
8889
  error = "Instance path and newContent are required",
7944
8890
  }
7945
8891
  end
8892
+ if expectedRevision == false then
8893
+ return {
8894
+ error = "expectedRevision must be a nonempty string",
8895
+ }
8896
+ end
7946
8897
  local instance = getInstanceByPath(instancePath)
7947
8898
  if not instance then
7948
8899
  return {
@@ -7954,9 +8905,21 @@ local function insertScriptLines(requestData)
7954
8905
  error = `Instance is not a script-like object: {instance.ClassName}`,
7955
8906
  }
7956
8907
  end
8908
+ local readSuccess, readResult = pcall(function()
8909
+ return readScriptSource(instance)
8910
+ end)
8911
+ if not readSuccess then
8912
+ return {
8913
+ error = `Failed to insert script lines: {readResult}`,
8914
+ }
8915
+ end
8916
+ local source = readResult
8917
+ local mismatch = revisionMismatch(instancePath, source, expectedRevision)
8918
+ if mismatch then
8919
+ return mismatch
8920
+ end
7957
8921
  local recordingId = beginRecording(`Insert script lines after line {afterLine}: {instance.Name}`)
7958
8922
  local success, result = pcall(function()
7959
- local source = readScriptSource(instance)
7960
8923
  local lines, hadTrailingNewline = splitLines(source)
7961
8924
  local totalLines = #lines
7962
8925
  if afterLine < 0 or afterLine > totalLines then
@@ -8010,6 +8973,7 @@ local function insertScriptLines(requestData)
8010
8973
  insertedAfterLine = afterLine,
8011
8974
  linesInserted = #newLines,
8012
8975
  newLineCount = #resultLines,
8976
+ revision = sourceRevision(newSource),
8013
8977
  method = applyResult.method,
8014
8978
  message = "Script lines inserted successfully",
8015
8979
  }
@@ -8027,11 +8991,17 @@ local function deleteScriptLines(requestData)
8027
8991
  local instancePath = requestData.instancePath
8028
8992
  local startLine = requestData.startLine
8029
8993
  local endLine = requestData.endLine
8994
+ local expectedRevision = readExpectedRevision(requestData)
8030
8995
  if not (instancePath ~= "" and instancePath) or not (startLine ~= 0 and startLine == startLine and startLine) or not (endLine ~= 0 and endLine == endLine and endLine) then
8031
8996
  return {
8032
8997
  error = "Instance path, startLine, and endLine are required",
8033
8998
  }
8034
8999
  end
9000
+ if expectedRevision == false then
9001
+ return {
9002
+ error = "expectedRevision must be a nonempty string",
9003
+ }
9004
+ end
8035
9005
  local instance = getInstanceByPath(instancePath)
8036
9006
  if not instance then
8037
9007
  return {
@@ -8043,9 +9013,23 @@ local function deleteScriptLines(requestData)
8043
9013
  error = `Instance is not a script-like object: {instance.ClassName}`,
8044
9014
  }
8045
9015
  end
9016
+ local readSuccess, readResult = pcall(function()
9017
+ return readScriptSource(instance)
9018
+ end)
9019
+ if not readSuccess then
9020
+ return {
9021
+ error = `Failed to delete script lines: {readResult}`,
9022
+ }
9023
+ end
9024
+ local source = readResult
9025
+ -- Line numbers name different text once the script changes; a revision
9026
+ -- keeps a retried delete from removing lines it never saw.
9027
+ local mismatch = revisionMismatch(instancePath, source, expectedRevision)
9028
+ if mismatch then
9029
+ return mismatch
9030
+ end
8046
9031
  local recordingId = beginRecording(`Delete script lines {startLine}-{endLine}: {instance.Name}`)
8047
9032
  local success, result = pcall(function()
8048
- local source = readScriptSource(instance)
8049
9033
  local lines, hadTrailingNewline = splitLines(source)
8050
9034
  local totalLines = #lines
8051
9035
  if startLine < 1 or startLine > totalLines then
@@ -8101,6 +9085,7 @@ local function deleteScriptLines(requestData)
8101
9085
  },
8102
9086
  linesDeleted = endLine - startLine + 1,
8103
9087
  newLineCount = #resultLines,
9088
+ revision = sourceRevision(newSource),
8104
9089
  method = applyResult.method,
8105
9090
  message = "Script lines deleted successfully",
8106
9091
  }
@@ -8114,196 +9099,43 @@ local function deleteScriptLines(requestData)
8114
9099
  error = `Failed to delete script lines: {result}`,
8115
9100
  }
8116
9101
  end
8117
- local function escapeLuaPattern(s)
8118
- return (string.gsub(s, "([%(%)%.%%%+%-%*%?%[%]%^%$])", "%%%1"))
8119
- end
8120
- local function escapeLuaReplacement(s)
8121
- return (string.gsub(s, "%%", "%%%%"))
8122
- end
8123
- local function caseInsensitiveLiteralReplace(src, searchStr, repl)
8124
- local lowerSrc = string.lower(src)
8125
- local lowerSearch = string.lower(searchStr)
8126
- local parts = {}
8127
- local lastEnd = 1
8128
- local searchLen = #lowerSearch
8129
- local pos = 1
8130
- local replCount = 0
8131
- while true do
8132
- local foundStart = string.find(lowerSrc, lowerSearch, pos, true)
8133
- if foundStart == nil then
8134
- break
8135
- end
8136
- local _arg0 = string.sub(src, lastEnd, foundStart - 1)
8137
- table.insert(parts, _arg0)
8138
- local _repl = repl
8139
- table.insert(parts, _repl)
8140
- lastEnd = foundStart + searchLen
8141
- pos = foundStart + searchLen
8142
- replCount += 1
8143
- end
8144
- local _arg0 = string.sub(src, lastEnd)
8145
- table.insert(parts, _arg0)
8146
- return { table.concat(parts, ""), replCount }
8147
- end
8148
- local function findAndReplaceInScripts(requestData)
8149
- local searchPattern = requestData.pattern
8150
- local replacement = requestData.replacement
8151
- if not (searchPattern ~= "" and searchPattern) then
8152
- return {
8153
- error = "pattern is required",
8154
- }
8155
- end
8156
- if replacement == nil then
8157
- return {
8158
- error = "replacement is required",
8159
- }
8160
- end
8161
- local _condition = (requestData.caseSensitive)
8162
- if _condition == nil then
8163
- _condition = false
8164
- end
8165
- local caseSensitive = _condition
8166
- local _condition_1 = (requestData.usePattern)
8167
- if _condition_1 == nil then
8168
- _condition_1 = false
8169
- end
8170
- local usePattern = _condition_1
8171
- local _condition_2 = (requestData.path)
8172
- if _condition_2 == nil then
8173
- _condition_2 = ""
8174
- end
8175
- local searchPath = _condition_2
8176
- local classFilter = requestData.classFilter
8177
- local _condition_3 = (requestData.dryRun)
8178
- if _condition_3 == nil then
8179
- _condition_3 = false
8180
- end
8181
- local dryRun = _condition_3
8182
- local _condition_4 = (requestData.maxReplacements)
8183
- if _condition_4 == nil then
8184
- _condition_4 = 1000
8185
- end
8186
- local maxReplacements = _condition_4
8187
- if not caseSensitive and usePattern then
8188
- return {
8189
- error = "Case-insensitive Lua pattern replacement is not supported. Use caseSensitive: true with usePattern: true, or use literal matching.",
8190
- }
8191
- end
8192
- local startInstance = if searchPath ~= "" then getInstanceByPath(searchPath) else game
8193
- if not startInstance then
8194
- return {
8195
- error = `Path not found: {searchPath}`,
8196
- }
8197
- end
8198
- local changes = {}
8199
- local totalReplacements = 0
8200
- local scriptsSearched = 0
8201
- local hitLimit = false
8202
- local recordingId = if dryRun then nil else beginRecording("Find and replace in scripts")
8203
- local function processInstance(instance)
8204
- if hitLimit then
9102
+ local scriptReplace = ScriptReplace.createScriptReplace({
9103
+ resolvePath = function(self, path)
9104
+ return if path == "" then game else getInstanceByPath(path)
9105
+ end,
9106
+ getChildren = function(self, instance)
9107
+ return instance:GetChildren()
9108
+ end,
9109
+ readScript = function(self, instance, classFilter)
9110
+ if not instance:IsA("LuaSourceContainer") then
8205
9111
  return nil
8206
9112
  end
8207
- local _condition_5 = classFilter == nil
8208
- if not _condition_5 then
8209
- local _exp = string.lower(instance.ClassName)
8210
- local _arg0 = string.lower(classFilter)
8211
- _condition_5 = (string.find(_exp, _arg0)) ~= nil
8212
- end
8213
- local matchesClass = _condition_5
8214
- if instance:IsA("LuaSourceContainer") and matchesClass then
8215
- scriptsSearched += 1
8216
- local source = readScriptSource(instance)
8217
- local newSource
8218
- local replCount
8219
- if usePattern then
8220
- local result, count = string.gsub(source, searchPattern, replacement)
8221
- newSource = result
8222
- replCount = count
8223
- elseif caseSensitive then
8224
- local escaped = escapeLuaPattern(searchPattern)
8225
- local escapedRepl = escapeLuaReplacement(replacement)
8226
- local result, count = string.gsub(source, escaped, escapedRepl)
8227
- newSource = result
8228
- replCount = count
8229
- else
8230
- local _binding_2 = caseInsensitiveLiteralReplace(source, searchPattern, replacement)
8231
- newSource = _binding_2[1]
8232
- replCount = _binding_2[2]
8233
- end
8234
- if replCount > 0 then
8235
- if totalReplacements + replCount > maxReplacements then
8236
- hitLimit = true
8237
- return nil
8238
- end
8239
- local applyResult = if dryRun then nil else applyScriptSource(instance, newSource, source)
8240
- if applyResult ~= nil and not applyResult.success then
8241
- local _object = {
8242
- instancePath = getInstancePath(instance),
8243
- name = instance.Name,
8244
- className = instance.ClassName,
8245
- replacements = 0,
8246
- }
8247
- local _left = "error"
8248
- local _condition_6 = applyResult.error
8249
- if _condition_6 == nil then
8250
- _condition_6 = "Script write failed verification"
8251
- end
8252
- _object[_left] = _condition_6
8253
- table.insert(changes, _object)
8254
- else
8255
- totalReplacements += replCount
8256
- local _arg0 = {
8257
- instancePath = getInstancePath(instance),
8258
- name = instance.Name,
8259
- className = instance.ClassName,
8260
- replacements = replCount,
8261
- }
8262
- table.insert(changes, _arg0)
8263
- end
8264
- end
8265
- end
8266
- for _, child in instance:GetChildren() do
8267
- if hitLimit then
8268
- return nil
8269
- end
8270
- processInstance(child)
8271
- end
8272
- end
8273
- local traversalSuccess, traversalResult = pcall(function()
8274
- return processInstance(startInstance)
8275
- end)
8276
- -- ▼ ReadonlyArray.filter ▼
8277
- local _newValue = {}
8278
- local _callback = function(change)
8279
- return change.error ~= nil
8280
- end
8281
- local _length = 0
8282
- for _k, _v in changes do
8283
- if _callback(_v, _k - 1, changes) == true then
8284
- _length += 1
8285
- _newValue[_length] = _v
9113
+ if classFilter ~= nil and instance.ClassName ~= classFilter then
9114
+ return nil
8286
9115
  end
8287
- end
8288
- -- ▲ ReadonlyArray.filter ▲
8289
- local failedScripts = #_newValue
8290
- local scriptsModified = #changes - failedScripts
8291
- if recordingId ~= nil then
8292
- finishRecording(recordingId, scriptsModified > 0)
8293
- end
8294
- return {
8295
- success = traversalSuccess and failedScripts == 0,
8296
- error = if traversalSuccess then nil else `Script traversal failed: {traversalResult}`,
8297
- dryRun = dryRun,
8298
- pattern = searchPattern,
8299
- replacement = replacement,
8300
- totalReplacements = totalReplacements,
8301
- scriptsSearched = scriptsSearched,
8302
- scriptsModified = scriptsModified,
8303
- scriptsFailed = failedScripts,
8304
- changes = changes,
8305
- truncated = hitLimit,
8306
- }
9116
+ return {
9117
+ instancePath = getInstancePath(instance),
9118
+ name = instance.Name,
9119
+ className = instance.ClassName,
9120
+ source = readScriptSource(instance),
9121
+ }
9122
+ end,
9123
+ createAmbiguityChecker = function(self)
9124
+ return createPathAmbiguityChecker()
9125
+ end,
9126
+ writeScript = function(self, instance, newSource, expectedSource)
9127
+ -- Only planned scripts are written, and planning admits LuaSourceContainers only.
9128
+ return applyScriptSource(instance, newSource, expectedSource)
9129
+ end,
9130
+ beginRecording = function(self, label)
9131
+ return beginRecording(label)
9132
+ end,
9133
+ finishRecording = function(self, recording, commit)
9134
+ finishRecording(recording, commit)
9135
+ end,
9136
+ })
9137
+ local function findAndReplaceInScripts(requestData)
9138
+ return scriptReplace.run(requestData)
8307
9139
  end
8308
9140
  return {
8309
9141
  getScriptSource = getScriptSource,
@@ -9448,6 +10280,166 @@ return {
9448
10280
  </Properties>
9449
10281
  </Item>
9450
10282
  <Item class="ModuleScript" referent="27">
10283
+ <Properties>
10284
+ <string name="Name">InstanceSearch</string>
10285
+ <string name="Source"><![CDATA[-- Compiled with roblox-ts v3.0.0
10286
+ -- Bounded instance search behind search_objects. It walks one subtree in
10287
+ -- GetChildren order, applies an optional IsA filter, and stops after
10288
+ -- maxResults matches. An ambiguous `path` is reported by PathGuard before this
10289
+ -- runs. It is written against an injected corpus so it can run outside Studio.
10290
+ -- Function properties rather than methods, so plain functions can be assigned
10291
+ -- directly under roblox-ts.
10292
+ local SEARCH_TYPES = {
10293
+ ["name"] = true,
10294
+ ["class"] = true,
10295
+ ["property"] = true,
10296
+ }
10297
+ local DEFAULT_MAX_RESULTS = 100
10298
+ local MAX_RESULTS = 10000
10299
+ local function invalid(message)
10300
+ return {
10301
+ error = "invalid_request",
10302
+ message = message,
10303
+ }
10304
+ end
10305
+ local function containsText(haystack, needle)
10306
+ return (string.find(string.lower(haystack), needle, 1, true)) ~= nil
10307
+ end
10308
+ local function createInstanceSearch(corpus)
10309
+ local function search(requestData, control)
10310
+ local rawQuery = requestData.query
10311
+ if rawQuery ~= nil and not (type(rawQuery) == "string") then
10312
+ return invalid("query must be a string")
10313
+ end
10314
+ local _condition = rawQuery
10315
+ if _condition == nil then
10316
+ _condition = ""
10317
+ end
10318
+ local query = _condition
10319
+ local _condition_1 = requestData.searchType
10320
+ if _condition_1 == nil then
10321
+ _condition_1 = "name"
10322
+ end
10323
+ local rawSearchType = _condition_1
10324
+ if not (type(rawSearchType) == "string") or not (SEARCH_TYPES[rawSearchType] ~= nil) then
10325
+ return invalid("searchType must be one of name, class, property")
10326
+ end
10327
+ local searchType = rawSearchType
10328
+ local propertyName = requestData.propertyName
10329
+ if searchType == "property" and (not (type(propertyName) == "string") or propertyName == "") then
10330
+ return invalid("propertyName is required when searchType is property")
10331
+ end
10332
+ local className = requestData.className
10333
+ if className ~= nil and (not (type(className) == "string") or className == "") then
10334
+ return invalid("className must be a non-empty string")
10335
+ end
10336
+ if query == "" and className == nil then
10337
+ return {
10338
+ error = "query is required unless className is set",
10339
+ }
10340
+ end
10341
+ local requestedMaxResults = requestData.maxResults
10342
+ if requestedMaxResults ~= nil and (not (type(requestedMaxResults) == "number") or math.floor(requestedMaxResults) ~= requestedMaxResults or requestedMaxResults < 1 or requestedMaxResults > MAX_RESULTS) then
10343
+ return invalid(`maxResults must be an integer between 1 and {MAX_RESULTS}`)
10344
+ end
10345
+ local _condition_2 = requestedMaxResults
10346
+ if _condition_2 == nil then
10347
+ _condition_2 = DEFAULT_MAX_RESULTS
10348
+ end
10349
+ local maxResults = _condition_2
10350
+ local rawPath = requestData.path
10351
+ if rawPath ~= nil and not (type(rawPath) == "string") then
10352
+ return invalid("path must be a string")
10353
+ end
10354
+ local _condition_3 = rawPath
10355
+ if _condition_3 == nil then
10356
+ _condition_3 = ""
10357
+ end
10358
+ local searchPath = _condition_3
10359
+ local root = corpus.resolveRoot(searchPath)
10360
+ if root == nil then
10361
+ return {
10362
+ error = `Path not found: {searchPath}`,
10363
+ }
10364
+ end
10365
+ local needle = string.lower(query)
10366
+ local isAmbiguous = corpus.createAmbiguityChecker()
10367
+ local function matches(node)
10368
+ if className ~= nil and not corpus.isA(node, className) then
10369
+ return false
10370
+ end
10371
+ if needle == "" then
10372
+ return true
10373
+ end
10374
+ if searchType == "name" then
10375
+ return containsText(corpus.getName(node), needle)
10376
+ end
10377
+ if searchType == "class" then
10378
+ return containsText(corpus.getClassName(node), needle)
10379
+ end
10380
+ local text = corpus.readPropertyText(node, propertyName)
10381
+ return text ~= nil and containsText(text, needle)
10382
+ end
10383
+ local results = {}
10384
+ local stack = { root }
10385
+ local truncated = false
10386
+ while #stack > 0 do
10387
+ control:checkpoint()
10388
+ -- ▼ Array.pop ▼
10389
+ local _length = #stack
10390
+ local _result = stack[_length]
10391
+ stack[_length] = nil
10392
+ -- ▲ Array.pop ▲
10393
+ local node = _result
10394
+ if matches(node) then
10395
+ if #results >= maxResults then
10396
+ truncated = true
10397
+ break
10398
+ end
10399
+ local entry = {
10400
+ name = corpus.getName(node),
10401
+ className = corpus.getClassName(node),
10402
+ path = corpus.getPath(node),
10403
+ }
10404
+ if isAmbiguous(node) then
10405
+ entry.ambiguous = true
10406
+ end
10407
+ table.insert(results, entry)
10408
+ end
10409
+ local children = corpus.getChildren(node)
10410
+ for index = #children - 1, 0, -1 do
10411
+ local _arg0 = children[index + 1]
10412
+ table.insert(stack, _arg0)
10413
+ end
10414
+ end
10415
+ local response = {
10416
+ results = results,
10417
+ query = query,
10418
+ searchType = searchType,
10419
+ count = #results,
10420
+ truncated = truncated,
10421
+ maxResults = maxResults,
10422
+ path = corpus.getPath(root),
10423
+ }
10424
+ if searchType == "property" then
10425
+ response.propertyName = propertyName
10426
+ end
10427
+ if className ~= nil then
10428
+ response.className = className
10429
+ end
10430
+ return response
10431
+ end
10432
+ return {
10433
+ search = search,
10434
+ }
10435
+ end
10436
+ return {
10437
+ createInstanceSearch = createInstanceSearch,
10438
+ }
10439
+ ]]></string>
10440
+ </Properties>
10441
+ </Item>
10442
+ <Item class="ModuleScript" referent="28">
9451
10443
  <Properties>
9452
10444
  <string name="Name">LuauExec</string>
9453
10445
  <string name="Source"><![CDATA[-- Compiled with roblox-ts v3.0.0
@@ -9881,7 +10873,331 @@ return {
9881
10873
  ]]></string>
9882
10874
  </Properties>
9883
10875
  </Item>
9884
- <Item class="ModuleScript" referent="28">
10876
+ <Item class="ModuleScript" referent="29">
10877
+ <Properties>
10878
+ <string name="Name">PathAmbiguity</string>
10879
+ <string name="Source"><![CDATA[-- Compiled with roblox-ts v3.0.0
10880
+ -- Canonical instance paths address children by name, so siblings that share a
10881
+ -- name produce identical paths. This module resolves paths while reporting the
10882
+ -- first ambiguous segment, and marks emitted paths that cannot identify one
10883
+ -- instance. It is written against an injected tree so it can run outside Studio.
10884
+ local function findNamedChild(tree, parent, name)
10885
+ local first
10886
+ local count = 0
10887
+ for _, child in tree.getChildren(parent) do
10888
+ if tree.getName(child) == name then
10889
+ if first == nil then
10890
+ first = child
10891
+ end
10892
+ count += 1
10893
+ end
10894
+ end
10895
+ return { first, count }
10896
+ end
10897
+ -- Mirrors Utils.getInstanceByPath: the root segment prefers service lookup and
10898
+ -- later segments take the first child with a matching name. The resolved
10899
+ -- instance is returned even when ambiguous, so callers decide whether to refuse.
10900
+ local function resolvePath(tree, parts)
10901
+ if #parts == 0 then
10902
+ return {
10903
+ instance = tree.root,
10904
+ }
10905
+ end
10906
+ local ambiguity
10907
+ local current = tree.getService(parts[1])
10908
+ if current == nil then
10909
+ local _binding = findNamedChild(tree, tree.root, parts[1])
10910
+ local first = _binding[1]
10911
+ local count = _binding[2]
10912
+ current = first
10913
+ if count > 1 then
10914
+ ambiguity = {
10915
+ segment = parts[1],
10916
+ parentPath = tree.getPath(tree.root),
10917
+ matchCount = count,
10918
+ }
10919
+ end
10920
+ end
10921
+ for i = 1, #parts - 1 do
10922
+ if current == nil then
10923
+ break
10924
+ end
10925
+ local _binding = findNamedChild(tree, current, parts[i + 1])
10926
+ local first = _binding[1]
10927
+ local count = _binding[2]
10928
+ if count > 1 and ambiguity == nil then
10929
+ ambiguity = {
10930
+ segment = parts[i + 1],
10931
+ parentPath = tree.getPath(current),
10932
+ matchCount = count,
10933
+ }
10934
+ end
10935
+ current = first
10936
+ end
10937
+ return {
10938
+ instance = current,
10939
+ ambiguity = ambiguity,
10940
+ }
10941
+ end
10942
+ -- Returns a checker for one request. Sibling name counts and verdicts are
10943
+ -- cached per node, so marking many results under one parent stays linear.
10944
+ local function createAmbiguityChecker(tree)
10945
+ local nameCounts = {}
10946
+ local verdicts = {}
10947
+ local function countNamed(parent, name)
10948
+ local _parent = parent
10949
+ local counts = nameCounts[_parent]
10950
+ if counts == nil then
10951
+ counts = {}
10952
+ for _, child in tree.getChildren(parent) do
10953
+ local childName = tree.getName(child)
10954
+ local _counts = counts
10955
+ local _condition = counts[childName]
10956
+ if _condition == nil then
10957
+ _condition = 0
10958
+ end
10959
+ _counts[childName] = _condition + 1
10960
+ end
10961
+ local _parent_1 = parent
10962
+ local _counts = counts
10963
+ nameCounts[_parent_1] = _counts
10964
+ end
10965
+ local _counts = counts
10966
+ local _name = name
10967
+ local _condition = _counts[_name]
10968
+ if _condition == nil then
10969
+ _condition = 0
10970
+ end
10971
+ return _condition
10972
+ end
10973
+ local function segmentIsAmbiguous(node, parent)
10974
+ local name = tree.getName(node)
10975
+ if parent == tree.root then
10976
+ if tree.isRootService(node) then
10977
+ return false
10978
+ end
10979
+ -- A root segment that names a service resolves to that service,
10980
+ -- never to this child.
10981
+ local service = tree.getService(name)
10982
+ if service ~= nil and service ~= node then
10983
+ return true
10984
+ end
10985
+ end
10986
+ return countNamed(parent, name) > 1
10987
+ end
10988
+ return function(node)
10989
+ local visited = {}
10990
+ local result = false
10991
+ local current = node
10992
+ while current ~= tree.root do
10993
+ local _current = current
10994
+ local cached = verdicts[_current]
10995
+ if cached ~= nil then
10996
+ result = cached
10997
+ break
10998
+ end
10999
+ local parent = tree.getParent(current)
11000
+ if parent == nil then
11001
+ break
11002
+ end
11003
+ local _current_1 = current
11004
+ table.insert(visited, _current_1)
11005
+ if segmentIsAmbiguous(current, parent) then
11006
+ result = true
11007
+ break
11008
+ end
11009
+ current = parent
11010
+ end
11011
+ for _, visitedNode in visited do
11012
+ local _result = result
11013
+ verdicts[visitedNode] = _result
11014
+ end
11015
+ return result
11016
+ end
11017
+ end
11018
+ return {
11019
+ resolvePath = resolvePath,
11020
+ createAmbiguityChecker = createAmbiguityChecker,
11021
+ }
11022
+ ]]></string>
11023
+ </Properties>
11024
+ </Item>
11025
+ <Item class="ModuleScript" referent="30">
11026
+ <Properties>
11027
+ <string name="Name">PathGuard</string>
11028
+ <string name="Source"><![CDATA[-- Compiled with roblox-ts v3.0.0
11029
+ -- Central handling of request paths that name more than one instance.
11030
+ -- Every endpoint that accepts instance paths declares them here. Before the
11031
+ -- handler runs, each declared path is checked:
11032
+ -- - write: an ambiguous path refuses the request, so no arbitrary duplicate
11033
+ -- is modified;
11034
+ -- - read: the handler runs on the first match, and the response gains
11035
+ -- `ambiguousPaths` and `pathWarning` so the caller knows it may be wrong.
11036
+ -- Written against an injected resolver so it can run outside Studio.
11037
+ local function pathField(field, access)
11038
+ return function(data)
11039
+ local value = data[field]
11040
+ if not (type(value) == "string") or value == "" then
11041
+ return {}
11042
+ end
11043
+ local _object = {
11044
+ field = field,
11045
+ path = value,
11046
+ }
11047
+ local _left = "access"
11048
+ local _access = access
11049
+ _object[_left] = if type(_access) == "string" then access else access(data)
11050
+ return { _object }
11051
+ end
11052
+ end
11053
+ local function pathListField(field, access)
11054
+ return function(data)
11055
+ local value = data[field]
11056
+ local references = {}
11057
+ if not (type(value) == "table") then
11058
+ return references
11059
+ end
11060
+ local index = 0
11061
+ for _, entry in value do
11062
+ if type(entry) == "string" and entry ~= "" then
11063
+ local _arg0 = {
11064
+ field = `{field}[{index}]`,
11065
+ path = entry,
11066
+ access = access,
11067
+ }
11068
+ table.insert(references, _arg0)
11069
+ end
11070
+ index += 1
11071
+ end
11072
+ return references
11073
+ end
11074
+ end
11075
+ -- set_properties takes instance paths as the values of reference properties.
11076
+ local REFERENCE_PROPERTIES = { "Parent", "PrimaryPart" }
11077
+ local function referencePropertyPaths(data)
11078
+ local properties = data.properties
11079
+ local references = {}
11080
+ if not (type(properties) == "table") then
11081
+ return references
11082
+ end
11083
+ for _, propertyName in REFERENCE_PROPERTIES do
11084
+ local value = properties[propertyName]
11085
+ if type(value) == "string" and value ~= "" then
11086
+ local _arg0 = {
11087
+ field = `properties.{propertyName}`,
11088
+ path = value,
11089
+ access = "write",
11090
+ }
11091
+ table.insert(references, _arg0)
11092
+ end
11093
+ end
11094
+ return references
11095
+ end
11096
+ local dryRunIsRead = function(data)
11097
+ return if data.dryRun == true then "read" else "write"
11098
+ end
11099
+ local ENDPOINT_PATHS = {
11100
+ ["/api/file-tree"] = { pathField("path", "read") },
11101
+ ["/api/search-objects"] = { pathField("path", "read") },
11102
+ ["/api/instance-properties"] = { pathField("instancePath", "read") },
11103
+ ["/api/project-structure"] = { pathField("path", "read") },
11104
+ ["/api/grep-scripts"] = { pathField("path", "read") },
11105
+ ["/api/get-script-source"] = { pathField("instancePath", "read") },
11106
+ ["/api/get-attributes"] = { pathField("instancePath", "read") },
11107
+ ["/api/set-selection"] = { pathListField("paths", "read") },
11108
+ ["/api/focus-viewport"] = { pathField("path", "read") },
11109
+ ["/api/breakpoints"] = { pathField("script_path", "read") },
11110
+ ["/api/export-rbxm"] = { pathListField("instance_paths", "read") },
11111
+ ["/api/set-properties"] = { pathField("instancePath", "write"), referencePropertyPaths },
11112
+ ["/api/set-script-source"] = { pathField("instancePath", "write") },
11113
+ ["/api/edit-script-lines"] = { pathField("instancePath", dryRunIsRead) },
11114
+ ["/api/insert-script-lines"] = { pathField("instancePath", "write") },
11115
+ ["/api/delete-script-lines"] = { pathField("instancePath", "write") },
11116
+ ["/api/find-and-replace-in-scripts"] = { pathField("path", dryRunIsRead) },
11117
+ ["/api/insert-asset"] = { pathField("parentPath", "write") },
11118
+ ["/api/import-rbxm"] = { pathField("parent_path", "write") },
11119
+ }
11120
+ local function describe(report)
11121
+ return `{report.path} ({report.field}): {report.matchCount} children of {report.parentPath} are named "{report.segment}"`
11122
+ end
11123
+ local function describeAll(reports)
11124
+ local parts = {}
11125
+ for _, report in reports do
11126
+ local _arg0 = describe(report)
11127
+ table.insert(parts, _arg0)
11128
+ end
11129
+ return table.concat(parts, "; ")
11130
+ end
11131
+ local function createPathGuard(findAmbiguity)
11132
+ local function inspect(endpoint, data)
11133
+ local reports = {}
11134
+ local extractors = ENDPOINT_PATHS[endpoint]
11135
+ if extractors == nil then
11136
+ return reports
11137
+ end
11138
+ for _, extract in extractors do
11139
+ for _1, reference in extract(data) do
11140
+ local ambiguity = findAmbiguity(reference.path)
11141
+ if ambiguity ~= nil then
11142
+ local _arg0 = {
11143
+ field = reference.field,
11144
+ path = reference.path,
11145
+ access = reference.access,
11146
+ segment = ambiguity.segment,
11147
+ parentPath = ambiguity.parentPath,
11148
+ matchCount = ambiguity.matchCount,
11149
+ }
11150
+ table.insert(reports, _arg0)
11151
+ end
11152
+ end
11153
+ end
11154
+ return reports
11155
+ end
11156
+ local function run(endpoint, data, handle)
11157
+ local reports = inspect(endpoint, data)
11158
+ if #reports == 0 then
11159
+ return handle()
11160
+ end
11161
+ -- ▼ ReadonlyArray.filter ▼
11162
+ local _newValue = {}
11163
+ local _callback = function(report)
11164
+ return report.access == "write"
11165
+ end
11166
+ local _length = 0
11167
+ for _k, _v in reports do
11168
+ if _callback(_v, _k - 1, reports) == true then
11169
+ _length += 1
11170
+ _newValue[_length] = _v
11171
+ end
11172
+ end
11173
+ -- ▲ ReadonlyArray.filter ▲
11174
+ local writes = _newValue
11175
+ if #writes > 0 then
11176
+ return {
11177
+ error = `Ambiguous path {describeAll(writes)}. Refusing to modify an arbitrary match; rename the duplicates or target the instance with execute_luau.`,
11178
+ ambiguousPaths = writes,
11179
+ }
11180
+ end
11181
+ local result = handle()
11182
+ if type(result) == "table" then
11183
+ local response = result
11184
+ response.ambiguousPaths = reports
11185
+ response.pathWarning = `Ambiguous path {describeAll(reports)}; the first match was used.`
11186
+ end
11187
+ return result
11188
+ end
11189
+ return {
11190
+ inspect = inspect,
11191
+ run = run,
11192
+ }
11193
+ end
11194
+ return {
11195
+ createPathGuard = createPathGuard,
11196
+ }
11197
+ ]]></string>
11198
+ </Properties>
11199
+ </Item>
11200
+ <Item class="ModuleScript" referent="31">
9885
11201
  <Properties>
9886
11202
  <string name="Name">PeerRole</string>
9887
11203
  <string name="Source"><![CDATA[-- Compiled with roblox-ts v3.0.0
@@ -9902,7 +11218,7 @@ return {
9902
11218
  ]]></string>
9903
11219
  </Properties>
9904
11220
  </Item>
9905
- <Item class="ModuleScript" referent="29">
11221
+ <Item class="ModuleScript" referent="32">
9906
11222
  <Properties>
9907
11223
  <string name="Name">PlaytestTickets</string>
9908
11224
  <string name="Source"><![CDATA[-- Compiled with roblox-ts v3.0.0
@@ -10083,7 +11399,7 @@ return {
10083
11399
  ]]></string>
10084
11400
  </Properties>
10085
11401
  </Item>
10086
- <Item class="ModuleScript" referent="30">
11402
+ <Item class="ModuleScript" referent="33">
10087
11403
  <Properties>
10088
11404
  <string name="Name">PluginSession</string>
10089
11405
  <string name="Source"><![CDATA[-- Compiled with roblox-ts v3.0.0
@@ -10750,7 +12066,7 @@ return {
10750
12066
  ]]></string>
10751
12067
  </Properties>
10752
12068
  </Item>
10753
- <Item class="ModuleScript" referent="31">
12069
+ <Item class="ModuleScript" referent="34">
10754
12070
  <Properties>
10755
12071
  <string name="Name">Recording</string>
10756
12072
  <string name="Source"><![CDATA[-- Compiled with roblox-ts v3.0.0
@@ -10780,7 +12096,7 @@ return {
10780
12096
  ]]></string>
10781
12097
  </Properties>
10782
12098
  </Item>
10783
- <Item class="ModuleScript" referent="32">
12099
+ <Item class="ModuleScript" referent="35">
10784
12100
  <Properties>
10785
12101
  <string name="Name">RenderMonitor</string>
10786
12102
  <string name="Source"><![CDATA[-- Compiled with roblox-ts v3.0.0
@@ -10848,7 +12164,7 @@ return {
10848
12164
  ]]></string>
10849
12165
  </Properties>
10850
12166
  </Item>
10851
- <Item class="ModuleScript" referent="33">
12167
+ <Item class="ModuleScript" referent="36">
10852
12168
  <Properties>
10853
12169
  <string name="Name">RuntimeLogBuffer</string>
10854
12170
  <string name="Source"><![CDATA[-- Compiled with roblox-ts v3.0.0
@@ -11084,10 +12400,1043 @@ return {
11084
12400
  ]]></string>
11085
12401
  </Properties>
11086
12402
  </Item>
11087
- <Item class="ModuleScript" referent="34">
12403
+ <Item class="ModuleScript" referent="37">
12404
+ <Properties>
12405
+ <string name="Name">ScriptClasses</string>
12406
+ <string name="Source"><![CDATA[-- Compiled with roblox-ts v3.0.0
12407
+ -- Script classes a caller can select with classFilter. Class names are
12408
+ -- compared exactly: "Script" must not also select LocalScript or ModuleScript.
12409
+ -- An omitted filter selects every LuaSourceContainer the corpus can read.
12410
+ local SCRIPT_CLASS_FILTERS = { "Script", "LocalScript", "ModuleScript" }
12411
+ local function isScriptClassFilter(value)
12412
+ local _value = value
12413
+ local _condition = type(_value) == "string"
12414
+ if _condition then
12415
+ local _value_1 = value
12416
+ _condition = table.find(SCRIPT_CLASS_FILTERS, _value_1) ~= nil
12417
+ end
12418
+ return _condition
12419
+ end
12420
+ --* Returns an error message when classFilter is present but not a supported script class.
12421
+ local function classFilterError(value)
12422
+ if value == nil or isScriptClassFilter(value) then
12423
+ return nil
12424
+ end
12425
+ return `classFilter must be one of {table.concat(SCRIPT_CLASS_FILTERS, ", ")}`
12426
+ end
12427
+ local function matchesClassFilter(className, classFilter)
12428
+ return classFilter == nil or className == classFilter
12429
+ end
12430
+ return {
12431
+ SCRIPT_CLASS_FILTERS = SCRIPT_CLASS_FILTERS,
12432
+ classFilterError = classFilterError,
12433
+ matchesClassFilter = matchesClassFilter,
12434
+ }
12435
+ ]]></string>
12436
+ </Properties>
12437
+ </Item>
12438
+ <Item class="ModuleScript" referent="38">
12439
+ <Properties>
12440
+ <string name="Name">ScriptEdits</string>
12441
+ <string name="Source"><![CDATA[-- Compiled with roblox-ts v3.0.0
12442
+ -- Exact-text script edits resolved against one source snapshot, so several
12443
+ -- replacements either all apply or none do. Kept free of Studio services so
12444
+ -- the planning logic can be exercised outside Studio.
12445
+ local FNV_OFFSET_BASIS = 2166136261
12446
+ local UINT32_MODULUS = 4294967296
12447
+ local BYTE_CHUNK = 4096
12448
+ local DIFF_CHAR_BUDGET = 20000
12449
+ --[[
12450
+ *
12451
+ * Content revision of the exact script text: byte length plus FNV-1a 32.
12452
+ * It is an optimistic-concurrency token, not a security hash.
12453
+
12454
+ ]]
12455
+ local function sourceRevision(source)
12456
+ local length = #source
12457
+ local hash = FNV_OFFSET_BASIS
12458
+ do
12459
+ local chunkStart = 1
12460
+ local _shouldIncrement = false
12461
+ while true do
12462
+ if _shouldIncrement then
12463
+ chunkStart += BYTE_CHUNK
12464
+ else
12465
+ _shouldIncrement = true
12466
+ end
12467
+ if not (chunkStart <= length) then
12468
+ break
12469
+ end
12470
+ local _array = {}
12471
+ local _length = #_array
12472
+ local _array_1 = { string.byte(source, chunkStart, math.min(chunkStart + BYTE_CHUNK - 1, length)) }
12473
+ table.move(_array_1, 1, #_array_1, _length + 1, _array)
12474
+ local bytes = _array
12475
+ for _, byte in bytes do
12476
+ hash = bit32.bxor(hash, byte)
12477
+ -- hash * 16777619 mod 2^32. The FNV prime is 2^24 + 403; splitting the
12478
+ -- product keeps every intermediate below 2^53, where doubles stay exact.
12479
+ hash = (bit32.lshift(hash, 24) + hash * 403) % UINT32_MODULUS
12480
+ end
12481
+ end
12482
+ end
12483
+ return `{length}:{hash}`
12484
+ end
12485
+ -- 1-based byte offset at which each line starts. A trailing newline yields a
12486
+ -- final empty line, which is where an anchored insertion at EOF lands.
12487
+ local function lineStarts(source)
12488
+ local starts = { 1 }
12489
+ local searchFrom = 1
12490
+ while true do
12491
+ local newline = string.find(source, "\n", searchFrom, true)
12492
+ if newline == nil then
12493
+ break
12494
+ end
12495
+ local _arg0 = newline + 1
12496
+ table.insert(starts, _arg0)
12497
+ searchFrom = newline + 1
12498
+ end
12499
+ return starts
12500
+ end
12501
+ -- Line containing a byte offset; a newline belongs to the line it ends.
12502
+ local function lineAt(starts, offset)
12503
+ local low = 0
12504
+ local high = #starts - 1
12505
+ while low < high do
12506
+ local middle = math.floor((low + high + 1) / 2)
12507
+ if starts[middle + 1] <= offset then
12508
+ low = middle
12509
+ else
12510
+ high = middle - 1
12511
+ end
12512
+ end
12513
+ return low + 1
12514
+ end
12515
+ -- Byte offset just past the line's terminator, or past the end of the source.
12516
+ local function lineEnd(starts, source, line)
12517
+ return if line < #starts then starts[line + 1] else #source + 1
12518
+ end
12519
+ local function locateEdit(source, starts, edit, label)
12520
+ local searchLength = #edit.oldString
12521
+ if edit.startLine ~= nil then
12522
+ if edit.startLine < 1 or edit.startLine % 1 ~= 0 then
12523
+ return `{label}line must be a positive whole number (got {edit.startLine}).`
12524
+ end
12525
+ if edit.startLine > #starts then
12526
+ return `{label}line {edit.startLine} is past the end of the script.`
12527
+ end
12528
+ local start = starts[edit.startLine]
12529
+ if string.sub(source, start, start + searchLength - 1) ~= edit.oldString then
12530
+ return `{label}old_string does not match at line {edit.startLine}. Use get_script_source to verify the exact text at that line.`
12531
+ end
12532
+ return start
12533
+ end
12534
+ if searchLength == 0 then
12535
+ return `{label}old_string is empty; pass line_range to insert at the start of a line.`
12536
+ end
12537
+ local first = string.find(source, edit.oldString, 1, true)
12538
+ if first == nil then
12539
+ return `{label}old_string not found in script. If old_string contains repeated patterns (e.g. closing braces), pass line_range to anchor the edit.`
12540
+ end
12541
+ -- Search again from the byte after the first match's start, not its end:
12542
+ -- "aa" occurs twice in "aaa", and "end\nend" twice in "end\nend\nend".
12543
+ local second = string.find(source, edit.oldString, first + 1, true)
12544
+ if second ~= nil then
12545
+ local firstLine = lineAt(starts, first)
12546
+ local secondLine = lineAt(starts, second)
12547
+ if firstLine == secondLine then
12548
+ return `{label}old_string matches multiple locations on line {firstLine}. Provide more surrounding context; line_range only anchors a match that starts the line.`
12549
+ end
12550
+ return `{label}old_string matches multiple locations (lines {firstLine} and {secondLine}). Provide more surrounding context, or pass line_range to anchor the edit.`
12551
+ end
12552
+ return first
12553
+ end
12554
+ -- Source text in [regionStart, regionEnd) with every edit in resolved[from, to) applied.
12555
+ local function applyWithin(source, resolved, from, to, regionStart, regionEnd)
12556
+ local parts = {}
12557
+ local cursor = regionStart
12558
+ do
12559
+ local index = from
12560
+ local _shouldIncrement = false
12561
+ while true do
12562
+ if _shouldIncrement then
12563
+ index += 1
12564
+ else
12565
+ _shouldIncrement = true
12566
+ end
12567
+ if not (index < to) then
12568
+ break
12569
+ end
12570
+ local edit = resolved[index + 1]
12571
+ local _arg0 = string.sub(source, cursor, edit.start - 1)
12572
+ table.insert(parts, _arg0)
12573
+ local _newString = edit.newString
12574
+ table.insert(parts, _newString)
12575
+ cursor = edit.finish
12576
+ end
12577
+ end
12578
+ local _arg0 = string.sub(source, cursor, regionEnd - 1)
12579
+ table.insert(parts, _arg0)
12580
+ return table.concat(parts, "")
12581
+ end
12582
+ local NO_FINAL_NEWLINE = "\"
12583
+ -- Lines of a diff region. A last line without its newline only occurs at the
12584
+ -- end of the file; it is flagged so that adding or removing that newline still
12585
+ -- differs, as in a unified diff.
12586
+ local function textLines(text)
12587
+ if text == "" then
12588
+ return {
12589
+ lines = {},
12590
+ missingFinalNewline = false,
12591
+ }
12592
+ end
12593
+ local lines = string.split(text, "\n")
12594
+ local missingFinalNewline = string.sub(text, -1) ~= "\n"
12595
+ if not missingFinalNewline then
12596
+ lines[#lines] = nil
12597
+ end
12598
+ return {
12599
+ lines = lines,
12600
+ missingFinalNewline = missingFinalNewline,
12601
+ }
12602
+ end
12603
+ local function sameLine(a, aIndex, b, bIndex)
12604
+ return a.lines[aIndex + 1] == b.lines[bIndex + 1] and (a.missingFinalNewline and aIndex == #a.lines - 1) == (b.missingFinalNewline and bIndex == #b.lines - 1)
12605
+ end
12606
+ local function pushHunkLines(hunk, text, from, count, prefix)
12607
+ do
12608
+ local index = from
12609
+ local _shouldIncrement = false
12610
+ while true do
12611
+ if _shouldIncrement then
12612
+ index += 1
12613
+ else
12614
+ _shouldIncrement = true
12615
+ end
12616
+ if not (index < from + count) then
12617
+ break
12618
+ end
12619
+ local _hunk = hunk
12620
+ local _arg0 = `{prefix}{text.lines[index + 1]}`
12621
+ table.insert(_hunk, _arg0)
12622
+ if text.missingFinalNewline and index == #text.lines - 1 then
12623
+ table.insert(hunk, NO_FINAL_NEWLINE)
12624
+ end
12625
+ end
12626
+ end
12627
+ end
12628
+ local function hunkStart(line, count)
12629
+ return if count == 0 then line - 1 else line
12630
+ end
12631
+ local function editFirstLine(starts, edit)
12632
+ return lineAt(starts, edit.start)
12633
+ end
12634
+ local function editLastLine(starts, edit)
12635
+ return lineAt(starts, if edit.finish > edit.start then edit.finish - 1 else edit.start)
12636
+ end
12637
+ -- Unified diff of whole changed lines, without context lines. Edits that share
12638
+ -- a line become one hunk; lines the edit left unchanged are trimmed away.
12639
+ local function buildDiff(source, starts, resolved, charBudget)
12640
+ if charBudget == nil then
12641
+ charBudget = DIFF_CHAR_BUDGET
12642
+ end
12643
+ local output = {}
12644
+ local outputSize = 0
12645
+ local truncated = false
12646
+ local lineDelta = 0
12647
+ local groupStart = 0
12648
+ while groupStart < #resolved and not truncated do
12649
+ local firstLine = editFirstLine(starts, resolved[groupStart + 1])
12650
+ local lastLine = editLastLine(starts, resolved[groupStart + 1])
12651
+ local groupEnd = groupStart + 1
12652
+ local oldText
12653
+ local newText
12654
+ while true do
12655
+ while groupEnd < #resolved and editFirstLine(starts, resolved[groupEnd + 1]) <= lastLine do
12656
+ lastLine = math.max(lastLine, editLastLine(starts, resolved[groupEnd + 1]))
12657
+ groupEnd += 1
12658
+ end
12659
+ local regionStart = starts[firstLine]
12660
+ local regionEnd = lineEnd(starts, source, lastLine)
12661
+ oldText = string.sub(source, regionStart, regionEnd - 1)
12662
+ newText = applyWithin(source, resolved, groupStart, groupEnd, regionStart, regionEnd)
12663
+ -- A replacement that drops the region's final newline joins the next
12664
+ -- line onto it, so that line belongs in the hunk too.
12665
+ local nextLineHasText = lastLine < #starts and starts[lastLine + 1] <= #source
12666
+ if nextLineHasText and string.sub(oldText, -1) == "\n" and string.sub(newText, -1) ~= "\n" then
12667
+ lastLine += 1
12668
+ continue
12669
+ end
12670
+ break
12671
+ end
12672
+ local oldRegion = textLines(oldText)
12673
+ local newRegion = textLines(newText)
12674
+ local oldSize = #oldRegion.lines
12675
+ local newSize = #newRegion.lines
12676
+ local prefix = 0
12677
+ while prefix < oldSize and prefix < newSize and sameLine(oldRegion, prefix, newRegion, prefix) do
12678
+ prefix += 1
12679
+ end
12680
+ local suffix = 0
12681
+ while suffix < oldSize - prefix and suffix < newSize - prefix and sameLine(oldRegion, oldSize - 1 - suffix, newRegion, newSize - 1 - suffix) do
12682
+ suffix += 1
12683
+ end
12684
+ local oldCount = oldSize - prefix - suffix
12685
+ local newCount = newSize - prefix - suffix
12686
+ if oldCount > 0 or newCount > 0 then
12687
+ local oldStart = firstLine + prefix
12688
+ local newStart = oldStart + lineDelta
12689
+ local hunk = { `@@ -{hunkStart(oldStart, oldCount)},{oldCount} +{hunkStart(newStart, newCount)},{newCount} @@` }
12690
+ pushHunkLines(hunk, oldRegion, prefix, oldCount, "-")
12691
+ pushHunkLines(hunk, newRegion, prefix, newCount, "+")
12692
+ for _, line in hunk do
12693
+ if outputSize + #line + 1 > charBudget then
12694
+ truncated = true
12695
+ break
12696
+ end
12697
+ table.insert(output, line)
12698
+ outputSize += #line + 1
12699
+ end
12700
+ end
12701
+ lineDelta += newSize - oldSize
12702
+ groupStart = groupEnd
12703
+ end
12704
+ return {
12705
+ diff = table.concat(output, "\n"),
12706
+ truncated = truncated,
12707
+ }
12708
+ end
12709
+ --[[
12710
+ *
12711
+ * Resolves every edit against the same source, rejects overlaps, and builds
12712
+ * the edited source in memory. Nothing is written: the caller applies
12713
+ * newSource in one compare-and-set write, so a bad edit changes nothing.
12714
+ * line_range anchors refer to the source as it was before any edit.
12715
+
12716
+ ]]
12717
+ local function planScriptEdits(source, edits, includeDiff)
12718
+ if #edits == 0 then
12719
+ return {
12720
+ ok = false,
12721
+ error = "At least one edit is required.",
12722
+ }
12723
+ end
12724
+ local starts = lineStarts(source)
12725
+ local resolved = {}
12726
+ for index = 0, #edits - 1 do
12727
+ local edit = edits[index + 1]
12728
+ local label = if #edits > 1 then `edits[{index}]: ` else ""
12729
+ local located = locateEdit(source, starts, edit, label)
12730
+ if type(located) == "string" then
12731
+ return {
12732
+ ok = false,
12733
+ error = located,
12734
+ }
12735
+ end
12736
+ local _arg0 = {
12737
+ index = index,
12738
+ start = located,
12739
+ finish = located + #edit.oldString,
12740
+ newString = edit.newString,
12741
+ }
12742
+ table.insert(resolved, _arg0)
12743
+ -- Insertion sort by position; k is small and ties keep request order.
12744
+ do
12745
+ local at = #resolved - 1
12746
+ local _shouldIncrement = false
12747
+ while true do
12748
+ if _shouldIncrement then
12749
+ at -= 1
12750
+ else
12751
+ _shouldIncrement = true
12752
+ end
12753
+ if not (at > 0 and resolved[at].start > resolved[at + 1].start) then
12754
+ break
12755
+ end
12756
+ local swap = resolved[at]
12757
+ resolved[at] = resolved[at + 1]
12758
+ resolved[at + 1] = swap
12759
+ end
12760
+ end
12761
+ end
12762
+ for at = 1, #resolved - 1 do
12763
+ local previous = resolved[at]
12764
+ local current = resolved[at + 1]
12765
+ if current.start < previous.finish or current.start == previous.start then
12766
+ local first = math.min(previous.index, current.index)
12767
+ local second = math.max(previous.index, current.index)
12768
+ return {
12769
+ ok = false,
12770
+ error = `edits[{first}] and edits[{second}] overlap at line {lineAt(starts, current.start)}; combine them into one edit.`,
12771
+ }
12772
+ end
12773
+ end
12774
+ local newSource = applyWithin(source, resolved, 0, #resolved, 1, #source + 1)
12775
+ if not includeDiff then
12776
+ return {
12777
+ ok = true,
12778
+ newSource = newSource,
12779
+ diff = "",
12780
+ diffTruncated = false,
12781
+ }
12782
+ end
12783
+ local built = buildDiff(source, starts, resolved)
12784
+ return {
12785
+ ok = true,
12786
+ newSource = newSource,
12787
+ diff = built.diff,
12788
+ diffTruncated = built.truncated,
12789
+ }
12790
+ end
12791
+ -- Text of a line including its terminator, as lineStarts numbers lines.
12792
+ local function lineText(source, starts, line)
12793
+ return string.sub(source, starts[line], lineEnd(starts, source, line) - 1)
12794
+ end
12795
+ --[[
12796
+ *
12797
+ * Unified diff from one whole source to another, for edits whose positions
12798
+ * are not tracked (Lua pattern replacement). Unchanged leading and trailing
12799
+ * lines are trimmed. When the changed window keeps its line count, lines pair
12800
+ * one to one and each changed line is its own edit; otherwise the window is a
12801
+ * single edit. charBudget bounds the returned diff's characters.
12802
+
12803
+ ]]
12804
+ local function diffSources(oldSource, newSource, charBudget)
12805
+ if charBudget == nil then
12806
+ charBudget = DIFF_CHAR_BUDGET
12807
+ end
12808
+ if oldSource == newSource then
12809
+ return {
12810
+ diff = "",
12811
+ truncated = false,
12812
+ }
12813
+ end
12814
+ local oldStarts = lineStarts(oldSource)
12815
+ local newStarts = lineStarts(newSource)
12816
+ local oldCount = #oldStarts
12817
+ local newCount = #newStarts
12818
+ local prefix = 0
12819
+ while prefix < oldCount and prefix < newCount and lineText(oldSource, oldStarts, prefix + 1) == lineText(newSource, newStarts, prefix + 1) do
12820
+ prefix += 1
12821
+ end
12822
+ local suffix = 0
12823
+ while suffix < oldCount - prefix and suffix < newCount - prefix and lineText(oldSource, oldStarts, oldCount - suffix) == lineText(newSource, newStarts, newCount - suffix) do
12824
+ suffix += 1
12825
+ end
12826
+ local resolved = {}
12827
+ if oldCount == newCount then
12828
+ do
12829
+ local line = prefix + 1
12830
+ local _shouldIncrement = false
12831
+ while true do
12832
+ if _shouldIncrement then
12833
+ line += 1
12834
+ else
12835
+ _shouldIncrement = true
12836
+ end
12837
+ if not (line <= oldCount - suffix) then
12838
+ break
12839
+ end
12840
+ local replacement = lineText(newSource, newStarts, line)
12841
+ if lineText(oldSource, oldStarts, line) ~= replacement then
12842
+ local _arg0 = {
12843
+ index = #resolved,
12844
+ start = oldStarts[line],
12845
+ finish = lineEnd(oldStarts, oldSource, line),
12846
+ newString = replacement,
12847
+ }
12848
+ table.insert(resolved, _arg0)
12849
+ end
12850
+ end
12851
+ end
12852
+ else
12853
+ local _condition = newStarts[prefix + 1]
12854
+ if _condition == nil then
12855
+ _condition = #newSource + 1
12856
+ end
12857
+ local newWindowStart = _condition
12858
+ local _object = {
12859
+ index = 0,
12860
+ }
12861
+ local _left = "start"
12862
+ local _condition_1 = oldStarts[prefix + 1]
12863
+ if _condition_1 == nil then
12864
+ _condition_1 = #oldSource + 1
12865
+ end
12866
+ _object[_left] = _condition_1
12867
+ _object.finish = lineEnd(oldStarts, oldSource, oldCount - suffix)
12868
+ _object.newString = string.sub(newSource, newWindowStart, lineEnd(newStarts, newSource, newCount - suffix) - 1)
12869
+ table.insert(resolved, _object)
12870
+ end
12871
+ return buildDiff(oldSource, oldStarts, resolved, charBudget)
12872
+ end
12873
+ return {
12874
+ sourceRevision = sourceRevision,
12875
+ planScriptEdits = planScriptEdits,
12876
+ diffSources = diffSources,
12877
+ }
12878
+ ]]></string>
12879
+ </Properties>
12880
+ </Item>
12881
+ <Item class="ModuleScript" referent="39">
12882
+ <Properties>
12883
+ <string name="Name">ScriptReplace</string>
12884
+ <string name="Source"><![CDATA[-- Compiled with roblox-ts v3.0.0
12885
+ local TS = require(script.Parent.Parent.include.RuntimeLib)
12886
+ local _ScriptEdits = TS.import(script, script.Parent, "ScriptEdits")
12887
+ local diffSources = _ScriptEdits.diffSources
12888
+ local sourceRevision = _ScriptEdits.sourceRevision
12889
+ local ScriptClasses = TS.import(script, script.Parent, "ScriptClasses")
12890
+ -- Find-and-replace across scripts, planned against one snapshot of every
12891
+ -- matching script before anything is written. The whole plan is checked (the
12892
+ -- replacement cap and any expected revisions) before the first write. Each
12893
+ -- write is a compare-and-set against the planned source, and a failed write
12894
+ -- restores the scripts already written wherever they still hold the written
12895
+ -- text, so a newer editor draft is never overwritten. ChangeHistoryService is
12896
+ -- not relied on to undo Source. Free of Studio services so it can run outside
12897
+ -- Studio.
12898
+ local DEFAULT_MAX_REPLACEMENTS = 1000
12899
+ local PREVIEW_DIFF_CHAR_BUDGET = 20000
12900
+ -- Originals returned when a restore was refused, so the caller can recover them.
12901
+ local RETAINED_SOURCE_CHAR_BUDGET = 200000
12902
+ local function readRequest(data)
12903
+ local pattern = data.pattern
12904
+ if not (type(pattern) == "string") or pattern == "" then
12905
+ return "pattern is required"
12906
+ end
12907
+ local replacement = data.replacement
12908
+ if not (type(replacement) == "string") then
12909
+ return "replacement is required"
12910
+ end
12911
+ for _, option in { "caseSensitive", "usePattern", "dryRun" } do
12912
+ local value = data[option]
12913
+ if value ~= nil and not (type(value) == "boolean") then
12914
+ return `{option} must be a boolean`
12915
+ end
12916
+ end
12917
+ local _condition = (data.caseSensitive)
12918
+ if _condition == nil then
12919
+ _condition = false
12920
+ end
12921
+ local caseSensitive = _condition
12922
+ local _condition_1 = (data.usePattern)
12923
+ if _condition_1 == nil then
12924
+ _condition_1 = false
12925
+ end
12926
+ local usePattern = _condition_1
12927
+ if not caseSensitive and usePattern then
12928
+ return "Case-insensitive Lua pattern replacement is not supported. Use caseSensitive: true with usePattern: true, or use literal matching."
12929
+ end
12930
+ local _condition_2 = data.path
12931
+ if _condition_2 == nil then
12932
+ _condition_2 = ""
12933
+ end
12934
+ local path = _condition_2
12935
+ if not (type(path) == "string") then
12936
+ return "path must be a string"
12937
+ end
12938
+ local classError = ScriptClasses.classFilterError(data.classFilter)
12939
+ if classError ~= nil then
12940
+ return classError
12941
+ end
12942
+ local _condition_3 = data.maxReplacements
12943
+ if _condition_3 == nil then
12944
+ _condition_3 = DEFAULT_MAX_REPLACEMENTS
12945
+ end
12946
+ local maxReplacements = _condition_3
12947
+ if not (type(maxReplacements) == "number") or maxReplacements < 1 or maxReplacements % 1 ~= 0 then
12948
+ return "maxReplacements must be a positive whole number"
12949
+ end
12950
+ local expectedRevisions
12951
+ local rawRevisions = data.expectedRevisions
12952
+ if rawRevisions ~= nil then
12953
+ if not (type(rawRevisions) == "table") then
12954
+ return "expectedRevisions must map script paths to revisions"
12955
+ end
12956
+ expectedRevisions = {}
12957
+ for key, value in pairs(rawRevisions) do
12958
+ if not (type(key) == "string") or not (type(value) == "string") or value == "" then
12959
+ return "expectedRevisions must map script paths to revisions"
12960
+ end
12961
+ expectedRevisions[key] = value
12962
+ end
12963
+ end
12964
+ local _object = {
12965
+ pattern = pattern,
12966
+ replacement = replacement,
12967
+ caseSensitive = caseSensitive,
12968
+ usePattern = usePattern,
12969
+ path = path,
12970
+ classFilter = data.classFilter,
12971
+ }
12972
+ local _left = "dryRun"
12973
+ local _condition_4 = (data.dryRun)
12974
+ if _condition_4 == nil then
12975
+ _condition_4 = false
12976
+ end
12977
+ _object[_left] = _condition_4
12978
+ _object.maxReplacements = maxReplacements
12979
+ _object.expectedRevisions = expectedRevisions
12980
+ return _object
12981
+ end
12982
+ -- Replaces every non-overlapping occurrence, left to right. Case-insensitive
12983
+ -- matching compares lowered copies; string.lower keeps byte offsets.
12984
+ local function replaceLiteral(source, search, replacement, caseSensitive)
12985
+ local haystack = if caseSensitive then source else string.lower(source)
12986
+ local needle = if caseSensitive then search else string.lower(search)
12987
+ local parts = {}
12988
+ local cursor = 1
12989
+ local count = 0
12990
+ while true do
12991
+ local found = string.find(haystack, needle, cursor, true)
12992
+ if found == nil then
12993
+ break
12994
+ end
12995
+ local _arg0 = string.sub(source, cursor, found - 1)
12996
+ table.insert(parts, _arg0)
12997
+ local _replacement = replacement
12998
+ table.insert(parts, _replacement)
12999
+ cursor = found + #needle
13000
+ count += 1
13001
+ end
13002
+ if count == 0 then
13003
+ return { source, 0 }
13004
+ end
13005
+ local _arg0 = string.sub(source, cursor)
13006
+ table.insert(parts, _arg0)
13007
+ return { table.concat(parts, ""), count }
13008
+ end
13009
+ local function createScriptReplace(corpus)
13010
+ local function replaceIn(request, source)
13011
+ if request.usePattern then
13012
+ local result, count = string.gsub(source, request.pattern, request.replacement)
13013
+ return { result, count }
13014
+ end
13015
+ return replaceLiteral(source, request.pattern, request.replacement, request.caseSensitive)
13016
+ end
13017
+ local function planScripts(request, root)
13018
+ local _self = corpus
13019
+ local _result = _self.createAmbiguityChecker
13020
+ if _result ~= nil then
13021
+ _result = _result(_self)
13022
+ end
13023
+ local _condition = _result
13024
+ if _condition == nil then
13025
+ _condition = (function()
13026
+ return false
13027
+ end)
13028
+ end
13029
+ local isAmbiguous = _condition
13030
+ local planned = {}
13031
+ local scriptsSearched = 0
13032
+ local stack = { root }
13033
+ while #stack > 0 do
13034
+ -- ▼ Array.pop ▼
13035
+ local _length = #stack
13036
+ local _result_1 = stack[_length]
13037
+ stack[_length] = nil
13038
+ -- ▲ Array.pop ▲
13039
+ local node = _result_1
13040
+ local snapshot = corpus:readScript(node, request.classFilter)
13041
+ if snapshot ~= nil and ScriptClasses.matchesClassFilter(snapshot.className, request.classFilter) then
13042
+ scriptsSearched += 1
13043
+ local _binding = replaceIn(request, snapshot.source)
13044
+ local newSource = _binding[1]
13045
+ local replacements = _binding[2]
13046
+ if replacements > 0 then
13047
+ local _arg0 = {
13048
+ node = node,
13049
+ snapshot = snapshot,
13050
+ newSource = newSource,
13051
+ replacements = replacements,
13052
+ revision = sourceRevision(snapshot.source),
13053
+ resultRevision = sourceRevision(newSource),
13054
+ ambiguous = isAmbiguous(node),
13055
+ }
13056
+ table.insert(planned, _arg0)
13057
+ end
13058
+ end
13059
+ local children = corpus:getChildren(node)
13060
+ for index = #children - 1, 0, -1 do
13061
+ local _arg0 = children[index + 1]
13062
+ table.insert(stack, _arg0)
13063
+ end
13064
+ end
13065
+ -- A path shared by two planned scripts cannot key a revision either.
13066
+ local pathCounts = {}
13067
+ for _, entry in planned do
13068
+ local _exp = entry.snapshot.instancePath
13069
+ local _instancePath = entry.snapshot.instancePath
13070
+ local _condition_1 = pathCounts[_instancePath]
13071
+ if _condition_1 == nil then
13072
+ _condition_1 = 0
13073
+ end
13074
+ pathCounts[_exp] = _condition_1 + 1
13075
+ end
13076
+ for _, entry in planned do
13077
+ local _instancePath = entry.snapshot.instancePath
13078
+ if pathCounts[_instancePath] > 1 then
13079
+ entry.ambiguous = true
13080
+ end
13081
+ end
13082
+ return { planned, scriptsSearched }
13083
+ end
13084
+ local function checkRevisions(planned, expected)
13085
+ local mismatches = {}
13086
+ local plannedPaths = {}
13087
+ for _, entry in planned do
13088
+ local instancePath = entry.snapshot.instancePath
13089
+ plannedPaths[instancePath] = true
13090
+ local expectedRevision = expected[instancePath]
13091
+ if entry.ambiguous then
13092
+ local _arg0 = {
13093
+ instancePath = instancePath,
13094
+ reason = "ambiguous_path",
13095
+ expectedRevision = expectedRevision,
13096
+ revision = entry.revision,
13097
+ }
13098
+ table.insert(mismatches, _arg0)
13099
+ elseif expectedRevision == nil then
13100
+ local _arg0 = {
13101
+ instancePath = instancePath,
13102
+ reason = "not_reviewed",
13103
+ revision = entry.revision,
13104
+ }
13105
+ table.insert(mismatches, _arg0)
13106
+ elseif expectedRevision ~= entry.revision then
13107
+ local _arg0 = {
13108
+ instancePath = instancePath,
13109
+ reason = "changed",
13110
+ expectedRevision = expectedRevision,
13111
+ revision = entry.revision,
13112
+ }
13113
+ table.insert(mismatches, _arg0)
13114
+ end
13115
+ end
13116
+ local reviewedOnly = {}
13117
+ for instancePath in expected do
13118
+ if not (plannedPaths[instancePath] ~= nil) then
13119
+ table.insert(reviewedOnly, instancePath)
13120
+ end
13121
+ end
13122
+ table.sort(reviewedOnly)
13123
+ for _, instancePath in reviewedOnly do
13124
+ local expectedRevision = expected[instancePath]
13125
+ local node = corpus:resolvePath(instancePath)
13126
+ local snapshot = if node == nil then nil else corpus:readScript(node)
13127
+ if snapshot == nil then
13128
+ local _arg0 = {
13129
+ instancePath = instancePath,
13130
+ reason = "missing",
13131
+ expectedRevision = expectedRevision,
13132
+ }
13133
+ table.insert(mismatches, _arg0)
13134
+ continue
13135
+ end
13136
+ local revision = sourceRevision(snapshot.source)
13137
+ local _arg0 = {
13138
+ instancePath = instancePath,
13139
+ reason = if revision == expectedRevision then "no_longer_matches" else "changed",
13140
+ expectedRevision = expectedRevision,
13141
+ revision = revision,
13142
+ }
13143
+ table.insert(mismatches, _arg0)
13144
+ end
13145
+ return mismatches
13146
+ end
13147
+ local function describePlanned(entry)
13148
+ local change = {
13149
+ instancePath = entry.snapshot.instancePath,
13150
+ name = entry.snapshot.name,
13151
+ className = entry.snapshot.className,
13152
+ replacements = entry.replacements,
13153
+ revision = entry.revision,
13154
+ resultRevision = entry.resultRevision,
13155
+ }
13156
+ if entry.ambiguous then
13157
+ change.ambiguous = true
13158
+ end
13159
+ return change
13160
+ end
13161
+ local function run(data)
13162
+ local request = readRequest(data)
13163
+ if type(request) == "string" then
13164
+ return {
13165
+ success = false,
13166
+ error = request,
13167
+ }
13168
+ end
13169
+ local root = corpus:resolvePath(request.path)
13170
+ if root == nil then
13171
+ return {
13172
+ success = false,
13173
+ error = `Path not found: {request.path}`,
13174
+ }
13175
+ end
13176
+ local summary = {
13177
+ dryRun = request.dryRun,
13178
+ pattern = request.pattern,
13179
+ replacement = request.replacement,
13180
+ maxReplacements = request.maxReplacements,
13181
+ }
13182
+ -- Planning reads and computes only; a malformed Lua pattern fails here,
13183
+ -- before any write.
13184
+ local scanned, scanResult = pcall(function()
13185
+ return planScripts(request, root)
13186
+ end)
13187
+ if not scanned then
13188
+ local _object = table.clone(summary)
13189
+ setmetatable(_object, nil)
13190
+ _object.success = false
13191
+ _object.error = `Script traversal failed: {scanResult}`
13192
+ _object.totalReplacements = 0
13193
+ _object.scriptsSearched = 0
13194
+ _object.scriptsMatched = 0
13195
+ _object.scriptsModified = 0
13196
+ _object.scriptsFailed = 0
13197
+ _object.changes = {}
13198
+ return _object
13199
+ end
13200
+ local _binding = scanResult
13201
+ local scripts = _binding[1]
13202
+ local scriptsSearched = _binding[2]
13203
+ local totalReplacements = 0
13204
+ for _, entry in scripts do
13205
+ totalReplacements += entry.replacements
13206
+ end
13207
+ summary.totalReplacements = totalReplacements
13208
+ summary.scriptsSearched = scriptsSearched
13209
+ summary.scriptsMatched = #scripts
13210
+ -- ▼ ReadonlyArray.map ▼
13211
+ local _newValue = table.create(#scripts)
13212
+ for _k, _v in scripts do
13213
+ _newValue[_k] = describePlanned(_v, _k - 1, scripts)
13214
+ end
13215
+ -- ▲ ReadonlyArray.map ▲
13216
+ local changes = _newValue
13217
+ local revisions = {}
13218
+ for _, entry in scripts do
13219
+ if not entry.ambiguous then
13220
+ local _instancePath = entry.snapshot.instancePath
13221
+ local _revision = entry.revision
13222
+ revisions[_instancePath] = _revision
13223
+ end
13224
+ end
13225
+ local refused = function(code, message, extra)
13226
+ if extra == nil then
13227
+ extra = {}
13228
+ end
13229
+ local _object = table.clone(summary)
13230
+ setmetatable(_object, nil)
13231
+ for _k, _v in extra do
13232
+ _object[_k] = _v
13233
+ end
13234
+ _object.success = false
13235
+ _object.code = code
13236
+ _object.error = message
13237
+ _object.scriptsModified = 0
13238
+ _object.scriptsFailed = 0
13239
+ _object.changes = changes
13240
+ return _object
13241
+ end
13242
+ if request.expectedRevisions ~= nil then
13243
+ local mismatches = checkRevisions(scripts, request.expectedRevisions)
13244
+ if #mismatches > 0 then
13245
+ return refused("revision_mismatch", "The scripts this replacement would change differ from the reviewed expected_revisions; nothing was written. Preview again with dryRun and pass its revisions.", {
13246
+ mismatches = mismatches,
13247
+ })
13248
+ end
13249
+ end
13250
+ if totalReplacements > request.maxReplacements then
13251
+ return refused("max_replacements_exceeded", `This replacement makes {totalReplacements} replacements, more than maxReplacements ({request.maxReplacements}); nothing was written. Narrow path or classFilter, or raise maxReplacements.`)
13252
+ end
13253
+ if request.dryRun then
13254
+ local diffBudget = PREVIEW_DIFF_CHAR_BUDGET
13255
+ local anyDiffTruncated = false
13256
+ for index = 0, #scripts - 1 do
13257
+ local entry = scripts[index + 1]
13258
+ local change = changes[index + 1]
13259
+ if diffBudget <= 0 then
13260
+ change.diffTruncated = true
13261
+ anyDiffTruncated = true
13262
+ continue
13263
+ end
13264
+ local built = diffSources(entry.snapshot.source, entry.newSource, diffBudget)
13265
+ change.diff = built.diff
13266
+ diffBudget -= #built.diff + 1
13267
+ if built.truncated then
13268
+ change.diffTruncated = true
13269
+ anyDiffTruncated = true
13270
+ end
13271
+ end
13272
+ local _object = table.clone(summary)
13273
+ setmetatable(_object, nil)
13274
+ _object.success = true
13275
+ _object.scriptsModified = #scripts
13276
+ _object.scriptsFailed = 0
13277
+ _object.changes = changes
13278
+ local preview = _object
13279
+ -- Pass back as expected_revisions to apply exactly this plan. Omitted
13280
+ -- when empty: Luau encodes an empty table as a JSON array.
13281
+ -- ▼ ReadonlyArray.some ▼
13282
+ local _result = false
13283
+ local _callback = function(entry)
13284
+ return not entry.ambiguous
13285
+ end
13286
+ for _k, _v in scripts do
13287
+ if _callback(_v, _k - 1, scripts) then
13288
+ _result = true
13289
+ break
13290
+ end
13291
+ end
13292
+ -- ▲ ReadonlyArray.some ▲
13293
+ if _result then
13294
+ preview.revisions = revisions
13295
+ end
13296
+ if anyDiffTruncated then
13297
+ preview.diffTruncated = true
13298
+ end
13299
+ return preview
13300
+ end
13301
+ if #scripts == 0 then
13302
+ local _object = table.clone(summary)
13303
+ setmetatable(_object, nil)
13304
+ _object.success = true
13305
+ _object.scriptsModified = 0
13306
+ _object.scriptsFailed = 0
13307
+ _object.changes = changes
13308
+ return _object
13309
+ end
13310
+ local recording = corpus:beginRecording("Find and replace in scripts")
13311
+ local write = function(node, newSource, expectedSource)
13312
+ local ok, result = pcall(function()
13313
+ return corpus:writeScript(node, newSource, expectedSource)
13314
+ end)
13315
+ return if ok then result else {
13316
+ success = false,
13317
+ error = tostring(result),
13318
+ }
13319
+ end
13320
+ local failedAt
13321
+ local failure
13322
+ for index = 0, #scripts - 1 do
13323
+ local entry = scripts[index + 1]
13324
+ local result = write(entry.node, entry.newSource, entry.snapshot.source)
13325
+ if not result.success then
13326
+ failedAt = index
13327
+ local _condition = result.error
13328
+ if _condition == nil then
13329
+ _condition = "Script write failed verification"
13330
+ end
13331
+ failure = _condition
13332
+ break
13333
+ end
13334
+ changes[index + 1].status = "applied"
13335
+ end
13336
+ if failedAt == nil then
13337
+ corpus:finishRecording(recording, true)
13338
+ local _object = table.clone(summary)
13339
+ setmetatable(_object, nil)
13340
+ _object.success = true
13341
+ _object.scriptsModified = #scripts
13342
+ _object.scriptsFailed = 0
13343
+ _object.changes = changes
13344
+ return _object
13345
+ end
13346
+ local statuses = {}
13347
+ for index = 0, #scripts - 1 do
13348
+ local _arg0 = if index < failedAt then "applied" elseif index == failedAt then "failed" else "not_attempted"
13349
+ table.insert(statuses, _arg0)
13350
+ end
13351
+ changes[failedAt + 1].error = failure
13352
+ -- A failed write can still have landed (verification refused it); if the
13353
+ -- script holds the written text, undo it like the others.
13354
+ local failedEntry = scripts[failedAt + 1]
13355
+ local holds = function(entry, source)
13356
+ local readOk, current = pcall(function()
13357
+ return corpus:readScript(entry.node)
13358
+ end)
13359
+ return readOk and current ~= nil and current.source == source
13360
+ end
13361
+ local restoreFrom = if holds(failedEntry, failedEntry.newSource) then failedAt else failedAt - 1
13362
+ local retainedBudget = RETAINED_SOURCE_CHAR_BUDGET
13363
+ local restored = 0
13364
+ local restoreFailed = 0
13365
+ do
13366
+ local index = restoreFrom
13367
+ local _shouldIncrement = false
13368
+ while true do
13369
+ if _shouldIncrement then
13370
+ index -= 1
13371
+ else
13372
+ _shouldIncrement = true
13373
+ end
13374
+ if not (index >= 0) then
13375
+ break
13376
+ end
13377
+ local entry = scripts[index + 1]
13378
+ local change = changes[index + 1]
13379
+ local result = write(entry.node, entry.snapshot.source, entry.newSource)
13380
+ -- A restore refused by verification can still have landed.
13381
+ if result.success or holds(entry, entry.snapshot.source) then
13382
+ statuses[index + 1] = "restored"
13383
+ restored += 1
13384
+ continue
13385
+ end
13386
+ statuses[index + 1] = "restore_failed"
13387
+ restoreFailed += 1
13388
+ local _condition = result.error
13389
+ if _condition == nil then
13390
+ _condition = "Script restore failed verification"
13391
+ end
13392
+ change.restoreError = _condition
13393
+ if #entry.snapshot.source <= retainedBudget then
13394
+ change.originalSource = entry.snapshot.source
13395
+ retainedBudget -= #entry.snapshot.source
13396
+ else
13397
+ change.originalSourceOmitted = true
13398
+ end
13399
+ end
13400
+ end
13401
+ for index = 0, #scripts - 1 do
13402
+ changes[index + 1].status = statuses[index + 1]
13403
+ end
13404
+ corpus:finishRecording(recording, restoreFailed > 0)
13405
+ local notAttempted = 0
13406
+ for _, status in statuses do
13407
+ if status == "not_attempted" then
13408
+ notAttempted += 1
13409
+ end
13410
+ end
13411
+ local restoreSummary = if restoreFailed > 0 then `{restored} written script(s) were restored; {restoreFailed} changed again after the write and were left as they are, with their original source in changes[].originalSource where it fits.` else `{restored} written script(s) were restored.`
13412
+ local _object = table.clone(summary)
13413
+ setmetatable(_object, nil)
13414
+ _object.success = false
13415
+ _object.code = "apply_failed"
13416
+ _object.error = `Failed to write {failedEntry.snapshot.instancePath}: {failure}. {restoreSummary}`
13417
+ _object.scriptsModified = restoreFailed
13418
+ _object.scriptsRestored = restored
13419
+ _object.scriptsFailed = 1
13420
+ _object.scriptsNotAttempted = notAttempted
13421
+ _object.changes = changes
13422
+ return _object
13423
+ end
13424
+ return {
13425
+ run = run,
13426
+ }
13427
+ end
13428
+ return {
13429
+ createScriptReplace = createScriptReplace,
13430
+ }
13431
+ ]]></string>
13432
+ </Properties>
13433
+ </Item>
13434
+ <Item class="ModuleScript" referent="40">
11088
13435
  <Properties>
11089
13436
  <string name="Name">ScriptSearch</string>
11090
13437
  <string name="Source"><![CDATA[-- Compiled with roblox-ts v3.0.0
13438
+ local TS = require(script.Parent.Parent.include.RuntimeLib)
13439
+ local ScriptClasses = TS.import(script, script.Parent, "ScriptClasses")
11091
13440
  local function splitLuaAlternation(pattern)
11092
13441
  local parts = {}
11093
13442
  local current = ""
@@ -11261,6 +13610,13 @@ local function createScriptSearch(corpus)
11261
13610
  _condition_4 = 0
11262
13611
  end
11263
13612
  local maxResultsPerScript = _condition_4
13613
+ local classError = ScriptClasses.classFilterError(requestData.classFilter)
13614
+ if classError ~= nil then
13615
+ return {
13616
+ error = "invalid_request",
13617
+ message = classError,
13618
+ }
13619
+ end
11264
13620
  local classFilter = requestData.classFilter
11265
13621
  local _condition_5 = (requestData.path)
11266
13622
  if _condition_5 == nil then
@@ -11273,6 +13629,18 @@ local function createScriptSearch(corpus)
11273
13629
  error = `Path not found: {searchPath}`,
11274
13630
  }
11275
13631
  end
13632
+ local _self = corpus
13633
+ local _result_1 = _self.createAmbiguityChecker
13634
+ if _result_1 ~= nil then
13635
+ _result_1 = _result_1(_self)
13636
+ end
13637
+ local _condition_6 = _result_1
13638
+ if _condition_6 == nil then
13639
+ _condition_6 = (function()
13640
+ return false
13641
+ end)
13642
+ end
13643
+ local isAmbiguous = _condition_6
11276
13644
  local searchPattern = if caseSensitive then pattern else string.lower(pattern)
11277
13645
  local patternAlternatives = if usePattern then splitLuaAlternation(searchPattern) else nil
11278
13646
  local results = {}
@@ -11284,12 +13652,12 @@ local function createScriptSearch(corpus)
11284
13652
  control:checkpoint()
11285
13653
  -- ▼ Array.pop ▼
11286
13654
  local _length = #stack
11287
- local _result_1 = stack[_length]
13655
+ local _result_2 = stack[_length]
11288
13656
  stack[_length] = nil
11289
13657
  -- ▲ Array.pop ▲
11290
- local instance = _result_1
13658
+ local instance = _result_2
11291
13659
  local snapshot = corpus:readScript(instance, classFilter)
11292
- if snapshot ~= nil and (classFilter == nil or snapshot.className == classFilter) then
13660
+ if snapshot ~= nil and ScriptClasses.matchesClassFilter(snapshot.className, classFilter) then
11293
13661
  scriptsSearched += 1
11294
13662
  local scriptMatches = {}
11295
13663
  local before = {}
@@ -11372,6 +13740,9 @@ local function createScriptSearch(corpus)
11372
13740
  if snapshot.enabled ~= nil then
11373
13741
  scriptResult.enabled = snapshot.enabled
11374
13742
  end
13743
+ if isAmbiguous(instance) then
13744
+ scriptResult.ambiguous = true
13745
+ end
11375
13746
  table.insert(results, scriptResult)
11376
13747
  end
11377
13748
  end
@@ -11411,7 +13782,7 @@ return {
11411
13782
  ]]></string>
11412
13783
  </Properties>
11413
13784
  </Item>
11414
- <Item class="ModuleScript" referent="35">
13785
+ <Item class="ModuleScript" referent="41">
11415
13786
  <Properties>
11416
13787
  <string name="Name">ServerUrlSettings</string>
11417
13788
  <string name="Source"><![CDATA[-- Compiled with roblox-ts v3.0.0
@@ -11525,11 +13896,11 @@ return {
11525
13896
  ]]></string>
11526
13897
  </Properties>
11527
13898
  </Item>
11528
- <Item class="ModuleScript" referent="36">
13899
+ <Item class="ModuleScript" referent="42">
11529
13900
  <Properties>
11530
13901
  <string name="Name">State</string>
11531
13902
  <string name="Source"><![CDATA[-- Compiled with roblox-ts v3.0.0
11532
- local CURRENT_VERSION = "3.2.1"
13903
+ local CURRENT_VERSION = "3.4.0"
11533
13904
  local PLUGIN_VARIANT = "inspector"
11534
13905
  local BASE_PORT = 58741
11535
13906
  local SENSITIVE_DIAGNOSTIC_TERMS = { "token", "authorization", "bearer", "password", "cookie", "secret" }
@@ -11667,7 +14038,7 @@ return {
11667
14038
  ]]></string>
11668
14039
  </Properties>
11669
14040
  </Item>
11670
- <Item class="ModuleScript" referent="37">
14041
+ <Item class="ModuleScript" referent="43">
11671
14042
  <Properties>
11672
14043
  <string name="Name">StopPlayMonitor</string>
11673
14044
  <string name="Source"><![CDATA[-- Compiled with roblox-ts v3.0.0
@@ -11953,7 +14324,7 @@ return {
11953
14324
  ]]></string>
11954
14325
  </Properties>
11955
14326
  </Item>
11956
- <Item class="ModuleScript" referent="38">
14327
+ <Item class="ModuleScript" referent="44">
11957
14328
  <Properties>
11958
14329
  <string name="Name">StudioWebSocket</string>
11959
14330
  <string name="Source"><![CDATA[-- Compiled with roblox-ts v3.0.0
@@ -13111,7 +15482,7 @@ return {
13111
15482
  ]]></string>
13112
15483
  </Properties>
13113
15484
  </Item>
13114
- <Item class="ModuleScript" referent="39">
15485
+ <Item class="ModuleScript" referent="45">
13115
15486
  <Properties>
13116
15487
  <string name="Name">TopologyId</string>
13117
15488
  <string name="Source"><![CDATA[-- Compiled with roblox-ts v3.0.0
@@ -13156,7 +15527,7 @@ return {
13156
15527
  ]]></string>
13157
15528
  </Properties>
13158
15529
  </Item>
13159
- <Item class="ModuleScript" referent="40">
15530
+ <Item class="ModuleScript" referent="46">
13160
15531
  <Properties>
13161
15532
  <string name="Name">UI</string>
13162
15533
  <string name="Source"><![CDATA[-- Compiled with roblox-ts v3.0.0
@@ -13681,10 +16052,12 @@ return {
13681
16052
  ]]></string>
13682
16053
  </Properties>
13683
16054
  </Item>
13684
- <Item class="ModuleScript" referent="41">
16055
+ <Item class="ModuleScript" referent="47">
13685
16056
  <Properties>
13686
16057
  <string name="Name">Utils</string>
13687
16058
  <string name="Source"><![CDATA[-- Compiled with roblox-ts v3.0.0
16059
+ local TS = require(script.Parent.Parent.include.RuntimeLib)
16060
+ local PathAmbiguity = TS.import(script, script.Parent, "PathAmbiguity")
13688
16061
  local ScriptEditorService = game:GetService("ScriptEditorService")
13689
16062
  local LUAU_KEYWORDS = {
13690
16063
  ["and"] = true,
@@ -13899,16 +16272,17 @@ local function parseInstancePath(path)
13899
16272
  end
13900
16273
  return parts
13901
16274
  end
16275
+ local function getService(segment)
16276
+ local ok, service = pcall(function()
16277
+ return game:GetService(segment)
16278
+ end)
16279
+ return if ok and service then service else nil
16280
+ end
16281
+ local function isRootService(instance)
16282
+ return instance.Parent == game and getService(instance.ClassName) == instance
16283
+ end
13902
16284
  local function getRootSegment(instance)
13903
- if instance.Parent == game then
13904
- local ok, service = pcall(function()
13905
- return game:GetService(instance.ClassName)
13906
- end)
13907
- if ok and service == instance then
13908
- return instance.ClassName
13909
- end
13910
- end
13911
- return instance.Name
16285
+ return if isRootService(instance) then instance.ClassName else instance.Name
13912
16286
  end
13913
16287
  local function getInstancePath(instance)
13914
16288
  if not instance or instance == game then
@@ -13932,13 +16306,7 @@ local function getInstancePath(instance)
13932
16306
  return path
13933
16307
  end
13934
16308
  local function getRootInstance(segment)
13935
- local ok, service = pcall(function()
13936
- return game:GetService(segment)
13937
- end)
13938
- if ok and service then
13939
- return service
13940
- end
13941
- return game:FindFirstChild(segment)
16309
+ return getService(segment) or game:FindFirstChild(segment)
13942
16310
  end
13943
16311
  local function getInstanceByPath(path)
13944
16312
  local parts = parseInstancePath(path)
@@ -13958,6 +16326,36 @@ local function getInstanceByPath(path)
13958
16326
  end
13959
16327
  return current
13960
16328
  end
16329
+ local instancePathTree = {
16330
+ root = game,
16331
+ getParent = function(instance)
16332
+ return instance.Parent
16333
+ end,
16334
+ getChildren = function(instance)
16335
+ return instance:GetChildren()
16336
+ end,
16337
+ getName = function(instance)
16338
+ return instance.Name
16339
+ end,
16340
+ getService = getService,
16341
+ isRootService = isRootService,
16342
+ getPath = getInstancePath,
16343
+ }
16344
+ -- Like getInstanceByPath, but also reports the first segment that names more
16345
+ -- than one sibling. Costs one child scan per segment. PathGuard applies it to
16346
+ -- every declared request path before the handler runs.
16347
+ local function resolveInstancePath(path)
16348
+ local parts = parseInstancePath(path)
16349
+ if parts == nil then
16350
+ return {}
16351
+ end
16352
+ return PathAmbiguity.resolvePath(instancePathTree, parts)
16353
+ end
16354
+ -- Returns a per-request predicate that is true when getInstancePath(instance)
16355
+ -- does not identify exactly that instance.
16356
+ local function createPathAmbiguityChecker()
16357
+ return PathAmbiguity.createAmbiguityChecker(instancePathTree)
16358
+ end
13961
16359
  local function splitLines(source)
13962
16360
  local _condition = source
13963
16361
  if _condition == nil then
@@ -14512,6 +16910,8 @@ return {
14512
16910
  safeCall = safeCall,
14513
16911
  getInstancePath = getInstancePath,
14514
16912
  getInstanceByPath = getInstanceByPath,
16913
+ resolveInstancePath = resolveInstancePath,
16914
+ createPathAmbiguityChecker = createPathAmbiguityChecker,
14515
16915
  splitLines = splitLines,
14516
16916
  joinLines = joinLines,
14517
16917
  readScriptSource = readScriptSource,
@@ -14524,11 +16924,11 @@ return {
14524
16924
  </Properties>
14525
16925
  </Item>
14526
16926
  </Item>
14527
- <Item class="Folder" referent="46">
16927
+ <Item class="Folder" referent="52">
14528
16928
  <Properties>
14529
16929
  <string name="Name">include</string>
14530
16930
  </Properties>
14531
- <Item class="ModuleScript" referent="42">
16931
+ <Item class="ModuleScript" referent="48">
14532
16932
  <Properties>
14533
16933
  <string name="Name">LibMP</string>
14534
16934
  <string name="Source"><![CDATA[-- =============================================================================
@@ -170912,7 +173312,7 @@ return LibMP
170912
173312
  ]]></string>
170913
173313
  </Properties>
170914
173314
  </Item>
170915
- <Item class="ModuleScript" referent="43">
173315
+ <Item class="ModuleScript" referent="49">
170916
173316
  <Properties>
170917
173317
  <string name="Name">Promise</string>
170918
173318
  <string name="Source"><![CDATA[--[[
@@ -172986,7 +175386,7 @@ return Promise
172986
175386
  ]]></string>
172987
175387
  </Properties>
172988
175388
  </Item>
172989
- <Item class="ModuleScript" referent="44">
175389
+ <Item class="ModuleScript" referent="50">
172990
175390
  <Properties>
172991
175391
  <string name="Name">RuntimeLib</string>
172992
175392
  <string name="Source"><![CDATA[local Promise = require(script.Parent.Promise)
@@ -173253,15 +175653,15 @@ return TS
173253
175653
  </Properties>
173254
175654
  </Item>
173255
175655
  </Item>
173256
- <Item class="Folder" referent="47">
175656
+ <Item class="Folder" referent="53">
173257
175657
  <Properties>
173258
175658
  <string name="Name">node_modules</string>
173259
175659
  </Properties>
173260
- <Item class="Folder" referent="48">
175660
+ <Item class="Folder" referent="54">
173261
175661
  <Properties>
173262
175662
  <string name="Name">@rbxts</string>
173263
175663
  </Properties>
173264
- <Item class="ModuleScript" referent="45">
175664
+ <Item class="ModuleScript" referent="51">
173265
175665
  <Properties>
173266
175666
  <string name="Name">services</string>
173267
175667
  <string name="Source"><![CDATA[return setmetatable({}, {