@zackbart/connecta 0.7.5 → 0.7.7

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.
Files changed (72) hide show
  1. package/CHANGELOG.md +108 -0
  2. package/README.md +1 -0
  3. package/dist/activity.d.ts +17 -0
  4. package/dist/activity.d.ts.map +1 -1
  5. package/dist/activity.js.map +1 -1
  6. package/dist/auth/clerk.d.ts.map +1 -1
  7. package/dist/auth/clerk.js +101 -0
  8. package/dist/auth/clerk.js.map +1 -1
  9. package/dist/auth/downstream-oauth.d.ts +57 -20
  10. package/dist/auth/downstream-oauth.d.ts.map +1 -1
  11. package/dist/auth/downstream-oauth.js +275 -67
  12. package/dist/auth/downstream-oauth.js.map +1 -1
  13. package/dist/connectors/remote-mcp.d.ts.map +1 -1
  14. package/dist/connectors/remote-mcp.js +165 -103
  15. package/dist/connectors/remote-mcp.js.map +1 -1
  16. package/dist/execute.d.ts.map +1 -1
  17. package/dist/execute.js +11 -0
  18. package/dist/execute.js.map +1 -1
  19. package/dist/executor-admission.d.ts +18 -1
  20. package/dist/executor-admission.d.ts.map +1 -1
  21. package/dist/executor-admission.js +82 -3
  22. package/dist/executor-admission.js.map +1 -1
  23. package/dist/executors/quickjs-protocol.d.ts +1 -0
  24. package/dist/executors/quickjs-protocol.d.ts.map +1 -1
  25. package/dist/executors/quickjs-protocol.js +7 -4
  26. package/dist/executors/quickjs-protocol.js.map +1 -1
  27. package/dist/executors/quickjs-runtime.d.ts.map +1 -1
  28. package/dist/executors/quickjs-runtime.js +22 -9
  29. package/dist/executors/quickjs-runtime.js.map +1 -1
  30. package/dist/executors/quickjs.d.ts.map +1 -1
  31. package/dist/executors/quickjs.js +44 -10
  32. package/dist/executors/quickjs.js.map +1 -1
  33. package/dist/index.d.ts +31 -2
  34. package/dist/index.d.ts.map +1 -1
  35. package/dist/index.js +38 -1
  36. package/dist/index.js.map +1 -1
  37. package/dist/registry.d.ts +12 -0
  38. package/dist/registry.d.ts.map +1 -1
  39. package/dist/registry.js +70 -15
  40. package/dist/registry.js.map +1 -1
  41. package/dist/server.d.ts +3 -0
  42. package/dist/server.d.ts.map +1 -1
  43. package/dist/server.js +413 -35
  44. package/dist/server.js.map +1 -1
  45. package/dist/storage/file.d.ts.map +1 -1
  46. package/dist/storage/file.js +8 -0
  47. package/dist/storage/file.js.map +1 -1
  48. package/dist/types.d.ts +47 -0
  49. package/dist/types.d.ts.map +1 -1
  50. package/dist/ui.d.ts +7 -1
  51. package/dist/ui.d.ts.map +1 -1
  52. package/dist/ui.js +118 -4
  53. package/dist/ui.js.map +1 -1
  54. package/dist/version.d.ts +1 -1
  55. package/dist/version.js +1 -1
  56. package/package.json +2 -1
  57. package/src/activity.ts +20 -0
  58. package/src/auth/clerk.ts +124 -0
  59. package/src/auth/downstream-oauth.ts +359 -68
  60. package/src/connectors/remote-mcp.ts +172 -104
  61. package/src/execute.ts +11 -0
  62. package/src/executor-admission.ts +90 -3
  63. package/src/executors/quickjs-protocol.ts +7 -4
  64. package/src/executors/quickjs-runtime.ts +31 -9
  65. package/src/executors/quickjs.ts +61 -12
  66. package/src/index.ts +90 -1
  67. package/src/registry.ts +79 -19
  68. package/src/server.ts +523 -45
  69. package/src/storage/file.ts +7 -0
  70. package/src/types.ts +50 -0
  71. package/src/ui.ts +124 -3
  72. package/src/version.ts +1 -1
@@ -393,7 +393,7 @@ interface ConnectionState {
393
393
  connecting: Promise<void> | null;
394
394
  authRequired: boolean;
395
395
  provider: KvOAuthProvider | null;
396
- connectedGeneration: number | null;
396
+ connectedGeneration: string | null;
397
397
  /**
398
398
  * One-way latch: set by closeScope and never cleared, so neither a late
399
399
  * connect nor a `reset()` can cache a client into a scope that is already
@@ -451,6 +451,16 @@ export function remoteMcp(id: string, opts: RemoteMcpOptions): Connector {
451
451
  { cause },
452
452
  );
453
453
 
454
+ class OperatorDisconnectedError extends ConnectorCallError {
455
+ constructor() {
456
+ super(
457
+ "auth_required",
458
+ `Connector "${id}" was disconnected by an operator — explicitly start authorization to reconnect it.`,
459
+ );
460
+ }
461
+ }
462
+ const operatorDisconnectedError = () => new OperatorDisconnectedError();
463
+
454
464
  const scopeEndedError = () =>
455
465
  new Error(`Connector "${id}" scope ended during connection.`);
456
466
 
@@ -518,16 +528,23 @@ export function remoteMcp(id: string, opts: RemoteMcpOptions): Connector {
518
528
  return state.provider;
519
529
  };
520
530
 
531
+ const newProvider = (ctx: ConnectorContext): KvOAuthProvider =>
532
+ new KvOAuthProvider(
533
+ id,
534
+ ctx.storage,
535
+ `${ctx.baseUrl}/oauth/callback/${id}`,
536
+ );
537
+
521
538
  const buildTransport = (
522
539
  ctx: ConnectorContext,
523
- state: ConnectionState,
540
+ provider: KvOAuthProvider | null,
524
541
  ): Transport => {
525
542
  if (opts._transportFactory) return opts._transportFactory(ctx);
526
543
  const url = new URL(opts.url);
527
544
  const guardedFetch = redirectSafeFetch(id, opts.redirects);
528
545
  if (opts.auth?.type === "oauth") {
529
546
  return new StreamableHTTPClientTransport(url, {
530
- authProvider: getProvider(ctx, state),
547
+ authProvider: provider ?? newProvider(ctx),
531
548
  fetch: guardedFetch,
532
549
  });
533
550
  }
@@ -547,6 +564,7 @@ export function remoteMcp(id: string, opts: RemoteMcpOptions): Connector {
547
564
  state.transport = null;
548
565
  state.connecting = null;
549
566
  state.authRequired = false;
567
+ state.provider = null;
550
568
  state.connectedGeneration = null;
551
569
  // `closed` is deliberately not cleared — see ConnectionState.
552
570
  };
@@ -563,97 +581,160 @@ export function remoteMcp(id: string, opts: RemoteMcpOptions): Connector {
563
581
  new UnauthorizedError("Downstream authorization is no longer valid."),
564
582
  );
565
583
  }
584
+ // Read the OAuth epoch before trusting either a cached client or starting a
585
+ // transport. A disconnected epoch is a durable operator instruction, not
586
+ // merely the absence of credentials: passive status/tool probes must not
587
+ // turn it back into a pending consent flow.
588
+ let oauthGeneration: string | undefined;
589
+ if (isOauth && (state.client || state.connecting)) {
590
+ const provider = getProvider(ctx, state);
591
+ oauthGeneration = await provider.generation();
592
+ if (provider.isOperatorDisconnectedGeneration(oauthGeneration)) {
593
+ const connecting = state.connecting;
594
+ const client = state.client;
595
+ const transport = state.transport;
596
+ reset(state);
597
+ void connecting?.catch(() => {});
598
+ try {
599
+ if (client) await client.close();
600
+ else await transport?.close();
601
+ } catch {
602
+ // The disconnected epoch is authoritative even if local close fails.
603
+ }
604
+ throw operatorDisconnectedError();
605
+ }
606
+ }
566
607
  // Cross-isolate force re-auth: another isolate bumped the KV generation and
567
608
  // wiped credentials. This request's cached client still speaks the old
568
609
  // token — drop it so the next connect runs against current state.
569
- if (state.client && isOauth && state.connectedGeneration !== null) {
570
- const generation = await getProvider(ctx, state).generation();
610
+ if (state.client && oauthGeneration !== undefined && state.connectedGeneration !== null) {
571
611
  if (state.closed) throw scopeEndedError();
572
- if (generation !== state.connectedGeneration) {
612
+ if (oauthGeneration !== state.connectedGeneration) {
573
613
  reset(state);
574
614
  }
575
615
  }
576
616
  if (state.closed) throw scopeEndedError();
577
617
  if (state.client) return;
578
- state.connecting ??= (async () => {
579
- const provider = isOauth ? getProvider(ctx, state) : null;
580
- const genAtStart = provider ? await provider.generation() : 0;
581
- if (state.closed) throw scopeEndedError();
582
- // Stamp the provider so any saveTokens/saveClientInformation the SDK fires
583
- // during this connect (code exchange, DCR) or during a later refresh on
584
- // the resulting client — is dropped if a concurrent force bumps the
585
- // generation past this point, instead of re-persisting wiped credentials.
586
- provider?.captureGeneration(genAtStart);
587
- // The SDK defaults to AJV, which compiles every advertised outputSchema
588
- // with `new Function`. Cloudflare Workers prohibit dynamic code
589
- // generation, so a remote such as Stripe fails during tools/list unless
590
- // the SDK's edge-safe validator is selected explicitly.
591
- const c = new Client(
592
- { name: "connecta", version: CONNECTA_VERSION },
593
- { jsonSchemaValidator: new CfWorkerJsonSchemaValidator() },
594
- );
595
- const t = buildTransport(ctx, state);
596
- state.transport = t;
597
- try {
598
- await c.connect(t);
599
- // A probe deadline can end its scope while connect is still in flight.
600
- // The transport is closed immediately by closeScope; if connect wins
601
- // that race anyway, close the resulting client rather than resurrecting
602
- // a session in the detached state object.
603
- if (state.closed) {
618
+ if (!state.connecting) {
619
+ let attempt!: Promise<void>;
620
+ attempt = (async () => {
621
+ const ownsAttempt = () =>
622
+ state.connecting === attempt && !state.closed;
623
+ const abandon = async (owner: Client | Transport) => {
604
624
  try {
605
- await c.close();
625
+ await owner.close();
606
626
  } catch {
607
- // The scope has already been discarded either way.
627
+ // The attempt is detached either way.
608
628
  }
609
629
  throw scopeEndedError();
630
+ };
631
+ // Let the assignment immediately below this async IIFE publish
632
+ // `state.connecting = attempt` before ownership is checked. OAuth's
633
+ // generation read naturally yields; unauthenticated transports do not.
634
+ await Promise.resolve();
635
+ // A provider belongs to exactly one connect attempt. A force reset can
636
+ // abandon that attempt while its transport still holds the provider;
637
+ // the replacement must never mutate the abandoned provider's epoch.
638
+ const provider = isOauth ? newProvider(ctx) : null;
639
+ const genAtStart = provider ? await provider.generation() : "";
640
+ if (!ownsAttempt()) throw scopeEndedError();
641
+ if (provider?.isOperatorDisconnectedGeneration(genAtStart)) {
642
+ throw operatorDisconnectedError();
610
643
  }
611
- // A force re-auth that landed WHILE we were connecting wiped the creds
612
- // this client just bound to. Discard it rather than cache a connection
613
- // that resurrects the wiped-and-reauthorized connector from a stale
614
- // isolate. Surfaces as auth_required the connector genuinely needs
615
- // re-consent now.
616
- if (provider) {
617
- const generation = await provider.generation();
618
- // closeScope can land while the generation read is pending, after
619
- // connect succeeded but before this client is cached. Discard the
620
- // client on that side of the await too.
621
- if (state.closed) {
622
- try {
623
- await c.close();
624
- } catch {
625
- // The scope has already been discarded either way.
644
+ provider?.captureGeneration(genAtStart);
645
+ // The SDK defaults to AJV, which compiles every advertised outputSchema
646
+ // with `new Function`. Cloudflare Workers prohibit dynamic code
647
+ // generation, so a remote such as Stripe fails during tools/list unless
648
+ // the SDK's edge-safe validator is selected explicitly.
649
+ const c = new Client(
650
+ { name: "connecta", version: CONNECTA_VERSION },
651
+ { jsonSchemaValidator: new CfWorkerJsonSchemaValidator() },
652
+ );
653
+ const t = buildTransport(ctx, provider);
654
+ if (!ownsAttempt()) await abandon(t);
655
+ state.transport = t;
656
+ try {
657
+ await c.connect(t);
658
+ // A probe deadline can end its scope while connect is still in flight.
659
+ // The transport is closed immediately by closeScope; if connect wins
660
+ // that race anyway, close the resulting client rather than
661
+ // resurrecting a session in the detached state object.
662
+ if (!ownsAttempt()) await abandon(c);
663
+ // A force re-auth that landed WHILE we were connecting wiped the
664
+ // credentials this client just bound to. Discard it rather than
665
+ // cache a stale-isolate connection.
666
+ if (provider) {
667
+ const generation = await provider.generation();
668
+ // closeScope can land while the generation read is pending, after
669
+ // connect succeeded but before this client is cached. Discard the
670
+ // client on that side of the await too.
671
+ if (!ownsAttempt()) await abandon(c);
672
+ if (generation !== genAtStart) {
673
+ try {
674
+ await c.close();
675
+ } catch {
676
+ // discarding either way
677
+ }
678
+ throw new UnauthorizedError(
679
+ "Connector was re-authorized during connect; reconnect required.",
680
+ );
626
681
  }
627
- throw scopeEndedError();
628
682
  }
629
- if (generation !== genAtStart) {
630
- try {
631
- await c.close();
632
- } catch {
633
- // discarding either way
634
- }
635
- throw new UnauthorizedError(
636
- "Connector was re-authorized during connect; reconnect required.",
637
- );
683
+ if (!ownsAttempt()) await abandon(c);
684
+ state.client = c;
685
+ state.connectedGeneration = genAtStart;
686
+ state.authRequired = false;
687
+ } catch (err) {
688
+ // Only a real 401/UnauthorizedError means auth is the problem — a
689
+ // network error on an oauth connector must surface as "error", not
690
+ // "auth_required".
691
+ if (err instanceof UnauthorizedError && ownsAttempt()) {
692
+ state.authRequired = true;
638
693
  }
694
+ if (err instanceof UnauthorizedError) {
695
+ throw authRequiredError(err);
696
+ }
697
+ throw err;
698
+ } finally {
699
+ // Force reset may have abandoned this attempt and installed a new one
700
+ // in the same request scope. An old completion must not erase the new
701
+ // promise and allow a third concurrent connect.
702
+ if (state.connecting === attempt) state.connecting = null;
639
703
  }
640
- state.client = c;
641
- state.connectedGeneration = genAtStart;
642
- state.authRequired = false;
643
- } catch (err) {
644
- // Only a real 401/UnauthorizedError means auth is the problem — a
645
- // network error on an oauth connector must surface as "error", not
646
- // "auth_required".
647
- if (err instanceof UnauthorizedError) {
648
- state.authRequired = true;
649
- throw authRequiredError(err);
704
+ })();
705
+ state.connecting = attempt;
706
+ }
707
+ return state.connecting;
708
+ };
709
+
710
+ const disconnectAuthorization = async (
711
+ ctx: ConnectorContext,
712
+ state: ConnectionState,
713
+ operatorDisconnected = false,
714
+ ): Promise<void> => {
715
+ const provider = getProvider(ctx, state);
716
+ // Publish the replacement epoch before waiting on or closing any
717
+ // request-local transport. A hung connect therefore cannot delay the
718
+ // fence, and every late OAuth write stays in the older namespace.
719
+ const connecting = state.connecting;
720
+ try {
721
+ await provider.resetAuthorization(operatorDisconnected);
722
+ } finally {
723
+ // Consume the abandoned connect and close whichever half of the
724
+ // client/transport exists. Reset is unconditional because KV may already
725
+ // be fenced behind a newer epoch after a cleanup error.
726
+ void connecting?.catch(() => {});
727
+ try {
728
+ if (state.client) {
729
+ await state.client.close();
730
+ } else {
731
+ await state.transport?.close();
650
732
  }
651
- throw err;
652
- } finally {
653
- state.connecting = null;
733
+ } catch {
734
+ // best-effort; the state is discarded either way
654
735
  }
655
- })();
656
- return state.connecting;
736
+ reset(state);
737
+ }
657
738
  };
658
739
 
659
740
  const connector: Connector = {
@@ -760,7 +841,7 @@ export function remoteMcp(id: string, opts: RemoteMcpOptions): Connector {
760
841
  // Classify that exactly like connect-time and call-time authorization
761
842
  // failures, and latch it for the rest of this request scope.
762
843
  if (err instanceof UnauthorizedError) {
763
- state.authRequired = true;
844
+ if (state.client === client) state.authRequired = true;
764
845
  throw authRequiredError(err);
765
846
  }
766
847
  throw err;
@@ -788,8 +869,9 @@ export function remoteMcp(id: string, opts: RemoteMcpOptions): Connector {
788
869
  async callTool(name, args, ctx) {
789
870
  const state = stateFor(ctx);
790
871
  await ensureConnected(ctx, state);
872
+ const client = state.client!;
791
873
  try {
792
- return await state.client!.callTool(
874
+ return await client.callTool(
793
875
  {
794
876
  name,
795
877
  arguments: (args ?? {}) as Record<string, unknown>,
@@ -805,7 +887,7 @@ export function remoteMcp(id: string, opts: RemoteMcpOptions): Connector {
805
887
  } catch (err) {
806
888
  // A grant revoked after connect surfaces here, not in ensureConnected.
807
889
  if (err instanceof UnauthorizedError) {
808
- state.authRequired = true;
890
+ if (state.client === client) state.authRequired = true;
809
891
  throw authRequiredError(err);
810
892
  }
811
893
  throw err;
@@ -860,6 +942,9 @@ export function remoteMcp(id: string, opts: RemoteMcpOptions): Connector {
860
942
  message: "Authorization required — open the URL to connect.",
861
943
  };
862
944
  }
945
+ if (err instanceof OperatorDisconnectedError) {
946
+ return { state: "auth_required", message: err.message };
947
+ }
863
948
  return { state: "error", message: msg(err) };
864
949
  }
865
950
  },
@@ -867,12 +952,11 @@ export function remoteMcp(id: string, opts: RemoteMcpOptions): Connector {
867
952
  async finishAuth(code, ctx) {
868
953
  const state = stateFor(ctx);
869
954
  const provider = getProvider(ctx, state);
870
- // The provider here may carry no captured generation, so its token saves
871
- // fail open. That is safe only because generation advances solely via the
872
- // force path, which always wipes oauth:state so verifyState rejects any
873
- // pre-force callback before this runs. Keep those two facts coupled.
955
+ // verifyState ran on this request-scoped provider first and captured the
956
+ // pending flow's generation. If force reset races the exchange, any late
957
+ // token write remains tagged with that older generation and is unreadable.
874
958
  const t = (state.transport ??
875
- buildTransport(ctx, state)) as StreamableHTTPClientTransport;
959
+ buildTransport(ctx, provider)) as StreamableHTTPClientTransport;
876
960
  await t.finishAuth(code);
877
961
  await provider.clearPending();
878
962
  // Reset so the next use reconnects with the freshly stored tokens.
@@ -895,31 +979,15 @@ export function remoteMcp(id: string, opts: RemoteMcpOptions): Connector {
895
979
  return getProvider(ctx, state).verifyState(oauthState);
896
980
  };
897
981
 
982
+ connector.disconnectAuth = async (ctx) => {
983
+ await disconnectAuthorization(ctx, stateFor(ctx), true);
984
+ };
985
+
898
986
  connector.startAuth = async (ctx, startOpts) => {
899
987
  const state = stateFor(ctx);
900
988
  const p = getProvider(ctx, state);
901
- if (startOpts?.force) {
902
- // Wipe stored credentials and drop the live connection so the next
903
- // connect attempt runs the flow from scratch (DCR + PKCE + consent).
904
- // Fence the in-flight connect first: a late-completing attempt must not
905
- // resurrect the credentials we're about to wipe, nor leave `client` set
906
- // (which would make ensureConnected below report already-authorized and
907
- // silently defeat force).
908
- await state.connecting?.catch(() => {});
909
- try {
910
- await state.client?.close();
911
- } catch {
912
- // best-effort; the connection is being discarded either way
913
- }
914
- // Bump the shared generation FIRST so any other isolate — one mid-
915
- // connect, or on its next tool call — sees the advance and drops its
916
- // client instead of keeping the token we're about to revoke.
917
- await p.bumpGeneration();
918
- // Wipe KV before dropping in-memory state so nothing racing back in can
919
- // write tokens over a half-cleared slot.
920
- await p.invalidateCredentials("all");
921
- await p.clearPending();
922
- reset(state);
989
+ if (startOpts?.force || (await p.operatorDisconnected())) {
990
+ await disconnectAuthorization(ctx, state);
923
991
  } else {
924
992
  // A consent URL already outstanding? Re-issue it rather than re-running
925
993
  // the SDK flow, which would overwrite the PKCE verifier and invalidate
package/src/execute.ts CHANGED
@@ -513,6 +513,11 @@ export function createExecuteTool(
513
513
  // catalogs, request scopes, or one-closure-per-tool provider arrays.
514
514
  if (isAdmittingExecutor(executor)) {
515
515
  lease = await executor.acquire({ signal: controller.signal });
516
+ if ((lease.waitMs ?? 0) > 0) {
517
+ logger.debug("[connecta] execute_code admitted after queue wait", {
518
+ waitMs: lease.waitMs,
519
+ });
520
+ }
516
521
  }
517
522
  const providers = await buildSandboxProviders(
518
523
  registry,
@@ -532,6 +537,12 @@ export function createExecuteTool(
532
537
  : await executor.execute(code, providers);
533
538
  } catch (err) {
534
539
  if (err instanceof ExecutorAdmissionError) {
540
+ if (err.code === "executor_overloaded") {
541
+ logger.warn("[connecta] execute_code admission rejected", {
542
+ code: err.code,
543
+ retryAfterMs: err.retryAfterMs,
544
+ });
545
+ }
535
546
  const result = jsonResult({
536
547
  error: {
537
548
  code: err.code,
@@ -1,6 +1,8 @@
1
1
  import type {
2
2
  AdmittingExecutor,
3
+ AdmissionSnapshot,
3
4
  Executor,
5
+ ExecutorLease,
4
6
  } from "./types.js";
5
7
 
6
8
  export type ExecutorAdmissionErrorCode =
@@ -35,10 +37,13 @@ export class ExecutorAdmissionError extends Error {
35
37
  }
36
38
 
37
39
  export interface AdmissionLease {
40
+ /** Time spent waiting behind active work. Zero for immediate admission. */
41
+ readonly waitMs: number;
38
42
  release(): void;
39
43
  }
40
44
 
41
45
  interface Waiter {
46
+ queuedAt: number;
42
47
  resolve: (lease: AdmissionLease) => void;
43
48
  reject: (error: ExecutorAdmissionError) => void;
44
49
  signal?: AbortSignal;
@@ -82,6 +87,14 @@ export class AdmissionController {
82
87
  private active = 0;
83
88
  private closed = false;
84
89
  private readonly waiters: Waiter[] = [];
90
+ private admittedTotal = 0;
91
+ private queuedTotal = 0;
92
+ private rejectedTotal = 0;
93
+ private cancelledTotal = 0;
94
+ private closedTotal = 0;
95
+ private queueWaitCount = 0;
96
+ private queueWaitTotalMs = 0;
97
+ private queueWaitMaxMs = 0;
85
98
 
86
99
  constructor(options: AdmissionControllerOptions) {
87
100
  this.concurrency = positiveWhole(options.concurrency, "concurrency");
@@ -107,8 +120,33 @@ export class AdmissionController {
107
120
  return this.waiters.length;
108
121
  }
109
122
 
123
+ snapshot(): AdmissionSnapshot {
124
+ return {
125
+ concurrency: this.concurrency,
126
+ maxQueueSize: this.maxQueueSize,
127
+ queueTimeoutMs: this.queueTimeoutMs,
128
+ retryAfterMs: this.retryAfterMs,
129
+ active: this.active,
130
+ queued: this.waiters.length,
131
+ closed: this.closed,
132
+ totals: {
133
+ admitted: this.admittedTotal,
134
+ queued: this.queuedTotal,
135
+ rejected: this.rejectedTotal,
136
+ cancelled: this.cancelledTotal,
137
+ closed: this.closedTotal,
138
+ },
139
+ queueWaitMs: {
140
+ count: this.queueWaitCount,
141
+ total: this.queueWaitTotalMs,
142
+ max: this.queueWaitMaxMs,
143
+ },
144
+ };
145
+ }
146
+
110
147
  acquire(options: { signal?: AbortSignal } = {}): Promise<AdmissionLease> {
111
148
  if (this.closed) {
149
+ this.closedTotal++;
112
150
  return Promise.reject(
113
151
  new ExecutorAdmissionError(
114
152
  "executor_closed",
@@ -117,6 +155,7 @@ export class AdmissionController {
117
155
  );
118
156
  }
119
157
  if (options.signal?.aborted) {
158
+ this.cancelledTotal++;
120
159
  return Promise.reject(
121
160
  new ExecutorAdmissionError(
122
161
  "executor_cancelled",
@@ -126,14 +165,17 @@ export class AdmissionController {
126
165
  }
127
166
  if (this.active < this.concurrency) {
128
167
  this.active++;
129
- return Promise.resolve(this.makeLease());
168
+ this.admittedTotal++;
169
+ return Promise.resolve(this.makeLease(0));
130
170
  }
131
171
  if (this.waiters.length >= this.maxQueueSize) {
172
+ this.rejectedTotal++;
132
173
  return Promise.reject(this.overloaded("Executor queue is full."));
133
174
  }
134
175
 
135
176
  return new Promise<AdmissionLease>((resolve, reject) => {
136
177
  const waiter: Waiter = {
178
+ queuedAt: Date.now(),
137
179
  resolve,
138
180
  reject,
139
181
  ...(options.signal ? { signal: options.signal } : {}),
@@ -141,6 +183,7 @@ export class AdmissionController {
141
183
  waiter.onAbort = () => {
142
184
  if (!this.remove(waiter)) return;
143
185
  this.cleanup(waiter);
186
+ this.cancelledTotal++;
144
187
  reject(
145
188
  new ExecutorAdmissionError(
146
189
  "executor_cancelled",
@@ -152,6 +195,7 @@ export class AdmissionController {
152
195
  waiter.timer = setTimeout(() => {
153
196
  if (!this.remove(waiter)) return;
154
197
  this.cleanup(waiter);
198
+ this.rejectedTotal++;
155
199
  reject(
156
200
  this.overloaded(
157
201
  `Executor admission timed out after ${this.queueTimeoutMs}ms.`,
@@ -159,6 +203,7 @@ export class AdmissionController {
159
203
  );
160
204
  }, this.queueTimeoutMs);
161
205
  this.waiters.push(waiter);
206
+ this.queuedTotal++;
162
207
  });
163
208
  }
164
209
 
@@ -167,6 +212,7 @@ export class AdmissionController {
167
212
  this.closed = true;
168
213
  for (const waiter of this.waiters.splice(0)) {
169
214
  this.cleanup(waiter);
215
+ this.closedTotal++;
170
216
  waiter.reject(
171
217
  new ExecutorAdmissionError(
172
218
  "executor_closed",
@@ -182,9 +228,10 @@ export class AdmissionController {
182
228
  });
183
229
  }
184
230
 
185
- private makeLease(): AdmissionLease {
231
+ private makeLease(waitMs: number): AdmissionLease {
186
232
  let released = false;
187
233
  return {
234
+ waitMs,
188
235
  release: () => {
189
236
  if (released) return;
190
237
  released = true;
@@ -199,8 +246,13 @@ export class AdmissionController {
199
246
  const waiter = this.waiters.shift();
200
247
  if (!waiter) return;
201
248
  this.cleanup(waiter);
249
+ const waitMs = Math.max(0, Date.now() - waiter.queuedAt);
250
+ this.admittedTotal++;
251
+ this.queueWaitCount++;
252
+ this.queueWaitTotalMs += waitMs;
253
+ this.queueWaitMaxMs = Math.max(this.queueWaitMaxMs, waitMs);
202
254
  this.active++;
203
- waiter.resolve(this.makeLease());
255
+ waiter.resolve(this.makeLease(waitMs));
204
256
  }
205
257
 
206
258
  private remove(waiter: Waiter): boolean {
@@ -227,3 +279,38 @@ export function isAdmittingExecutor(
227
279
  typeof (executor as { acquire?: unknown }).acquire === "function"
228
280
  );
229
281
  }
282
+
283
+ /**
284
+ * Give a structurally-compatible but otherwise unbounded executor the same
285
+ * admission contract as the built-in Node executor. The wrapper owns only the
286
+ * queue; closing the underlying runtime remains the Connecta lifecycle's job.
287
+ */
288
+ export function withExecutorAdmission(
289
+ executor: Executor,
290
+ admission: AdmissionController,
291
+ ): AdmittingExecutor {
292
+ return {
293
+ async acquire(options = {}): Promise<ExecutorLease> {
294
+ const token = await admission.acquire(options);
295
+ let released = false;
296
+ return {
297
+ waitMs: token.waitMs,
298
+ execute: (code, providers) => executor.execute(code, providers),
299
+ release: () => {
300
+ if (released) return;
301
+ released = true;
302
+ token.release();
303
+ },
304
+ };
305
+ },
306
+ async execute(code, providers) {
307
+ const lease = await this.acquire();
308
+ try {
309
+ return await lease.execute(code, providers);
310
+ } finally {
311
+ lease.release();
312
+ }
313
+ },
314
+ admissionSnapshot: () => admission.snapshot(),
315
+ };
316
+ }
@@ -1,11 +1,14 @@
1
1
  import type { ExecuteResult } from "../types.js";
2
2
  import type { QuickJsRuntimeOptions } from "./quickjs-runtime.js";
3
3
 
4
- // The guest result is shaped to 24k characters before transport and QuickJS
5
- // capture already bounds logs to 256k characters. Every complete message is
6
- // measured against this ceiling before process.send; one MiB leaves room for
7
- // multibyte log text and envelope escaping while remaining a hard IPC bound.
4
+ // An execution result is serialized once into payloadJson and again as that
5
+ // string is embedded in ChildToParentMessage. Captured logs therefore get a
6
+ // separate 512 KiB budget measured after both JSON encodings. The final result
7
+ // is shaped to 24k characters; even if every character takes its worst-case
8
+ // seven transport bytes, that leaves ample structural overhead below this hard
9
+ // process.send ceiling.
8
10
  export const MAX_QUICKJS_IPC_BYTES = 1024 * 1024;
11
+ export const MAX_QUICKJS_LOG_TRANSPORT_BYTES = 512 * 1024;
9
12
  /** Preserve #84's stopgap before a host value enters the child/WASM process. */
10
13
  export const MAX_QUICKJS_HOST_RPC_BYTES = 256 * 1024;
11
14