@rivetkit/engine-runner 2.0.22-rc.1 → 2.0.22-rc.2

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.
@@ -1,5 +1,5 @@
1
1
 
2
- > @rivetkit/engine-runner@2.0.22-rc.1 build /home/runner/work/rivet/rivet/engine/sdks/typescript/runner
2
+ > @rivetkit/engine-runner@2.0.22-rc.2 build /home/runner/work/rivet/rivet/engine/sdks/typescript/runner
3
3
  > tsup src/mod.ts
4
4
 
5
5
  CLI Building entry: src/mod.ts
@@ -10,13 +10,13 @@
10
10
  CLI Cleaning output folder
11
11
  CJS Build start
12
12
  ESM Build start
13
- ESM dist/mod.js 58.58 KB
14
- ESM dist/mod.js.map 111.69 KB
15
- ESM ⚡️ Build success in 259ms
16
- CJS dist/mod.cjs 59.46 KB
17
- CJS dist/mod.cjs.map 95.00 KB
18
- CJS ⚡️ Build success in 312ms
13
+ ESM dist/mod.js 61.25 KB
14
+ ESM dist/mod.js.map 117.35 KB
15
+ ESM ⚡️ Build success in 256ms
16
+ CJS dist/mod.cjs 62.25 KB
17
+ CJS dist/mod.cjs.map 99.90 KB
18
+ CJS ⚡️ Build success in 257ms
19
19
  DTS Build start
20
- DTS ⚡️ Build success in 1571ms
21
- DTS dist/mod.d.cts 2.85 KB
22
- DTS dist/mod.d.ts 2.85 KB
20
+ DTS ⚡️ Build success in 1525ms
21
+ DTS dist/mod.d.cts 3.26 KB
22
+ DTS dist/mod.d.ts 3.26 KB
package/dist/mod.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } var _class;// src/mod.ts
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } var _class;// src/mod.ts
2
2
  var _enginerunnerprotocol = require('@rivetkit/engine-runner-protocol'); var protocol = _interopRequireWildcard(_enginerunnerprotocol);
3
3
 
4
4
  // src/log.ts
@@ -171,12 +171,18 @@ var WebSocketTunnelAdapter = (_class = class {
171
171
  this.#sendCallback(messageData, isBinary);
172
172
  }
173
173
  close(code, reason) {
174
+ this.closeInner(code, reason);
175
+ }
176
+ __closeWithRetry(code, reason) {
177
+ this.closeInner(code, reason, true);
178
+ }
179
+ closeInner(code, reason, retry = false) {
174
180
  if (this.#readyState === 2 || // CLOSING
175
181
  this.#readyState === 3) {
176
182
  return;
177
183
  }
178
184
  this.#readyState = 2;
179
- this.#closeCallback(code, reason);
185
+ this.#closeCallback(code, reason, retry);
180
186
  this.#readyState = 3;
181
187
  const closeEvent = {
182
188
  wasClean: true,
@@ -361,20 +367,22 @@ var WebSocketTunnelAdapter = (_class = class {
361
367
  }
362
368
  }
363
369
  // Internal methods called by the Tunnel class
364
- _handleOpen() {
370
+ _handleOpen(requestId) {
365
371
  if (this.#readyState !== 0) {
366
372
  return;
367
373
  }
368
374
  this.#readyState = 1;
369
375
  const event = {
370
376
  type: "open",
377
+ rivetRequestId: requestId,
371
378
  target: this
372
379
  };
373
380
  this.#fireEvent("open", event);
374
381
  }
375
- _handleMessage(data, isBinary) {
382
+ /// Returns false if the message was sent off.
383
+ _handleMessage(requestId, data, index, isBinary) {
376
384
  if (this.#readyState !== 1) {
377
- return;
385
+ return true;
378
386
  }
379
387
  let messageData;
380
388
  if (isBinary) {
@@ -398,22 +406,26 @@ var WebSocketTunnelAdapter = (_class = class {
398
406
  messageData = data;
399
407
  }
400
408
  const event = {
401
- data: messageData,
402
409
  type: "message",
410
+ data: messageData,
411
+ rivetRequestId: requestId,
412
+ rivetMessageIndex: index,
403
413
  target: this
404
414
  };
405
415
  this.#fireEvent("message", event);
416
+ return false;
406
417
  }
407
- _handleClose(code, reason) {
418
+ _handleClose(requestId, code, reason) {
408
419
  if (this.#readyState === 3) {
409
420
  return;
410
421
  }
411
422
  this.#readyState = 3;
412
423
  const event = {
424
+ type: "close",
413
425
  wasClean: true,
414
426
  code: code || 1e3,
415
427
  reason: reason || "",
416
- type: "close",
428
+ rivetRequestId: requestId,
417
429
  target: this
418
430
  };
419
431
  this.#fireEvent("close", event);
@@ -485,12 +497,12 @@ var Tunnel = class {
485
497
  }
486
498
  this.#actorPendingRequests.clear();
487
499
  for (const [_, ws] of this.#actorWebSockets) {
488
- ws.close();
500
+ ws.__closeWithRetry();
489
501
  }
490
502
  this.#actorWebSockets.clear();
491
503
  }
492
504
  #sendMessage(requestId, messageKind) {
493
- var _a;
505
+ var _a, _b;
494
506
  if (!this.#runner.__webSocketReady()) {
495
507
  (_a = logger()) == null ? void 0 : _a.warn(
496
508
  "cannot send tunnel message, socket not connected to engine"
@@ -498,11 +510,18 @@ var Tunnel = class {
498
510
  return;
499
511
  }
500
512
  const messageId = generateUuidBuffer();
501
- const requestIdStr = bufferToString(requestId);
502
- this.#pendingTunnelMessages.set(bufferToString(messageId), {
513
+ const requestIdStr = idToStr(requestId);
514
+ const messageIdStr = idToStr(messageId);
515
+ this.#pendingTunnelMessages.set(messageIdStr, {
503
516
  sentAt: Date.now(),
504
517
  requestIdStr
505
518
  });
519
+ (_b = logger()) == null ? void 0 : _b.debug({
520
+ msg: "send tunnel msg",
521
+ requestId: requestIdStr,
522
+ messageId: messageIdStr,
523
+ message: messageKind
524
+ });
506
525
  const message = {
507
526
  tag: "ToServerTunnelMessage",
508
527
  val: {
@@ -514,6 +533,7 @@ var Tunnel = class {
514
533
  this.#runner.__sendToServer(message);
515
534
  }
516
535
  #sendAck(requestId, messageId) {
536
+ var _a;
517
537
  if (!this.#runner.__webSocketReady()) {
518
538
  return;
519
539
  }
@@ -525,6 +545,11 @@ var Tunnel = class {
525
545
  messageKind: { tag: "TunnelAck", val: null }
526
546
  }
527
547
  };
548
+ (_a = logger()) == null ? void 0 : _a.debug({
549
+ msg: "ack tunnel msg",
550
+ requestId: idToStr(requestId),
551
+ messageId: idToStr(messageId)
552
+ });
528
553
  this.#runner.__sendToServer(message);
529
554
  }
530
555
  #startGarbageCollector() {
@@ -557,7 +582,10 @@ var Tunnel = class {
557
582
  }
558
583
  const webSocket = this.#actorWebSockets.get(requestIdStr);
559
584
  if (webSocket) {
560
- webSocket.close(1e3, "Message acknowledgment timeout");
585
+ webSocket.__closeWithRetry(
586
+ 1e3,
587
+ "Message acknowledgment timeout"
588
+ );
561
589
  this.#actorWebSockets.delete(requestIdStr);
562
590
  }
563
591
  }
@@ -572,7 +600,7 @@ var Tunnel = class {
572
600
  }
573
601
  }
574
602
  }
575
- unregisterActor(actor) {
603
+ closeActiveRequests(actor) {
576
604
  const actorId = actor.actorId;
577
605
  for (const requestId of actor.requests) {
578
606
  const pending = this.#actorPendingRequests.get(requestId);
@@ -585,24 +613,28 @@ var Tunnel = class {
585
613
  for (const webSocketId of actor.webSockets) {
586
614
  const ws = this.#actorWebSockets.get(webSocketId);
587
615
  if (ws) {
588
- ws.close(1e3, "Actor stopped");
616
+ ws.__closeWithRetry(1e3, "Actor stopped");
589
617
  this.#actorWebSockets.delete(webSocketId);
590
618
  }
591
619
  }
592
620
  actor.webSockets.clear();
593
621
  }
594
- async #fetch(actorId, request) {
622
+ async #fetch(actorId, requestId, request) {
595
623
  var _a;
596
624
  if (!this.#runner.hasActor(actorId)) {
597
625
  (_a = logger()) == null ? void 0 : _a.warn({
598
626
  msg: "ignoring request for unknown actor",
599
627
  actorId
600
628
  });
601
- return new Response("Actor not found", { status: 404 });
629
+ return new Response("Actor not found", {
630
+ status: 503,
631
+ headers: { "x-rivet-error": "runner.actor_not_found" }
632
+ });
602
633
  }
603
634
  const fetchHandler = this.#runner.config.fetch(
604
635
  this.#runner,
605
636
  actorId,
637
+ requestId,
606
638
  request
607
639
  );
608
640
  if (!fetchHandler) {
@@ -611,43 +643,64 @@ var Tunnel = class {
611
643
  return fetchHandler;
612
644
  }
613
645
  async handleTunnelMessage(message) {
646
+ var _a, _b;
647
+ const requestIdStr = idToStr(message.requestId);
648
+ const messageIdStr = idToStr(message.messageId);
649
+ (_a = logger()) == null ? void 0 : _a.debug({
650
+ msg: "receive tunnel msg",
651
+ requestId: requestIdStr,
652
+ messageId: messageIdStr,
653
+ message: message.messageKind
654
+ });
614
655
  if (message.messageKind.tag === "TunnelAck") {
615
- const msgIdStr = bufferToString(message.messageId);
616
- const pending = this.#pendingTunnelMessages.get(msgIdStr);
656
+ const pending = this.#pendingTunnelMessages.get(messageIdStr);
617
657
  if (pending) {
618
- this.#pendingTunnelMessages.delete(msgIdStr);
658
+ const didDelete = this.#pendingTunnelMessages.delete(messageIdStr);
659
+ if (!didDelete) {
660
+ (_b = logger()) == null ? void 0 : _b.warn({
661
+ msg: "received tunnel ack for nonexistent message",
662
+ requestId: requestIdStr,
663
+ messageId: messageIdStr
664
+ });
665
+ }
619
666
  }
620
667
  } else {
621
- this.#sendAck(message.requestId, message.messageId);
622
668
  switch (message.messageKind.tag) {
623
669
  case "ToClientRequestStart":
670
+ this.#sendAck(message.requestId, message.messageId);
624
671
  await this.#handleRequestStart(
625
672
  message.requestId,
626
673
  message.messageKind.val
627
674
  );
628
675
  break;
629
676
  case "ToClientRequestChunk":
677
+ this.#sendAck(message.requestId, message.messageId);
630
678
  await this.#handleRequestChunk(
631
679
  message.requestId,
632
680
  message.messageKind.val
633
681
  );
634
682
  break;
635
683
  case "ToClientRequestAbort":
684
+ this.#sendAck(message.requestId, message.messageId);
636
685
  await this.#handleRequestAbort(message.requestId);
637
686
  break;
638
687
  case "ToClientWebSocketOpen":
688
+ this.#sendAck(message.requestId, message.messageId);
639
689
  await this.#handleWebSocketOpen(
640
690
  message.requestId,
641
691
  message.messageKind.val
642
692
  );
643
693
  break;
644
- case "ToClientWebSocketMessage":
645
- await this.#handleWebSocketMessage(
694
+ case "ToClientWebSocketMessage": {
695
+ this.#sendAck(message.requestId, message.messageId);
696
+ const _unhandled = await this.#handleWebSocketMessage(
646
697
  message.requestId,
647
698
  message.messageKind.val
648
699
  );
649
700
  break;
701
+ }
650
702
  case "ToClientWebSocketClose":
703
+ this.#sendAck(message.requestId, message.messageId);
651
704
  await this.#handleWebSocketClose(
652
705
  message.requestId,
653
706
  message.messageKind.val
@@ -660,7 +713,7 @@ var Tunnel = class {
660
713
  }
661
714
  async #handleRequestStart(requestId, req) {
662
715
  var _a;
663
- const requestIdStr = bufferToString(requestId);
716
+ const requestIdStr = idToStr(requestId);
664
717
  const actor = this.#runner.getActor(req.actorId);
665
718
  if (actor) {
666
719
  actor.requests.add(requestIdStr);
@@ -700,11 +753,16 @@ var Tunnel = class {
700
753
  });
701
754
  const response = await this.#fetch(
702
755
  req.actorId,
756
+ requestId,
703
757
  streamingRequest
704
758
  );
705
759
  await this.#sendResponse(requestId, response);
706
760
  } else {
707
- const response = await this.#fetch(req.actorId, request);
761
+ const response = await this.#fetch(
762
+ req.actorId,
763
+ requestId,
764
+ request
765
+ );
708
766
  await this.#sendResponse(requestId, response);
709
767
  }
710
768
  } catch (error) {
@@ -718,7 +776,7 @@ var Tunnel = class {
718
776
  }
719
777
  }
720
778
  async #handleRequestChunk(requestId, chunk) {
721
- const requestIdStr = bufferToString(requestId);
779
+ const requestIdStr = idToStr(requestId);
722
780
  const pending = this.#actorPendingRequests.get(requestIdStr);
723
781
  if (pending == null ? void 0 : pending.streamController) {
724
782
  pending.streamController.enqueue(new Uint8Array(chunk.body));
@@ -729,7 +787,7 @@ var Tunnel = class {
729
787
  }
730
788
  }
731
789
  async #handleRequestAbort(requestId) {
732
- const requestIdStr = bufferToString(requestId);
790
+ const requestIdStr = idToStr(requestId);
733
791
  const pending = this.#actorPendingRequests.get(requestIdStr);
734
792
  if (pending == null ? void 0 : pending.streamController) {
735
793
  pending.streamController.error(new Error("Request aborted"));
@@ -770,7 +828,7 @@ var Tunnel = class {
770
828
  }
771
829
  async #handleWebSocketOpen(requestId, open) {
772
830
  var _a, _b, _c;
773
- const webSocketId = bufferToString(requestId);
831
+ const webSocketId = idToStr(requestId);
774
832
  const actor = this.#runner.getActor(open.actorId);
775
833
  if (!actor) {
776
834
  (_a = logger()) == null ? void 0 : _a.warn({
@@ -781,7 +839,8 @@ var Tunnel = class {
781
839
  tag: "ToServerWebSocketClose",
782
840
  val: {
783
841
  code: 1011,
784
- reason: "Actor not found"
842
+ reason: "Actor not found",
843
+ retry: false
785
844
  }
786
845
  });
787
846
  return;
@@ -795,7 +854,8 @@ var Tunnel = class {
795
854
  tag: "ToServerWebSocketClose",
796
855
  val: {
797
856
  code: 1011,
798
- reason: "Not Implemented"
857
+ reason: "Not Implemented",
858
+ retry: false
799
859
  }
800
860
  });
801
861
  return;
@@ -816,12 +876,13 @@ var Tunnel = class {
816
876
  }
817
877
  });
818
878
  },
819
- (code, reason) => {
879
+ (code, reason, retry = false) => {
820
880
  this.#sendMessage(requestId, {
821
881
  tag: "ToServerWebSocketClose",
822
882
  val: {
823
883
  code: code || null,
824
- reason: reason || null
884
+ reason: reason || null,
885
+ retry
825
886
  }
826
887
  });
827
888
  this.#actorWebSockets.delete(webSocketId);
@@ -831,11 +892,6 @@ var Tunnel = class {
831
892
  }
832
893
  );
833
894
  this.#actorWebSockets.set(webSocketId, adapter);
834
- this.#sendMessage(requestId, {
835
- tag: "ToServerWebSocketOpen",
836
- val: null
837
- });
838
- adapter._handleOpen();
839
895
  const headerInit = {};
840
896
  if (open.headers) {
841
897
  for (const [k, v] of open.headers) {
@@ -848,10 +904,24 @@ var Tunnel = class {
848
904
  method: "GET",
849
905
  headers: headerInit
850
906
  });
907
+ const hibernationConfig = this.#runner.config.getActorHibernationConfig(
908
+ actor.actorId,
909
+ requestId,
910
+ request
911
+ );
912
+ this.#sendMessage(requestId, {
913
+ tag: "ToServerWebSocketOpen",
914
+ val: {
915
+ canHibernate: hibernationConfig.enabled,
916
+ lastMsgIndex: BigInt(_nullishCoalesce(hibernationConfig.lastMsgIndex, () => ( -1)))
917
+ }
918
+ });
919
+ adapter._handleOpen(requestId);
851
920
  await websocketHandler(
852
921
  this.#runner,
853
922
  open.actorId,
854
923
  adapter,
924
+ requestId,
855
925
  request
856
926
  );
857
927
  } catch (error) {
@@ -860,7 +930,8 @@ var Tunnel = class {
860
930
  tag: "ToServerWebSocketClose",
861
931
  val: {
862
932
  code: 1011,
863
- reason: "Server Error"
933
+ reason: "Server Error",
934
+ retry: false
864
935
  }
865
936
  });
866
937
  this.#actorWebSockets.delete(webSocketId);
@@ -869,34 +940,59 @@ var Tunnel = class {
869
940
  }
870
941
  }
871
942
  }
943
+ /// Returns false if the message was sent off
872
944
  async #handleWebSocketMessage(requestId, msg) {
873
- const webSocketId = bufferToString(requestId);
945
+ const webSocketId = idToStr(requestId);
874
946
  const adapter = this.#actorWebSockets.get(webSocketId);
875
947
  if (adapter) {
876
948
  const data = msg.binary ? new Uint8Array(msg.data) : new TextDecoder().decode(new Uint8Array(msg.data));
877
- adapter._handleMessage(data, msg.binary);
949
+ return adapter._handleMessage(
950
+ requestId,
951
+ data,
952
+ msg.index,
953
+ msg.binary
954
+ );
955
+ } else {
956
+ return true;
878
957
  }
879
958
  }
959
+ __ackWebsocketMessage(requestId, index) {
960
+ var _a;
961
+ (_a = logger()) == null ? void 0 : _a.debug({
962
+ msg: "ack ws msg",
963
+ requestId: idToStr(requestId),
964
+ index
965
+ });
966
+ if (index < 0 || index > 65535)
967
+ throw new Error("invalid websocket ack index");
968
+ this.#sendMessage(requestId, {
969
+ tag: "ToServerWebSocketMessageAck",
970
+ val: {
971
+ index
972
+ }
973
+ });
974
+ }
880
975
  async #handleWebSocketClose(requestId, close) {
881
- const webSocketId = bufferToString(requestId);
882
- const adapter = this.#actorWebSockets.get(webSocketId);
976
+ const requestIdStr = idToStr(requestId);
977
+ const adapter = this.#actorWebSockets.get(requestIdStr);
883
978
  if (adapter) {
884
979
  adapter._handleClose(
980
+ requestId,
885
981
  close.code || void 0,
886
982
  close.reason || void 0
887
983
  );
888
- this.#actorWebSockets.delete(webSocketId);
984
+ this.#actorWebSockets.delete(requestIdStr);
889
985
  }
890
986
  }
891
987
  };
892
- function bufferToString(buffer) {
893
- return Buffer.from(buffer).toString("base64");
894
- }
895
988
  function generateUuidBuffer() {
896
989
  const buffer = new Uint8Array(16);
897
990
  _uuid.v4.call(void 0, void 0, buffer);
898
991
  return buffer.buffer;
899
992
  }
993
+ function idToStr(id) {
994
+ return _uuid.stringify.call(void 0, new Uint8Array(id));
995
+ }
900
996
 
901
997
  // src/websocket.ts
902
998
  var webSocketPromise = null;
@@ -933,7 +1029,8 @@ async function importWebSocket() {
933
1029
 
934
1030
  // src/mod.ts
935
1031
  var KV_EXPIRE = 3e4;
936
- var PROTOCOL_VERSION = 1;
1032
+ var PROTOCOL_VERSION = 2;
1033
+ var RUNNER_PING_INTERVAL = 3e3;
937
1034
  var EVENT_BACKLOG_WARN_THRESHOLD = 1e4;
938
1035
  var SIGNAL_HANDLERS = [];
939
1036
  var Runner = class {
@@ -989,22 +1086,13 @@ var Runner = class {
989
1086
  var _a;
990
1087
  const actor = this.#removeActor(actorId, generation);
991
1088
  if (!actor) return;
992
- (_a = this.#tunnel) == null ? void 0 : _a.unregisterActor(actor);
993
1089
  try {
994
1090
  await this.#config.onActorStop(actorId, actor.generation);
995
1091
  } catch (err) {
996
1092
  console.error(`Error in onActorStop for actor ${actorId}:`, err);
997
1093
  }
1094
+ (_a = this.#tunnel) == null ? void 0 : _a.closeActiveRequests(actor);
998
1095
  this.#sendActorStateUpdate(actorId, actor.generation, "stopped");
999
- this.#config.onActorStop(actorId, actor.generation).catch((err) => {
1000
- var _a2;
1001
- (_a2 = logger()) == null ? void 0 : _a2.error({
1002
- msg: "error in onactorstop for actor",
1003
- runnerId: this.runnerId,
1004
- actorId,
1005
- err
1006
- });
1007
- });
1008
1096
  }
1009
1097
  #stopAllActors() {
1010
1098
  var _a;
@@ -1043,8 +1131,9 @@ var Runner = class {
1043
1131
  const actor = this.#actors.get(actorId);
1044
1132
  return !!actor && (generation === void 0 || actor.generation === generation);
1045
1133
  }
1134
+ // IMPORTANT: Make sure to call stopActiveRequests if calling #removeActor
1046
1135
  #removeActor(actorId, generation) {
1047
- var _a, _b, _c;
1136
+ var _a, _b;
1048
1137
  const actor = this.#actors.get(actorId);
1049
1138
  if (!actor) {
1050
1139
  (_a = logger()) == null ? void 0 : _a.error({
@@ -1064,22 +1153,6 @@ var Runner = class {
1064
1153
  return void 0;
1065
1154
  }
1066
1155
  this.#actors.delete(actorId);
1067
- const actorWebSockets = this.#actorWebSockets.get(actorId);
1068
- if (actorWebSockets) {
1069
- for (const ws of actorWebSockets) {
1070
- try {
1071
- ws.close(1e3, "Actor stopped");
1072
- } catch (err) {
1073
- (_c = logger()) == null ? void 0 : _c.error({
1074
- msg: "error closing websocket for actor",
1075
- runnerId: this.runnerId,
1076
- actorId,
1077
- err
1078
- });
1079
- }
1080
- }
1081
- this.#actorWebSockets.delete(actorId);
1082
- }
1083
1156
  return actor;
1084
1157
  }
1085
1158
  // MARK: Start
@@ -1231,22 +1304,33 @@ var Runner = class {
1231
1304
  this.#config.onShutdown();
1232
1305
  }
1233
1306
  // MARK: Networking
1307
+ get pegboardEndpoint() {
1308
+ return this.#config.pegboardEndpoint || this.#config.endpoint;
1309
+ }
1234
1310
  get pegboardUrl() {
1235
- const endpoint = this.#config.pegboardEndpoint || this.#config.endpoint;
1236
- const wsEndpoint = endpoint.replace("http://", "ws://").replace("https://", "wss://");
1237
- return `${wsEndpoint}?protocol_version=${PROTOCOL_VERSION}&namespace=${encodeURIComponent(this.#config.namespace)}&runner_key=${encodeURIComponent(this.#config.runnerKey)}`;
1311
+ const wsEndpoint = this.pegboardEndpoint.replace("http://", "ws://").replace("https://", "wss://");
1312
+ const baseUrl = wsEndpoint.endsWith("/") ? wsEndpoint.slice(0, -1) : wsEndpoint;
1313
+ return `${baseUrl}/runners/connect?protocol_version=${PROTOCOL_VERSION}&namespace=${encodeURIComponent(this.#config.namespace)}&runner_key=${encodeURIComponent(this.#config.runnerKey)}`;
1238
1314
  }
1239
1315
  // MARK: Runner protocol
1240
1316
  async #openPegboardWebSocket() {
1241
- const protocols = ["rivet", `rivet_target.runner`];
1317
+ var _a;
1318
+ const protocols = ["rivet"];
1242
1319
  if (this.config.token)
1243
1320
  protocols.push(`rivet_token.${this.config.token}`);
1244
1321
  const WS = await importWebSocket();
1245
1322
  const ws = new WS(this.pegboardUrl, protocols);
1246
1323
  this.#pegboardWebSocket = ws;
1324
+ (_a = logger()) == null ? void 0 : _a.info({
1325
+ msg: "connecting",
1326
+ endpoint: this.pegboardEndpoint,
1327
+ namespace: this.#config.namespace,
1328
+ runnerKey: this.#config.runnerKey,
1329
+ hasToken: !!this.config.token
1330
+ });
1247
1331
  ws.addEventListener("open", () => {
1248
- var _a;
1249
- (_a = logger()) == null ? void 0 : _a.info({ msg: "Connected" });
1332
+ var _a2;
1333
+ (_a2 = logger()) == null ? void 0 : _a2.info({ msg: "connected" });
1250
1334
  this.#reconnectAttempt = 0;
1251
1335
  if (this.#reconnectTimeout) {
1252
1336
  clearTimeout(this.#reconnectTimeout);
@@ -1276,9 +1360,8 @@ var Runner = class {
1276
1360
  val: init
1277
1361
  });
1278
1362
  this.#processUnsentKvRequests();
1279
- const pingInterval = 1e3;
1280
1363
  const pingLoop = setInterval(() => {
1281
- var _a2;
1364
+ var _a3;
1282
1365
  if (ws.readyState === 1) {
1283
1366
  this.__sendToServer({
1284
1367
  tag: "ToServerPing",
@@ -1288,21 +1371,21 @@ var Runner = class {
1288
1371
  });
1289
1372
  } else {
1290
1373
  clearInterval(pingLoop);
1291
- (_a2 = logger()) == null ? void 0 : _a2.info({
1374
+ (_a3 = logger()) == null ? void 0 : _a3.info({
1292
1375
  msg: "WebSocket not open, stopping ping loop",
1293
1376
  runnerId: this.runnerId
1294
1377
  });
1295
1378
  }
1296
- }, pingInterval);
1379
+ }, RUNNER_PING_INTERVAL);
1297
1380
  this.#pingLoop = pingLoop;
1298
1381
  const ackInterval = 5 * 60 * 1e3;
1299
1382
  const ackLoop = setInterval(() => {
1300
- var _a2;
1383
+ var _a3;
1301
1384
  if (ws.readyState === 1) {
1302
1385
  this.#sendCommandAcknowledgment();
1303
1386
  } else {
1304
1387
  clearInterval(ackLoop);
1305
- (_a2 = logger()) == null ? void 0 : _a2.info({
1388
+ (_a3 = logger()) == null ? void 0 : _a3.info({
1306
1389
  msg: "WebSocket not open, stopping ack loop",
1307
1390
  runnerId: this.runnerId
1308
1391
  });
@@ -1311,7 +1394,7 @@ var Runner = class {
1311
1394
  this.#ackInterval = ackLoop;
1312
1395
  });
1313
1396
  ws.addEventListener("message", async (ev) => {
1314
- var _a, _b, _c, _d;
1397
+ var _a2, _b, _c, _d;
1315
1398
  let buf;
1316
1399
  if (ev.data instanceof Blob) {
1317
1400
  buf = new Uint8Array(await ev.data.arrayBuffer());
@@ -1327,7 +1410,7 @@ var Runner = class {
1327
1410
  this.runnerId = init.runnerId;
1328
1411
  this.#eventHistory.length = 0;
1329
1412
  }
1330
- this.#runnerLostThreshold = ((_a = init.metadata) == null ? void 0 : _a.runnerLostThreshold) ? Number(init.metadata.runnerLostThreshold) : void 0;
1413
+ this.#runnerLostThreshold = ((_a2 = init.metadata) == null ? void 0 : _a2.runnerLostThreshold) ? Number(init.metadata.runnerLostThreshold) : void 0;
1331
1414
  (_b = logger()) == null ? void 0 : _b.info({
1332
1415
  msg: "received init",
1333
1416
  runnerId: init.runnerId,
@@ -1354,8 +1437,8 @@ var Runner = class {
1354
1437
  }
1355
1438
  });
1356
1439
  ws.addEventListener("error", (ev) => {
1357
- var _a, _b;
1358
- (_a = logger()) == null ? void 0 : _a.error({
1440
+ var _a2, _b;
1441
+ (_a2 = logger()) == null ? void 0 : _a2.error({
1359
1442
  msg: `WebSocket error: ${ev.error}`,
1360
1443
  runnerId: this.runnerId
1361
1444
  });
@@ -1374,14 +1457,14 @@ var Runner = class {
1374
1457
  }
1375
1458
  });
1376
1459
  ws.addEventListener("close", async (ev) => {
1377
- var _a, _b, _c;
1378
- (_a = logger()) == null ? void 0 : _a.info({
1460
+ var _a2, _b, _c;
1461
+ (_a2 = logger()) == null ? void 0 : _a2.info({
1379
1462
  msg: "connection closed",
1380
1463
  runnerId: this.runnerId,
1381
1464
  code: ev.code,
1382
1465
  reason: ev.reason.toString()
1383
1466
  });
1384
- this.#config.onDisconnected();
1467
+ this.#config.onDisconnected(ev.code, ev.reason);
1385
1468
  if (ev.reason.toString().startsWith("ws.eviction")) {
1386
1469
  (_b = logger()) == null ? void 0 : _b.info({
1387
1470
  msg: "runner evicted",
@@ -1947,6 +2030,10 @@ var Runner = class {
1947
2030
  });
1948
2031
  }
1949
2032
  }
2033
+ sendWebsocketMessageAck(requestId, index) {
2034
+ var _a;
2035
+ (_a = this.#tunnel) == null ? void 0 : _a.__ackWebsocketMessage(requestId, index);
2036
+ }
1950
2037
  getServerlessInitPacket() {
1951
2038
  if (!this.runnerId) return void 0;
1952
2039
  const data = protocol.encodeToServerlessServer({