@opendatalabs/personal-server-ts-lite 1.37.0 → 1.38.1

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 (88) hide show
  1. package/dist/account-mode-store.d.ts +11 -0
  2. package/dist/account-mode-store.d.ts.map +1 -0
  3. package/dist/account-mode-store.js +68 -0
  4. package/dist/account-mode-store.js.map +1 -0
  5. package/dist/additions-worker.bundle.js +135 -37
  6. package/dist/browser-runtime.d.ts +88 -1
  7. package/dist/browser-runtime.d.ts.map +1 -1
  8. package/dist/browser-runtime.js +135 -12
  9. package/dist/browser-runtime.js.map +1 -1
  10. package/dist/browser-tls-rustls/browser_tls_rustls_bg.wasm +0 -0
  11. package/dist/client.d.ts +42 -3
  12. package/dist/client.d.ts.map +1 -1
  13. package/dist/client.js +130 -115
  14. package/dist/client.js.map +1 -1
  15. package/dist/history-probe-worker.bundle.js +66 -29
  16. package/dist/history-probe.worker.d.ts.map +1 -1
  17. package/dist/history-probe.worker.js +4 -3
  18. package/dist/history-probe.worker.js.map +1 -1
  19. package/dist/index.d.ts +6 -3
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +2 -1
  22. package/dist/index.js.map +1 -1
  23. package/dist/localdb-port.d.ts +28 -0
  24. package/dist/localdb-port.d.ts.map +1 -0
  25. package/dist/localdb-port.js +30 -0
  26. package/dist/localdb-port.js.map +1 -0
  27. package/dist/mcp-store.d.ts.map +1 -1
  28. package/dist/mcp-store.js +6 -2
  29. package/dist/mcp-store.js.map +1 -1
  30. package/dist/owner-binding.d.ts +5 -0
  31. package/dist/owner-binding.d.ts.map +1 -1
  32. package/dist/owner-binding.js +4 -8
  33. package/dist/owner-binding.js.map +1 -1
  34. package/dist/owner-request.d.ts +16 -0
  35. package/dist/owner-request.d.ts.map +1 -0
  36. package/dist/owner-request.js +37 -0
  37. package/dist/owner-request.js.map +1 -0
  38. package/dist/pdpp-records.d.ts +18 -0
  39. package/dist/pdpp-records.d.ts.map +1 -0
  40. package/dist/pdpp-records.js +105 -0
  41. package/dist/pdpp-records.js.map +1 -0
  42. package/dist/persistence.d.ts +1 -1
  43. package/dist/persistence.d.ts.map +1 -1
  44. package/dist/persistence.js +2 -2
  45. package/dist/persistence.js.map +1 -1
  46. package/dist/personal-server-client.d.ts +32 -0
  47. package/dist/personal-server-client.d.ts.map +1 -0
  48. package/dist/personal-server-client.js +57 -0
  49. package/dist/personal-server-client.js.map +1 -0
  50. package/dist/pull-signals.d.ts +52 -0
  51. package/dist/pull-signals.d.ts.map +1 -0
  52. package/dist/pull-signals.js +142 -0
  53. package/dist/pull-signals.js.map +1 -0
  54. package/dist/relay.d.ts.map +1 -1
  55. package/dist/relay.js +4 -1
  56. package/dist/relay.js.map +1 -1
  57. package/dist/runtime.d.ts +38 -2
  58. package/dist/runtime.d.ts.map +1 -1
  59. package/dist/runtime.js +327 -16
  60. package/dist/runtime.js.map +1 -1
  61. package/dist/seed-staging.d.ts +8 -0
  62. package/dist/seed-staging.d.ts.map +1 -0
  63. package/dist/seed-staging.js +106 -0
  64. package/dist/seed-staging.js.map +1 -0
  65. package/dist/state.d.ts +9 -1
  66. package/dist/state.d.ts.map +1 -1
  67. package/dist/state.js +10 -4
  68. package/dist/state.js.map +1 -1
  69. package/dist/storage-utils.d.ts.map +1 -1
  70. package/dist/storage-utils.js +1 -1
  71. package/dist/storage-utils.js.map +1 -1
  72. package/dist/storage.d.ts +26 -1
  73. package/dist/storage.d.ts.map +1 -1
  74. package/dist/storage.js +226 -109
  75. package/dist/storage.js.map +1 -1
  76. package/dist/stream-sync-budget.d.ts +3 -0
  77. package/dist/stream-sync-budget.d.ts.map +1 -0
  78. package/dist/stream-sync-budget.js +3 -0
  79. package/dist/stream-sync-budget.js.map +1 -0
  80. package/dist/sync.d.ts +82 -2
  81. package/dist/sync.d.ts.map +1 -1
  82. package/dist/sync.js +295 -57
  83. package/dist/sync.js.map +1 -1
  84. package/dist/wasm-stream-crypto.d.ts +20 -0
  85. package/dist/wasm-stream-crypto.d.ts.map +1 -0
  86. package/dist/wasm-stream-crypto.js +53 -0
  87. package/dist/wasm-stream-crypto.js.map +1 -0
  88. package/package.json +10 -3
package/dist/runtime.js CHANGED
@@ -1,20 +1,84 @@
1
+ import { liveStreamCounts } from "@opendatalabs/personal-server-ts-core/stream-sync-read";
2
+ import { RunIntakeError } from "@opendatalabs/personal-server-ts-core/stream-sync";
1
3
  import { importOuraBrowserRecords } from "./oura-import.js";
2
4
  import { withLegacyProjection, } from "@opendatalabs/personal-server-ts-core/storage/legacy-projection";
3
- import { GrantRequiredError, InvalidSignatureError, MissingAuthError, NotOwnerError, ProtocolError, PsUnavailableError, } from "@opendatalabs/personal-server-ts-core/errors";
4
- import { authenticateRequest, } from "@opendatalabs/personal-server-ts-core/auth";
5
+ import { ContentTooLargeError, GrantRequiredError, InvalidSignatureError, MissingAuthError, NotOwnerError, ProtocolError, PsUnavailableError, } from "@opendatalabs/personal-server-ts-core/errors";
6
+ import { authenticateRequest, cacheRequestBodyBytes, } from "@opendatalabs/personal-server-ts-core/auth";
5
7
  import { approveDeviceSessionContract, createMemoryDeviceSessionStore, initiateDeviceSessionContract, pollDeviceSessionContract, provisionDeviceTokenContract, revokeDeviceTokenContract, } from "@opendatalabs/personal-server-ts-core/contracts";
6
- import { handlePersonalServerAccessLogsRequest, handlePersonalServerConfigRequest, handlePersonalServerDataRequest, handlePersonalServerScopeUploadAppend, createScopeUploadRegistry, handleOuraCollectionRequirementsRequest, handlePersonalServerGrantsRequest, handlePersonalServerOauthTokenRequest, handlePersonalServerSyncRequest, } from "@opendatalabs/personal-server-ts-core/api";
8
+ import { accountStorageModeOf, decisionBody, normalizeOwner, parseEvidenceBody, } from "@opendatalabs/personal-server-ts-core/sync/account-mode";
9
+ import { handleOwnerConnectorDelete, handleOwnerConnectorLifetime, handlePersonalServerAccessLogsRequest, handlePersonalServerConfigRequest, handlePersonalServerDataRequest, handlePersonalServerScopeUploadAppend, refuseLegacyWrite, LegacyWriteRefusedError, accountStorageModeFor, createScopeUploadRegistry, handleOuraCollectionRequirementsRequest, handlePersonalServerGrantsRequest, handlePersonalServerOauthTokenRequest, handlePersonalServerSyncRequest, } from "@opendatalabs/personal-server-ts-core/api";
7
10
  import { handlePersonalServerDerivativesRequest, } from "@opendatalabs/personal-server-ts-core/derivatives";
8
11
  import { resolveDataListGrantScopes, verifyDataReadPolicy, } from "@opendatalabs/personal-server-ts-core/policy";
9
12
  import { createInMemoryWriteProofReplayStore, createWriteSessionAuthorization, handleWriteSessionRequest, } from "@opendatalabs/personal-server-ts-core/write";
10
- import { approveMcpOAuthAuthorization, approveMcpOAuthAuthorizationWithScopes, approveMcpConnection, approveMcpScopeAccessRequest, buildMcpProtectedResourceMetadataUrl, buildStableMcpUrl, createInMemoryMcpOAuthAuthorizationStore, createMcpConnection, createMcpOAuthAuthorization, createMcpDataReadClient, denyMcpScopeAccessRequest, handleMcpStreamableHttpRequest, hashConnectionToken, listMcpConnectionViews, loadMcpGranteeAccount, MCP_CONNECTION_NOT_FOUND, MCP_SCOPE_REQUEST_NOT_FOUND, MCP_SCOPE_REQUEST_TOKEN_HEADER, readMcpScopeRequestWithToken, getMcpConnectionView, McpConnectionNotFoundError, McpConnectionStateError, McpOAuthAuthorizationError, isAllowedOAuthRedirectUri, McpScopeRequestError, redeemMcpOAuthAuthorizationCode, refreshMcpOAuthToken, requestMcpScopeAccess, toMcpOAuthAuthorizationView, revokeMcpConnection, toMcpConnectionView, McpActivityRecorder, } from "@opendatalabs/personal-server-ts-core/mcp";
13
+ import { approveMcpOAuthAuthorization, approveMcpOAuthAuthorizationWithScopes, approveMcpConnection, approveMcpScopeAccessRequest, liveMcpGrants, buildMcpProtectedResourceMetadataUrl, buildStableMcpUrl, createInMemoryMcpOAuthAuthorizationStore, createMcpConnection, createMcpOAuthAuthorization, createMcpDataReadClient, McpDataWriteError, denyMcpScopeAccessRequest, handleMcpStreamableHttpRequest, hashConnectionToken, listMcpConnectionViews, loadMcpGranteeAccount, MCP_CONNECTION_NOT_FOUND, MCP_SCOPE_REQUEST_NOT_FOUND, MCP_SCOPE_REQUEST_TOKEN_HEADER, McpInvalidScopeError, readMcpScopeRequestWithToken, getMcpConnectionView, McpConnectionNotFoundError, McpConnectionStateError, McpOAuthAuthorizationError, isAllowedOAuthRedirectUri, McpScopeRequestError, redeemMcpOAuthAuthorizationCode, refreshMcpOAuthToken, requestMcpScopeAccess, toMcpOAuthAuthorizationView, revokeMcpConnection, toMcpConnectionView, McpActivityRecorder, } from "@opendatalabs/personal-server-ts-core/mcp";
14
+ import { startPullSignals, startVisibilityPause } from "./pull-signals.js";
11
15
  import { createDefaultPsLiteAccessLogStore, createDefaultPsLiteSaveConfig, createDefaultPsLiteTokenStore, } from "./state.js";
16
+ import { handleLitePdppRecordList } from "./pdpp-records.js";
12
17
  import { collectDiagnosticsWithTimeout, DiagnosticsRecorder, } from "./diagnostics.js";
13
18
  function jsonResponse(body, init) {
14
19
  const headers = new Headers(init?.headers);
15
20
  headers.set("Content-Type", "application/json");
16
21
  return new Response(JSON.stringify(body), { ...init, headers });
17
22
  }
23
+ /**
24
+ * A mode answer: the decision body, with a refusal's own HTTP status. A 503 is
25
+ * retryable and says when to ask again.
26
+ */
27
+ function decisionResponse(decision) {
28
+ const refused = decision.kind === "refuse";
29
+ return jsonResponse(decisionBody(decision), {
30
+ status: refused ? decision.status : 200,
31
+ ...(refused && decision.status === 503
32
+ ? { headers: { "Retry-After": MODE_RETRY_AFTER_SECONDS } }
33
+ : {}),
34
+ });
35
+ }
36
+ // The mode routes take small bodies, as on the Node server: at most 16 KiB
37
+ // (413 above it, sized or chunked), a flat object of at most 8 plain values,
38
+ // and an owner of at most 100 characters (400 otherwise).
39
+ const MODE_BODY_MAX_BYTES = 16 * 1024;
40
+ const MODE_BODY_MAX_KEYS = 8;
41
+ const MODE_OWNER_MAX_LENGTH = 100;
42
+ const MODE_RETRY_AFTER_SECONDS = "5";
43
+ const BODY_TOO_LARGE = Symbol("body too large");
44
+ /** The request's flat JSON object, null when it is not one, or too large. */
45
+ async function readModeBody(request) {
46
+ if (Number(request.headers.get("content-length")) > MODE_BODY_MAX_BYTES) {
47
+ return BODY_TOO_LARGE;
48
+ }
49
+ let parsed;
50
+ try {
51
+ const bytes = await cacheRequestBodyBytes(request, MODE_BODY_MAX_BYTES, true);
52
+ if (bytes && bytes.byteLength > MODE_BODY_MAX_BYTES)
53
+ return BODY_TOO_LARGE;
54
+ parsed = JSON.parse(new TextDecoder().decode(bytes));
55
+ }
56
+ catch (error) {
57
+ if (error instanceof ContentTooLargeError)
58
+ return BODY_TOO_LARGE;
59
+ if (error instanceof SyntaxError)
60
+ return null;
61
+ throw error;
62
+ }
63
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
64
+ return null;
65
+ }
66
+ const values = Object.values(parsed);
67
+ if (values.length > MODE_BODY_MAX_KEYS)
68
+ return null;
69
+ if (values.some((v) => v !== null && typeof v === "object"))
70
+ return null;
71
+ return parsed;
72
+ }
73
+ function modeBodyRefusal(body, code, shape) {
74
+ if (body === BODY_TOO_LARGE) {
75
+ return jsonResponse({
76
+ error: "CONTENT_TOO_LARGE",
77
+ message: `Request body exceeds maximum size of ${MODE_BODY_MAX_BYTES} bytes`,
78
+ }, { status: 413 });
79
+ }
80
+ return body ? null : errorResponse(400, code, shape);
81
+ }
18
82
  function protocolErrorResponse(err) {
19
83
  return jsonResponse(err.toJSON(), { status: err.code });
20
84
  }
@@ -340,6 +404,8 @@ function warnLegacyProjectionIssue(issue) {
340
404
  }
341
405
  export function createPsLiteRuntime(options) {
342
406
  let active = options.active ?? false;
407
+ // Page signals start a pull while the runtime is active (D4-SYNC-TRIGGERS).
408
+ let stopPullSignals;
343
409
  const now = options.now ?? (() => new Date());
344
410
  const auth = options.auth ?? createMissingAuthAdapter();
345
411
  // Readers get legacy bodies projected from stored PDPP records; writes and
@@ -363,6 +429,25 @@ export function createPsLiteRuntime(options) {
363
429
  accessLogReader ??= accessLogStore;
364
430
  accessLogWriter ??= accessLogStore;
365
431
  }
432
+ if (options.localSync) {
433
+ const legacyReader = accessLogReader;
434
+ accessLogReader = {
435
+ read: async (page) => {
436
+ if (accountStorageMode.read() === "switched")
437
+ return (await options.localSync()).accessActivity.read(page);
438
+ return legacyReader.read(page);
439
+ },
440
+ };
441
+ const fallback = accessLogWriter;
442
+ accessLogWriter = {
443
+ write: async (entry) => {
444
+ if (accountStorageMode.read() === "switched")
445
+ await (await options.localSync()).accessActivity.write(entry);
446
+ else
447
+ await fallback.write(entry);
448
+ },
449
+ };
450
+ }
366
451
  const tokenStore = options.tokenStore ?? createDefaultPsLiteTokenStore();
367
452
  const saveConfig = options.saveConfig ?? createDefaultPsLiteSaveConfig();
368
453
  // The gateway client (options.gateway) and the server signer are built ONCE
@@ -418,6 +503,40 @@ export function createPsLiteRuntime(options) {
418
503
  function ownerAddress() {
419
504
  return options.serverOwner ?? options.identity?.address;
420
505
  }
506
+ // The owner the account mode is bound to: the person's owner only, as on the
507
+ // Node server. The server identity is never a substitute.
508
+ function modeOwner() {
509
+ return options.serverOwner;
510
+ }
511
+ function modeMethodNotAllowed() {
512
+ return jsonResponse({
513
+ error: {
514
+ code: 405,
515
+ errorCode: "METHOD_NOT_ALLOWED",
516
+ message: "Method not allowed",
517
+ },
518
+ }, { status: 405, headers: { Allow: "POST" } });
519
+ }
520
+ /** A refusal unless the body's owner is the runtime's mode owner. */
521
+ function modeOwnerRefusal(owner) {
522
+ if (typeof owner !== "string" || owner.length > MODE_OWNER_MAX_LENGTH) {
523
+ return errorResponse(400, "INVALID_ACCOUNT_MODE_OWNER", "Body owner must be a string of at most 100 characters");
524
+ }
525
+ const bound = modeOwner();
526
+ if (bound === undefined ||
527
+ normalizeOwner(owner) !== normalizeOwner(bound)) {
528
+ return errorResponse(403, "ACCOUNT_MODE_OWNER_MISMATCH", "This server only takes account mode for its own owner");
529
+ }
530
+ return null;
531
+ }
532
+ // The host's mode, bound once to this runtime's owner. Every consumer below
533
+ // (scope-upload append, the data handler, Oura, every MCP engine) receives
534
+ // this bound view, which cannot be asked about another account. The mode
535
+ // answers `unknown` when it is bound to a different owner or this runtime
536
+ // has none.
537
+ const accountStorageMode = accountStorageModeFor(options.accountModeAuthority
538
+ ? accountStorageModeOf(options.accountModeAuthority)
539
+ : { read: () => "unknown" }, modeOwner());
421
540
  async function handleAuthDevice(request, url) {
422
541
  if (url.pathname === "/auth/device") {
423
542
  if (request.method !== "POST") {
@@ -521,15 +640,43 @@ export function createPsLiteRuntime(options) {
521
640
  }
522
641
  return {
523
642
  kind: "ps-lite",
643
+ streamSyncSeed: options.streamSyncSeed ?? null,
524
644
  storage: options.storage,
525
645
  activate() {
526
646
  active = true;
647
+ stopPullSignals?.();
527
648
  options.syncManager?.start?.();
649
+ const manager = options.syncManager;
650
+ // Hides pause the manager; shows resume it, then the pull below probes.
651
+ const requestPull = () => {
652
+ manager?.requestPull?.().catch(() => undefined);
653
+ };
654
+ const stopVisibility = manager
655
+ ? options.activity
656
+ ? startVisibilityPause(manager, {
657
+ activity: options.activity,
658
+ onActive: requestPull,
659
+ })
660
+ : startVisibilityPause(manager)
661
+ : undefined;
662
+ const stopPulls = manager?.requestPull
663
+ ? startPullSignals(requestPull)
664
+ : undefined;
665
+ stopPullSignals = () => {
666
+ try {
667
+ stopVisibility?.();
668
+ }
669
+ finally {
670
+ stopPulls?.();
671
+ }
672
+ };
528
673
  options.derivatives?.scheduler.start();
529
674
  options.replication?.resume();
530
675
  },
531
676
  deactivate() {
532
677
  active = false;
678
+ stopPullSignals?.();
679
+ stopPullSignals = undefined;
533
680
  void options.syncManager?.stop?.();
534
681
  options.derivatives?.scheduler.stop();
535
682
  void options.replication?.pause();
@@ -542,7 +689,13 @@ export function createPsLiteRuntime(options) {
542
689
  async appendScopeUpload(request, batch) {
543
690
  if (!active)
544
691
  return unavailableResponse();
545
- return handlePersonalServerScopeUploadAppend(request, { storage: dataStorage, auth, accessLogWriter, scopeUploads }, batch);
692
+ return handlePersonalServerScopeUploadAppend(request, {
693
+ storage: dataStorage,
694
+ auth,
695
+ accessLogWriter,
696
+ scopeUploads,
697
+ accountStorageMode,
698
+ }, batch);
546
699
  },
547
700
  }
548
701
  : {}),
@@ -553,7 +706,9 @@ export function createPsLiteRuntime(options) {
553
706
  const apiOrigin = url.origin;
554
707
  const identity = options.identity ?? null;
555
708
  let serverId = null;
556
- if (identity && options.gateway) {
709
+ if (identity &&
710
+ options.gateway &&
711
+ url.searchParams.get("registration") !== "skip") {
557
712
  try {
558
713
  const server = await options.gateway.getServer(identity.address);
559
714
  serverId = server?.id ?? null;
@@ -632,9 +787,55 @@ export function createPsLiteRuntime(options) {
632
787
  await auth.authorizeOwner(request);
633
788
  return jsonResponse(options.replication?.status() ?? { state: "off" });
634
789
  }
790
+ // Account-mode answers do not wait for activation: a host submits the
791
+ // first Off or On, and only then starts the workers that depend on it.
792
+ if (url.pathname === "/v1/account-mode/evidence" &&
793
+ options.accountModeAuthority) {
794
+ if (request.method !== "POST")
795
+ return modeMethodNotAllowed();
796
+ await auth.authorizeOwner(request);
797
+ const raw = await readModeBody(request);
798
+ const bad = modeBodyRefusal(raw, "INVALID_ACCOUNT_MODE_BODY", "Body must be a flat JSON object");
799
+ if (bad)
800
+ return bad;
801
+ const mismatch = modeOwnerRefusal(raw.owner);
802
+ if (mismatch)
803
+ return mismatch;
804
+ const body = parseEvidenceBody(raw);
805
+ if (!body) {
806
+ return errorResponse(400, "INVALID_ACCOUNT_MODE_EVIDENCE", "Body must be {owner, state, generation?} or {owner, rawStatus, streamSync?, generation?}");
807
+ }
808
+ // authorizeOwner succeeded, so the caller is this runtime's owner,
809
+ // and so is the body's.
810
+ return decisionResponse(await options.accountModeAuthority.submitEvidence(body));
811
+ }
635
812
  if (!active) {
636
813
  return unavailableResponse();
637
814
  }
815
+ const connectorPath = /^\/v1\/owner\/connectors\/([^/]+)$/.exec(url.pathname);
816
+ if (connectorPath) {
817
+ if (request.method !== "DELETE" && request.method !== "GET") {
818
+ // Owner first: a caller who is not the owner learns nothing of the route.
819
+ await auth.authorizeOwner(request);
820
+ return errorResponse(405, "METHOD_NOT_ALLOWED", "Method not allowed");
821
+ }
822
+ let connectorId;
823
+ try {
824
+ connectorId = decodeURIComponent(connectorPath[1]);
825
+ }
826
+ catch {
827
+ // A malformed percent-escape is a bad id (400 after authorization).
828
+ connectorId = null;
829
+ }
830
+ const connectorDeps = {
831
+ authorizeOwner: (req) => auth.authorizeOwner(req),
832
+ mode: accountStorageMode,
833
+ connectionDelete: options.streamSyncConnectionDelete,
834
+ };
835
+ return request.method === "GET"
836
+ ? handleOwnerConnectorLifetime(request, connectorId, connectorDeps)
837
+ : handleOwnerConnectorDelete(request, connectorId, connectorDeps);
838
+ }
638
839
  if (url.pathname === "/v1/replication/sync") {
639
840
  if (request.method !== "POST")
640
841
  return errorResponse(405, "METHOD_NOT_ALLOWED", "Method not allowed");
@@ -664,6 +865,13 @@ export function createPsLiteRuntime(options) {
664
865
  await auth.authorizeOwner(request);
665
866
  if (request.method !== "POST")
666
867
  return errorResponse(405, "METHOD_NOT_ALLOWED", "Method not allowed");
868
+ // An Oura browser import is a legacy write: a switched account refuses
869
+ // it. This is the early refusal; each stream the import stores is a
870
+ // storage write that passes the storage's seal on its own, so an
871
+ // account that switches mid-batch stops at the next stream.
872
+ const refusal = refuseLegacyWrite(accountStorageMode);
873
+ if (refusal)
874
+ return refusal;
667
875
  let body;
668
876
  try {
669
877
  body = await request.json();
@@ -671,15 +879,34 @@ export function createPsLiteRuntime(options) {
671
879
  catch {
672
880
  return errorResponse(400, "INVALID_BODY", "Body must be JSON");
673
881
  }
674
- const result = await importOuraBrowserRecords(toDataStoragePort(options.storage), body, {
675
- additions: options.additions,
676
- scopeDeletions: options.scopeDeletions,
677
- syncManager: options.syncManager ?? null,
678
- onDataWritten: options.derivatives
679
- ? (event) => options.derivatives?.scheduler.markSourceChanged(event.scope, { lineageSources: event.lineageSources })
680
- : undefined,
882
+ try {
883
+ const result = await importOuraBrowserRecords(toDataStoragePort(options.storage), body, {
884
+ accountStorageMode,
885
+ additions: options.additions,
886
+ scopeDeletions: options.scopeDeletions,
887
+ syncManager: options.syncManager ?? null,
888
+ onDataWritten: options.derivatives
889
+ ? (event) => options.derivatives?.scheduler.markSourceChanged(event.scope, { lineageSources: event.lineageSources })
890
+ : undefined,
891
+ });
892
+ return jsonResponse(result, { status: result.ok ? 200 : 409 });
893
+ }
894
+ catch (error) {
895
+ if (error instanceof LegacyWriteRefusedError)
896
+ return error.response;
897
+ throw error;
898
+ }
899
+ }
900
+ const pdppRecords = /^\/v1\/streams\/([^/]+)\/records$/.exec(url.pathname);
901
+ if (pdppRecords && options.localSync) {
902
+ if (request.method !== "GET")
903
+ return errorResponse(405, "METHOD_NOT_ALLOWED", "Method not allowed");
904
+ return handleLitePdppRecordList(request, decodeURIComponent(pdppRecords[1]), {
905
+ localSync: options.localSync,
906
+ accountStorageMode,
907
+ authorizeOwner: (req) => auth.authorizeOwner(req),
908
+ ownerAddress,
681
909
  });
682
- return jsonResponse(result, { status: result.ok ? 200 : 409 });
683
910
  }
684
911
  const dataPrefix = "/v1/data";
685
912
  if (url.pathname === dataPrefix ||
@@ -687,6 +914,7 @@ export function createPsLiteRuntime(options) {
687
914
  const x402 = resolveX402Settings(options.config, boundGatewayConfig);
688
915
  return handlePersonalServerDataRequest(request, {
689
916
  storage: dataStorage,
917
+ accountStorageMode,
690
918
  auth,
691
919
  logger: options.logger,
692
920
  accessLogWriter,
@@ -694,6 +922,8 @@ export function createPsLiteRuntime(options) {
694
922
  additions: options.additions,
695
923
  syncManager: options.syncManager ?? null,
696
924
  scopeDeletions: options.scopeDeletions,
925
+ streamSyncRead: options.streamSyncRead,
926
+ history: options.history,
697
927
  scopeUploads,
698
928
  now,
699
929
  createLogId,
@@ -806,7 +1036,50 @@ export function createPsLiteRuntime(options) {
806
1036
  url.pathname === `${accessLogsPrefix}/`) {
807
1037
  return handlePersonalServerAccessLogsRequest(request, { auth, accessLogReader }, { basePath: accessLogsPrefix });
808
1038
  }
1039
+ if (url.pathname === "/v1/stream-sync/read-status" &&
1040
+ options.localSync) {
1041
+ await auth.authorizeOwner(request);
1042
+ if (request.method !== "GET")
1043
+ return errorResponse(405, "METHOD_NOT_ALLOWED", "Method not allowed");
1044
+ const local = await options.localSync();
1045
+ const status = await local.listing.status();
1046
+ return jsonResponse({
1047
+ listed: status.listed,
1048
+ streams: liveStreamCounts(status),
1049
+ issues: status.issues.length,
1050
+ });
1051
+ }
1052
+ // Whether a run is saved: `GET /v1/stream-sync/runs/:runId/publication`.
1053
+ // `superseded` alone does not mean saved; a consumer must check `reason`.
1054
+ const runPublication = /^\/v1\/stream-sync\/runs\/([A-Za-z0-9._-]{1,128})\/publication$/.exec(url.pathname);
1055
+ if (runPublication && options.localSync) {
1056
+ await auth.authorizeOwner(request);
1057
+ if (request.method !== "GET")
1058
+ return errorResponse(405, "METHOD_NOT_ALLOWED", "Method not allowed");
1059
+ // Bind to the runtime's owner: a run written under another owner
1060
+ // answers 404, the same as an unknown run, so it is not revealed.
1061
+ const owner = ownerAddress();
1062
+ if (!owner)
1063
+ return errorResponse(404, "RUN_NOT_FOUND", "Run not found");
1064
+ try {
1065
+ return jsonResponse(await (await options.localSync()).intake.publicationStatus(runPublication[1], { owner }));
1066
+ }
1067
+ catch (err) {
1068
+ if (err instanceof RunIntakeError &&
1069
+ (err.code === "gone" || err.code === "owner_mismatch"))
1070
+ return errorResponse(404, "RUN_NOT_FOUND", "Run not found");
1071
+ throw err;
1072
+ }
1073
+ }
809
1074
  const syncPrefix = "/v1/sync";
1075
+ if (url.pathname === `${syncPrefix}/status` &&
1076
+ options.localSync &&
1077
+ accountStorageMode.read() !== "unswitched") {
1078
+ await auth.authorizeOwner(request);
1079
+ if (request.method !== "GET")
1080
+ return errorResponse(405, "METHOD_NOT_ALLOWED", "Method not allowed");
1081
+ return jsonResponse(await (await options.localSync()).listing.status());
1082
+ }
810
1083
  if (url.pathname === `${syncPrefix}/trigger` ||
811
1084
  url.pathname === `${syncPrefix}/status` ||
812
1085
  url.pathname.startsWith(`${syncPrefix}/file/`)) {
@@ -844,8 +1117,12 @@ export function createPsLiteRuntime(options) {
844
1117
  authorizationStore: mcpOAuthAuthorizationStore,
845
1118
  approvalUrl: options.mcpOAuthApprovalUrl,
846
1119
  scopeRequestApprovalUrl: options.mcpScopeRequestApprovalUrl,
1120
+ exposeUnsharedScopes: options.mcpExposeUnsharedScopes,
1121
+ scopeRequestGuidance: options.mcpScopeRequestGuidance,
847
1122
  auth,
848
1123
  dataStorage,
1124
+ streamSyncRead: options.streamSyncRead,
1125
+ accountStorageMode,
849
1126
  accessLogWriter,
850
1127
  readFulfillmentReporter: options.readFulfillmentReporter,
851
1128
  now,
@@ -1120,7 +1397,7 @@ async function handleMcpRoute(input) {
1120
1397
  const view = await readMcpScopeRequestWithToken({
1121
1398
  connectionId,
1122
1399
  token: input.request.headers.get(MCP_SCOPE_REQUEST_TOKEN_HEADER),
1123
- }, { store: input.store, now: input.now });
1400
+ }, { store: input.store, gateway: input.gateway, now: input.now });
1124
1401
  if (!view) {
1125
1402
  const notFound = errorResponse(404, MCP_SCOPE_REQUEST_NOT_FOUND, "Scope request not found");
1126
1403
  notFound.headers.set("Cache-Control", "no-store");
@@ -1204,6 +1481,9 @@ async function handleMcpRoute(input) {
1204
1481
  if (err instanceof McpConnectionStateError) {
1205
1482
  return errorResponse(409, "INVALID_STATE", err.message);
1206
1483
  }
1484
+ if (err instanceof McpInvalidScopeError) {
1485
+ return errorResponse(400, err.code, err.message);
1486
+ }
1207
1487
  throw err;
1208
1488
  }
1209
1489
  }
@@ -1328,11 +1608,26 @@ async function handleMcpRoute(input) {
1328
1608
  publicKey: record.granteePublicKey,
1329
1609
  encryptedPrivateKey: record.encryptedGranteePrivateKey,
1330
1610
  });
1611
+ const mode = input.accountStorageMode?.read() ?? "unknown";
1612
+ const storage = mode === "unswitched"
1613
+ ? input.dataStorage
1614
+ : new Proxy({}, {
1615
+ get() {
1616
+ return () => {
1617
+ throw new ProtocolError(503, "STREAM_SYNC_LEGACY_STORAGE", "Legacy storage is sealed for this account mode");
1618
+ };
1619
+ },
1620
+ });
1331
1621
  const readClient = createMcpDataReadClient({
1332
1622
  serverOrigin: input.serverOrigin,
1333
1623
  granteeAccount,
1334
1624
  dataApiDeps: {
1335
- storage: input.dataStorage,
1625
+ storage,
1626
+ streamSyncRead: mode === "switched" ? input.streamSyncRead : undefined,
1627
+ accountStorageMode: {
1628
+ owner: input.accountStorageMode?.owner ?? input.serverOwner ?? "",
1629
+ read: () => mode,
1630
+ },
1336
1631
  auth: input.auth,
1337
1632
  accessLogWriter: input.accessLogWriter,
1338
1633
  readFulfillmentReporter: input.readFulfillmentReporter,
@@ -1344,11 +1639,27 @@ async function handleMcpRoute(input) {
1344
1639
  const response = await handleMcpStreamableHttpRequest(input.request, {
1345
1640
  connection: record,
1346
1641
  readClient,
1642
+ writeClient: mode === "switched"
1643
+ ? {
1644
+ async updateScope() {
1645
+ throw new McpDataWriteError(409, {
1646
+ error: {
1647
+ code: 409,
1648
+ errorCode: "STREAM_SYNC_WRITE_UNAVAILABLE",
1649
+ message: "Memory writes are not available through stream sync",
1650
+ },
1651
+ });
1652
+ },
1653
+ }
1654
+ : undefined,
1347
1655
  activityRecorder: input.activityRecorder,
1348
1656
  requestScopeAccess: async (request) => {
1349
1657
  return requestMcpScopeAccess({ connectionId: record.id, ...request }, { store: input.store, now: input.now });
1350
1658
  },
1351
1659
  scopeRequestApprovalUrl: input.scopeRequestApprovalUrl,
1660
+ exposeUnsharedScopes: input.exposeUnsharedScopes,
1661
+ verifyGrantsLive: () => liveMcpGrants(record, input.gateway, input.now),
1662
+ scopeRequestGuidance: input.scopeRequestGuidance,
1352
1663
  serverOrigin: input.serverOrigin,
1353
1664
  });
1354
1665
  void input.store